blob: 7d13398e929713396e023b7636f6023f46c81ea4 [file] [log] [blame]
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001# -*- coding: iso-8859-15 -*-
Lars Gustäbelc64e4022007-03-13 10:47:19 +00002
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00003import sys
Serhiy Storchakae7829bd2014-07-16 23:58:12 +03004import io
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00005import os
6import shutil
Georg Brandl38c6a222006-05-10 16:26:03 +00007import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00008from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00009import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000010
11import unittest
12import tarfile
13
14from test import test_support
15
16# Check for our compression modules.
17try:
18 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000019 gzip.GzipFile
20except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000021 gzip = None
22try:
23 import bz2
24except ImportError:
25 bz2 = None
26
Lars Gustäbelc64e4022007-03-13 10:47:19 +000027def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000028 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000029
Antoine Pitrou310c9fe2009-11-11 20:55:07 +000030TEMPDIR = os.path.abspath(test_support.TESTFN)
31tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000032gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
33bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
34tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000035
Lars Gustäbelc64e4022007-03-13 10:47:19 +000036md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
37md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000038
39
Lars Gustäbelc64e4022007-03-13 10:47:19 +000040class ReadTest(unittest.TestCase):
41
42 tarname = tarname
43 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000044
45 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000046 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000047
48 def tearDown(self):
49 self.tar.close()
50
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000051
Lars Gustäbelc64e4022007-03-13 10:47:19 +000052class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000053
Lars Gustäbelc64e4022007-03-13 10:47:19 +000054 def test_fileobj_regular_file(self):
55 tarinfo = self.tar.getmember("ustar/regtype")
56 fobj = self.tar.extractfile(tarinfo)
57 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000058 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000059 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000060
Lars Gustäbelc64e4022007-03-13 10:47:19 +000061 def test_fileobj_readlines(self):
62 self.tar.extract("ustar/regtype", TEMPDIR)
63 tarinfo = self.tar.getmember("ustar/regtype")
64 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
65 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000066
Lars Gustäbelc64e4022007-03-13 10:47:19 +000067 lines1 = fobj1.readlines()
68 lines2 = fobj2.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000069 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000070 "fileobj.readlines() failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000071 self.assertTrue(len(lines2) == 114,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000072 "fileobj.readlines() failed")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +000073 self.assertTrue(lines2[83] ==
Lars Gustäbelc64e4022007-03-13 10:47:19 +000074 "I will gladly admit that Python is not the fastest running scripting language.\n",
75 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000076
Lars Gustäbelc64e4022007-03-13 10:47:19 +000077 def test_fileobj_iter(self):
78 self.tar.extract("ustar/regtype", TEMPDIR)
79 tarinfo = self.tar.getmember("ustar/regtype")
80 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
81 fobj2 = self.tar.extractfile(tarinfo)
82 lines1 = fobj1.readlines()
83 lines2 = [line for line in fobj2]
Benjamin Peterson5c8da862009-06-30 22:57:08 +000084 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000085 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000086
Lars Gustäbelc64e4022007-03-13 10:47:19 +000087 def test_fileobj_seek(self):
88 self.tar.extract("ustar/regtype", TEMPDIR)
89 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
90 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000091 fobj.close()
92
Lars Gustäbelc64e4022007-03-13 10:47:19 +000093 tarinfo = self.tar.getmember("ustar/regtype")
94 fobj = self.tar.extractfile(tarinfo)
95
96 text = fobj.read()
97 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000098 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000099 "seek() to file's start failed")
100 fobj.seek(2048, 0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000101 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000102 "seek() to absolute position failed")
103 fobj.seek(-1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000104 self.assertTrue(1024 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000105 "seek() to negative relative position failed")
106 fobj.seek(1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000107 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000108 "seek() to positive relative position failed")
109 s = fobj.read(10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000110 self.assertTrue(s == data[2048:2058],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000111 "read() after seek failed")
112 fobj.seek(0, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000113 self.assertTrue(tarinfo.size == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000114 "seek() to file's end failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000115 self.assertTrue(fobj.read() == "",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000116 "read() at file's end did not return empty string")
117 fobj.seek(-tarinfo.size, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000118 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000119 "relative seek() to file's start failed")
120 fobj.seek(512)
121 s1 = fobj.readlines()
122 fobj.seek(512)
123 s2 = fobj.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000124 self.assertTrue(s1 == s2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000125 "readlines() after seek failed")
126 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000127 self.assertTrue(len(fobj.readline()) == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000128 "tell() after readline() failed")
129 fobj.seek(512)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000130 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000131 "tell() after seek() and readline() failed")
132 fobj.seek(0)
133 line = fobj.readline()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000134 self.assertTrue(fobj.read() == data[len(line):],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000135 "read() after readline() failed")
136 fobj.close()
137
Lars Gustäbel4da7d412010-06-03 12:34:14 +0000138 # Test if symbolic and hard links are resolved by extractfile(). The
139 # test link members each point to a regular member whose data is
140 # supposed to be exported.
141 def _test_fileobj_link(self, lnktype, regtype):
142 a = self.tar.extractfile(lnktype)
143 b = self.tar.extractfile(regtype)
144 self.assertEqual(a.name, b.name)
145
146 def test_fileobj_link1(self):
147 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
148
149 def test_fileobj_link2(self):
150 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
151
152 def test_fileobj_symlink1(self):
153 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
154
155 def test_fileobj_symlink2(self):
156 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
157
Lars Gustäbel231d4742012-04-24 22:42:08 +0200158 def test_issue14160(self):
159 self._test_fileobj_link("symtype2", "ustar/regtype")
160
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000161
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +0200162class ListTest(ReadTest, unittest.TestCase):
163
164 # Override setUp to use default encoding (UTF-8)
165 def setUp(self):
166 self.tar = tarfile.open(self.tarname, mode=self.mode)
167
168 def test_list(self):
169 with test_support.captured_stdout() as t:
170 self.tar.list(verbose=False)
171 out = t.getvalue()
172 self.assertIn('ustar/conttype', out)
173 self.assertIn('ustar/regtype', out)
174 self.assertIn('ustar/lnktype', out)
175 self.assertIn('ustar' + ('/12345' * 40) + '67/longname', out)
176 self.assertIn('./ustar/linktest2/symtype', out)
177 self.assertIn('./ustar/linktest2/lnktype', out)
178 # Make sure it puts trailing slash for directory
179 self.assertIn('ustar/dirtype/', out)
180 self.assertIn('ustar/dirtype-with-size/', out)
181 # Make sure it is able to print non-ASCII characters
182 self.assertIn('ustar/umlauts-'
183 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
184 self.assertIn('misc/regtype-hpux-signed-chksum-'
185 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
186 self.assertIn('misc/regtype-old-v7-signed-chksum-'
187 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
188 # Make sure it prints files separated by one newline without any
189 # 'ls -l'-like accessories if verbose flag is not being used
190 # ...
191 # ustar/conttype
192 # ustar/regtype
193 # ...
194 self.assertRegexpMatches(out, r'ustar/conttype ?\r?\n'
195 r'ustar/regtype ?\r?\n')
196 # Make sure it does not print the source of link without verbose flag
197 self.assertNotIn('link to', out)
198 self.assertNotIn('->', out)
199
200 def test_list_verbose(self):
201 with test_support.captured_stdout() as t:
202 self.tar.list(verbose=True)
203 out = t.getvalue()
204 # Make sure it prints files separated by one newline with 'ls -l'-like
205 # accessories if verbose flag is being used
206 # ...
207 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
208 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
209 # ...
210 self.assertRegexpMatches(out, (r'-rw-r--r-- tarfile/tarfile\s+7011 '
211 r'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
212 r'ustar/\w+type ?\r?\n') * 2)
213 # Make sure it prints the source of link with verbose flag
214 self.assertIn('ustar/symtype -> regtype', out)
215 self.assertIn('./ustar/linktest2/symtype -> ../linktest1/regtype', out)
216 self.assertIn('./ustar/linktest2/lnktype link to '
217 './ustar/linktest1/regtype', out)
218 self.assertIn('gnu' + ('/123' * 125) + '/longlink link to gnu' +
219 ('/123' * 125) + '/longname', out)
220 self.assertIn('pax' + ('/123' * 125) + '/longlink link to pax' +
221 ('/123' * 125) + '/longname', out)
222
223
224class GzipListTest(ListTest):
225 tarname = gzipname
226 mode = "r:gz"
227 taropen = tarfile.TarFile.gzopen
228
229
230class Bz2ListTest(ListTest):
231 tarname = bz2name
232 mode = "r:bz2"
233 taropen = tarfile.TarFile.bz2open
234
235
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000236class CommonReadTest(ReadTest):
237
238 def test_empty_tarfile(self):
239 # Test for issue6123: Allow opening empty archives.
240 # This test checks if tarfile.open() is able to open an empty tar
241 # archive successfully. Note that an empty tar archive is not the
242 # same as an empty file!
243 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
244 try:
245 tar = tarfile.open(tmpname, self.mode)
246 tar.getnames()
247 except tarfile.ReadError:
248 self.fail("tarfile.open() failed on empty archive")
249 self.assertListEqual(tar.getmembers(), [])
250
251 def test_null_tarfile(self):
252 # Test for issue6123: Allow opening empty archives.
253 # This test guarantees that tarfile.open() does not treat an empty
254 # file as an empty tar archive.
255 open(tmpname, "wb").close()
256 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
257 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
258
Serhiy Storchakad804f532014-01-13 19:08:51 +0200259 def test_non_existent_tarfile(self):
260 # Test for issue11513: prevent non-existent gzipped tarfiles raising
261 # multiple exceptions.
262 exctype = OSError if '|' in self.mode else IOError
263 with self.assertRaisesRegexp(exctype, "xxx") as ex:
264 tarfile.open("xxx", self.mode)
265 self.assertEqual(ex.exception.errno, errno.ENOENT)
266
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000267 def test_ignore_zeros(self):
268 # Test TarFile's ignore_zeros option.
269 if self.mode.endswith(":gz"):
270 _open = gzip.GzipFile
271 elif self.mode.endswith(":bz2"):
272 _open = bz2.BZ2File
273 else:
274 _open = open
275
276 for char in ('\0', 'a'):
277 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
278 # are ignored correctly.
279 fobj = _open(tmpname, "wb")
280 fobj.write(char * 1024)
281 fobj.write(tarfile.TarInfo("foo").tobuf())
282 fobj.close()
283
284 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
285 self.assertListEqual(tar.getnames(), ["foo"],
286 "ignore_zeros=True should have skipped the %r-blocks" % char)
287 tar.close()
288
289
290class MiscReadTest(CommonReadTest):
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200291 taropen = tarfile.TarFile.taropen
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000292
Serhiy Storchakae7829bd2014-07-16 23:58:12 +0300293 def requires_name_attribute(self):
294 pass
295
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000296 def test_no_name_argument(self):
Serhiy Storchakae7829bd2014-07-16 23:58:12 +0300297 self.requires_name_attribute()
298 with open(self.tarname, "rb") as fobj:
299 self.assertIsInstance(fobj.name, str)
300 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
301 self.assertIsInstance(tar.name, str)
302 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000303
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000304 def test_no_name_attribute(self):
305 data = open(self.tarname, "rb").read()
306 fobj = StringIO.StringIO(data)
307 self.assertRaises(AttributeError, getattr, fobj, "name")
308 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchakae7829bd2014-07-16 23:58:12 +0300309 self.assertIsNone(tar.name)
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000310
311 def test_empty_name_attribute(self):
312 data = open(self.tarname, "rb").read()
313 fobj = StringIO.StringIO(data)
314 fobj.name = ""
315 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchakae7829bd2014-07-16 23:58:12 +0300316 self.assertIsNone(tar.name)
317
318 def test_int_name_attribute(self):
319 # Issue 21044: tarfile.open() should handle fileobj with an integer
320 # 'name' attribute.
321 fd = os.open(self.tarname, os.O_RDONLY)
322 with io.open(fd, 'rb') as fobj:
323 self.assertIsInstance(fobj.name, int)
324 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
325 self.assertIsNone(tar.name)
326
327 @test_support.requires_unicode
328 def test_unicode_name_attribute(self):
329 self.requires_name_attribute()
330 tarname = unicode(self.tarname, test_support.TESTFN_ENCODING)
331 with io.open(tarname, 'rb') as fobj:
332 self.assertIsInstance(fobj.name, unicode)
333 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
334 self.assertIsInstance(tar.name, unicode)
335 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000336
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200337 def test_illegal_mode_arg(self):
338 with open(tmpname, 'wb'):
339 pass
340 self.addCleanup(os.unlink, tmpname)
341 with self.assertRaisesRegexp(ValueError, 'mode must be '):
342 tar = self.taropen(tmpname, 'q')
343 with self.assertRaisesRegexp(ValueError, 'mode must be '):
344 tar = self.taropen(tmpname, 'rw')
345 with self.assertRaisesRegexp(ValueError, 'mode must be '):
346 tar = self.taropen(tmpname, '')
347
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000348 def test_fileobj_with_offset(self):
349 # Skip the first member and store values from the second member
350 # of the testtar.
351 tar = tarfile.open(self.tarname, mode=self.mode)
352 tar.next()
353 t = tar.next()
354 name = t.name
355 offset = t.offset
356 data = tar.extractfile(t).read()
357 tar.close()
358
359 # Open the testtar and seek to the offset of the second member.
360 if self.mode.endswith(":gz"):
361 _open = gzip.GzipFile
362 elif self.mode.endswith(":bz2"):
363 _open = bz2.BZ2File
364 else:
365 _open = open
366 fobj = _open(self.tarname, "rb")
367 fobj.seek(offset)
368
369 # Test if the tarfile starts with the second member.
370 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
371 t = tar.next()
372 self.assertEqual(t.name, name)
373 # Read to the end of fileobj and test if seeking back to the
374 # beginning works.
375 tar.getmembers()
376 self.assertEqual(tar.extractfile(t).read(), data,
377 "seek back did not work")
378 tar.close()
379
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000380 def test_fail_comp(self):
381 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
382 if self.mode == "r:":
Zachary Ware1f702212013-12-10 14:09:20 -0600383 self.skipTest('needs a gz or bz2 mode')
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000384 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
385 fobj = open(tarname, "rb")
386 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
387
388 def test_v7_dirtype(self):
389 # Test old style dirtype member (bug #1336623):
390 # Old V7 tars create directory members using an AREGTYPE
391 # header with a "/" appended to the filename field.
392 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000393 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000394 "v7 dirtype failed")
395
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000396 def test_xstar_type(self):
397 # The xstar format stores extra atime and ctime fields inside the
398 # space reserved for the prefix field. The prefix field must be
399 # ignored in this case, otherwise it will mess up the name.
400 try:
401 self.tar.getmember("misc/regtype-xstar")
402 except KeyError:
403 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
404
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000405 def test_check_members(self):
406 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000407 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000408 "wrong mtime for %s" % tarinfo.name)
409 if not tarinfo.name.startswith("ustar/"):
410 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000411 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000412 "wrong uname for %s" % tarinfo.name)
413
414 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000415 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000416 "could not find all members")
417
418 def test_extract_hardlink(self):
419 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200420 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
421 tar.extract("ustar/regtype", TEMPDIR)
422 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000423
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000424 tar.extract("ustar/lnktype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200425 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
426 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
427 data = f.read()
428 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000429
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000430 tar.extract("ustar/symtype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200431 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
432 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
433 data = f.read()
434 self.assertEqual(md5sum(data), md5_regtype)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000435
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000436 def test_extractall(self):
437 # Test if extractall() correctly restores directory permissions
438 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000439 tar = tarfile.open(tarname, encoding="iso8859-1")
440 directories = [t for t in tar if t.isdir()]
441 tar.extractall(TEMPDIR, directories)
442 for tarinfo in directories:
443 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000444 if sys.platform != "win32":
445 # Win32 has no support for fine grained permissions.
446 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000447 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
448 tar.close()
449
Lars Gustäbel12adc652009-11-23 15:46:19 +0000450 def test_init_close_fobj(self):
451 # Issue #7341: Close the internal file object in the TarFile
452 # constructor in case of an error. For the test we rely on
453 # the fact that opening an empty file raises a ReadError.
454 empty = os.path.join(TEMPDIR, "empty")
455 open(empty, "wb").write("")
456
457 try:
458 tar = object.__new__(tarfile.TarFile)
459 try:
460 tar.__init__(empty)
461 except tarfile.ReadError:
462 self.assertTrue(tar.fileobj.closed)
463 else:
464 self.fail("ReadError not raised")
465 finally:
466 os.remove(empty)
467
Serhiy Storchakace34ba62013-05-09 14:22:05 +0300468 def test_parallel_iteration(self):
469 # Issue #16601: Restarting iteration over tarfile continued
470 # from where it left off.
471 with tarfile.open(self.tarname) as tar:
472 for m1, m2 in zip(tar, tar):
473 self.assertEqual(m1.offset, m2.offset)
474 self.assertEqual(m1.name, m2.name)
475
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000476
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000477class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000478
479 mode="r|"
480
481 def test_fileobj_regular_file(self):
482 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
483 fobj = self.tar.extractfile(tarinfo)
484 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000485 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000486 "regular file extraction failed")
487
488 def test_provoke_stream_error(self):
489 tarinfos = self.tar.getmembers()
490 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000491 self.assertRaises(tarfile.StreamError, f.read)
492
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000493 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000494 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000495 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000496
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000497 while True:
498 t1 = tar1.next()
499 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000500 if t1 is None:
501 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000502 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000503
504 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000505 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000506 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000507
508 v1 = tar1.extractfile(t1)
509 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000510 if v1 is None:
511 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000512 self.assertTrue(v2 is not None, "stream.extractfile() failed")
513 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000514
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000515 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000516
Georg Brandla32e0a02006-10-24 16:54:16 +0000517
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000518class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000519
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000520 def _testfunc_file(self, name, mode):
521 try:
522 tarfile.open(name, mode)
523 except tarfile.ReadError:
524 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000525
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000526 def _testfunc_fileobj(self, name, mode):
527 try:
528 tarfile.open(name, mode, fileobj=open(name, "rb"))
529 except tarfile.ReadError:
530 self.fail()
531
532 def _test_modes(self, testfunc):
533 testfunc(tarname, "r")
534 testfunc(tarname, "r:")
535 testfunc(tarname, "r:*")
536 testfunc(tarname, "r|")
537 testfunc(tarname, "r|*")
538
539 if gzip:
540 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
541 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
542 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
543 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
544
545 testfunc(gzipname, "r")
546 testfunc(gzipname, "r:*")
547 testfunc(gzipname, "r:gz")
548 testfunc(gzipname, "r|*")
549 testfunc(gzipname, "r|gz")
550
551 if bz2:
552 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
553 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
554 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
555 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
556
557 testfunc(bz2name, "r")
558 testfunc(bz2name, "r:*")
559 testfunc(bz2name, "r:bz2")
560 testfunc(bz2name, "r|*")
561 testfunc(bz2name, "r|bz2")
562
563 def test_detect_file(self):
564 self._test_modes(self._testfunc_file)
565
566 def test_detect_fileobj(self):
567 self._test_modes(self._testfunc_fileobj)
568
Zachary Ware1f702212013-12-10 14:09:20 -0600569 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbel9a388632011-12-06 13:07:09 +0100570 def test_detect_stream_bz2(self):
571 # Originally, tarfile's stream detection looked for the string
572 # "BZh91" at the start of the file. This is incorrect because
573 # the '9' represents the blocksize (900kB). If the file was
574 # compressed using another blocksize autodetection fails.
Lars Gustäbel9a388632011-12-06 13:07:09 +0100575 with open(tarname, "rb") as fobj:
576 data = fobj.read()
577
578 # Compress with blocksize 100kB, the file starts with "BZh11".
579 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
580 fobj.write(data)
581
582 self._testfunc_file(tmpname, "r|*")
583
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000584
585class MemberReadTest(ReadTest):
586
587 def _test_member(self, tarinfo, chksum=None, **kwargs):
588 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000589 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000590 "wrong md5sum for %s" % tarinfo.name)
591
592 kwargs["mtime"] = 07606136617
593 kwargs["uid"] = 1000
594 kwargs["gid"] = 100
595 if "old-v7" not in tarinfo.name:
596 # V7 tar can't handle alphabetic owners.
597 kwargs["uname"] = "tarfile"
598 kwargs["gname"] = "tarfile"
599 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000600 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000601 "wrong value in %s field of %s" % (k, tarinfo.name))
602
603 def test_find_regtype(self):
604 tarinfo = self.tar.getmember("ustar/regtype")
605 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
606
607 def test_find_conttype(self):
608 tarinfo = self.tar.getmember("ustar/conttype")
609 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
610
611 def test_find_dirtype(self):
612 tarinfo = self.tar.getmember("ustar/dirtype")
613 self._test_member(tarinfo, size=0)
614
615 def test_find_dirtype_with_size(self):
616 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
617 self._test_member(tarinfo, size=255)
618
619 def test_find_lnktype(self):
620 tarinfo = self.tar.getmember("ustar/lnktype")
621 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
622
623 def test_find_symtype(self):
624 tarinfo = self.tar.getmember("ustar/symtype")
625 self._test_member(tarinfo, size=0, linkname="regtype")
626
627 def test_find_blktype(self):
628 tarinfo = self.tar.getmember("ustar/blktype")
629 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
630
631 def test_find_chrtype(self):
632 tarinfo = self.tar.getmember("ustar/chrtype")
633 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
634
635 def test_find_fifotype(self):
636 tarinfo = self.tar.getmember("ustar/fifotype")
637 self._test_member(tarinfo, size=0)
638
639 def test_find_sparse(self):
640 tarinfo = self.tar.getmember("ustar/sparse")
641 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
642
643 def test_find_umlauts(self):
644 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
645 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
646
647 def test_find_ustar_longname(self):
648 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000649 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000650
651 def test_find_regtype_oldv7(self):
652 tarinfo = self.tar.getmember("misc/regtype-old-v7")
653 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
654
655 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000656 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000657 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
658 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
659
660
661class LongnameTest(ReadTest):
662
663 def test_read_longname(self):
664 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000665 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000666 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000667 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000668 except KeyError:
669 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000670 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000671
672 def test_read_longlink(self):
673 longname = self.subdir + "/" + "123/" * 125 + "longname"
674 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
675 try:
676 tarinfo = self.tar.getmember(longlink)
677 except KeyError:
678 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000679 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000680
681 def test_truncated_longname(self):
682 longname = self.subdir + "/" + "123/" * 125 + "longname"
683 tarinfo = self.tar.getmember(longname)
684 offset = tarinfo.offset
685 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000686 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000687 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
688
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000689 def test_header_offset(self):
690 # Test if the start offset of the TarInfo object includes
691 # the preceding extended header.
692 longname = self.subdir + "/" + "123/" * 125 + "longname"
693 offset = self.tar.getmember(longname).offset
694 fobj = open(tarname)
695 fobj.seek(offset)
696 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
697 self.assertEqual(tarinfo.type, self.longnametype)
698
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000699
700class GNUReadTest(LongnameTest):
701
702 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000703 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000704
705 def test_sparse_file(self):
706 tarinfo1 = self.tar.getmember("ustar/sparse")
707 fobj1 = self.tar.extractfile(tarinfo1)
708 tarinfo2 = self.tar.getmember("gnu/sparse")
709 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000710 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000711 "sparse file extraction failed")
712
713
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000714class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000715
716 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000717 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000718
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000719 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000720 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000721
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000722 tarinfo = tar.getmember("pax/regtype1")
723 self.assertEqual(tarinfo.uname, "foo")
724 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000725 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000726
727 tarinfo = tar.getmember("pax/regtype2")
728 self.assertEqual(tarinfo.uname, "")
729 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000730 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000731
732 tarinfo = tar.getmember("pax/regtype3")
733 self.assertEqual(tarinfo.uname, "tarfile")
734 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000735 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
736
737 def test_pax_number_fields(self):
738 # All following number fields are read from the pax header.
739 tar = tarfile.open(tarname, encoding="iso8859-1")
740 tarinfo = tar.getmember("pax/regtype4")
741 self.assertEqual(tarinfo.size, 7011)
742 self.assertEqual(tarinfo.uid, 123)
743 self.assertEqual(tarinfo.gid, 123)
744 self.assertEqual(tarinfo.mtime, 1041808783.0)
745 self.assertEqual(type(tarinfo.mtime), float)
746 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
747 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000748
749
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000750class WriteTestBase(unittest.TestCase):
751 # Put all write tests in here that are supposed to be tested
752 # in all possible mode combinations.
753
754 def test_fileobj_no_close(self):
755 fobj = StringIO.StringIO()
756 tar = tarfile.open(fileobj=fobj, mode=self.mode)
757 tar.addfile(tarfile.TarInfo("foo"))
758 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000759 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Serhiy Storchakacdf1ebd2014-01-18 15:54:32 +0200760 # Issue #20238: Incomplete gzip output with mode="w:gz"
761 data = fobj.getvalue()
762 del tar
763 test_support.gc_collect()
764 self.assertFalse(fobj.closed)
765 self.assertEqual(data, fobj.getvalue())
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000766
767
768class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000769
770 mode = "w:"
771
772 def test_100_char_name(self):
773 # The name field in a tar header stores strings of at most 100 chars.
774 # If a string is shorter than 100 chars it has to be padded with '\0',
775 # which implies that a string of exactly 100 chars is stored without
776 # a trailing '\0'.
777 name = "0123456789" * 10
778 tar = tarfile.open(tmpname, self.mode)
779 t = tarfile.TarInfo(name)
780 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000781 tar.close()
782
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000783 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000784 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000785 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000786 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000787
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000788 def test_tar_size(self):
789 # Test for bug #1013882.
790 tar = tarfile.open(tmpname, self.mode)
791 path = os.path.join(TEMPDIR, "file")
792 fobj = open(path, "wb")
793 fobj.write("aaa")
794 fobj.close()
795 tar.add(path)
796 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000797 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000798 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000799
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000800 # The test_*_size tests test for bug #1167128.
801 def test_file_size(self):
802 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000803
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000804 path = os.path.join(TEMPDIR, "file")
805 fobj = open(path, "wb")
806 fobj.close()
807 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000808 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000809
810 fobj = open(path, "wb")
811 fobj.write("aaa")
812 fobj.close()
813 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000814 self.assertEqual(tarinfo.size, 3)
815
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000816 tar.close()
817
818 def test_directory_size(self):
819 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000820 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000821 try:
822 tar = tarfile.open(tmpname, self.mode)
823 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000824 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000825 finally:
826 os.rmdir(path)
827
828 def test_link_size(self):
829 if hasattr(os, "link"):
830 link = os.path.join(TEMPDIR, "link")
831 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000832 fobj = open(target, "wb")
833 fobj.write("aaa")
834 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000835 os.link(target, link)
836 try:
837 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000838 # Record the link target in the inodes list.
839 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000840 tarinfo = tar.gettarinfo(link)
841 self.assertEqual(tarinfo.size, 0)
842 finally:
843 os.remove(target)
844 os.remove(link)
845
846 def test_symlink_size(self):
847 if hasattr(os, "symlink"):
848 path = os.path.join(TEMPDIR, "symlink")
849 os.symlink("link_target", path)
850 try:
851 tar = tarfile.open(tmpname, self.mode)
852 tarinfo = tar.gettarinfo(path)
853 self.assertEqual(tarinfo.size, 0)
854 finally:
855 os.remove(path)
856
857 def test_add_self(self):
858 # Test for #1257255.
859 dstname = os.path.abspath(tmpname)
860
861 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000862 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000863
864 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000865 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000866
867 cwd = os.getcwd()
868 os.chdir(TEMPDIR)
869 tar.add(dstname)
870 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000871 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000872
Lars Gustäbel104490e2007-06-18 11:42:11 +0000873 def test_exclude(self):
874 tempdir = os.path.join(TEMPDIR, "exclude")
875 os.mkdir(tempdir)
876 try:
877 for name in ("foo", "bar", "baz"):
878 name = os.path.join(tempdir, name)
879 open(name, "wb").close()
880
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000881 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000882
883 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000884 with test_support.check_warnings(("use the filter argument",
885 DeprecationWarning)):
886 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000887 tar.close()
888
889 tar = tarfile.open(tmpname, "r")
890 self.assertEqual(len(tar.getmembers()), 1)
891 self.assertEqual(tar.getnames()[0], "empty_dir")
892 finally:
893 shutil.rmtree(tempdir)
894
Lars Gustäbel21121e62009-09-12 10:28:15 +0000895 def test_filter(self):
896 tempdir = os.path.join(TEMPDIR, "filter")
897 os.mkdir(tempdir)
898 try:
899 for name in ("foo", "bar", "baz"):
900 name = os.path.join(tempdir, name)
901 open(name, "wb").close()
902
903 def filter(tarinfo):
904 if os.path.basename(tarinfo.name) == "bar":
905 return
906 tarinfo.uid = 123
907 tarinfo.uname = "foo"
908 return tarinfo
909
910 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
911 tar.add(tempdir, arcname="empty_dir", filter=filter)
912 tar.close()
913
914 tar = tarfile.open(tmpname, "r")
915 for tarinfo in tar:
916 self.assertEqual(tarinfo.uid, 123)
917 self.assertEqual(tarinfo.uname, "foo")
918 self.assertEqual(len(tar.getmembers()), 3)
919 tar.close()
920 finally:
921 shutil.rmtree(tempdir)
922
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000923 # Guarantee that stored pathnames are not modified. Don't
924 # remove ./ or ../ or double slashes. Still make absolute
925 # pathnames relative.
926 # For details see bug #6054.
927 def _test_pathname(self, path, cmp_path=None, dir=False):
928 # Create a tarfile with an empty member named path
929 # and compare the stored name with the original.
930 foo = os.path.join(TEMPDIR, "foo")
931 if not dir:
932 open(foo, "w").close()
933 else:
934 os.mkdir(foo)
935
936 tar = tarfile.open(tmpname, self.mode)
937 tar.add(foo, arcname=path)
938 tar.close()
939
940 tar = tarfile.open(tmpname, "r")
941 t = tar.next()
942 tar.close()
943
944 if not dir:
945 os.remove(foo)
946 else:
947 os.rmdir(foo)
948
949 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
950
951 def test_pathnames(self):
952 self._test_pathname("foo")
953 self._test_pathname(os.path.join("foo", ".", "bar"))
954 self._test_pathname(os.path.join("foo", "..", "bar"))
955 self._test_pathname(os.path.join(".", "foo"))
956 self._test_pathname(os.path.join(".", "foo", "."))
957 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
958 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
959 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
960 self._test_pathname(os.path.join("..", "foo"))
961 self._test_pathname(os.path.join("..", "foo", ".."))
962 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
963 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
964
965 self._test_pathname("foo" + os.sep + os.sep + "bar")
966 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
967
968 def test_abs_pathnames(self):
969 if sys.platform == "win32":
970 self._test_pathname("C:\\foo", "foo")
971 else:
972 self._test_pathname("/foo", "foo")
973 self._test_pathname("///foo", "foo")
974
975 def test_cwd(self):
976 # Test adding the current working directory.
977 cwd = os.getcwd()
978 os.chdir(TEMPDIR)
979 try:
980 open("foo", "w").close()
981
982 tar = tarfile.open(tmpname, self.mode)
983 tar.add(".")
984 tar.close()
985
986 tar = tarfile.open(tmpname, "r")
987 for t in tar:
Serhiy Storchaka88761452012-12-28 00:32:19 +0200988 self.assertTrue(t.name == "." or t.name.startswith("./"))
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000989 tar.close()
990 finally:
991 os.chdir(cwd)
992
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800993 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800994 def test_extractall_symlinks(self):
995 # Test if extractall works properly when tarfile contains symlinks
996 tempdir = os.path.join(TEMPDIR, "testsymlinks")
997 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
998 os.mkdir(tempdir)
999 try:
1000 source_file = os.path.join(tempdir,'source')
1001 target_file = os.path.join(tempdir,'symlink')
1002 with open(source_file,'w') as f:
1003 f.write('something\n')
1004 os.symlink(source_file, target_file)
1005 tar = tarfile.open(temparchive,'w')
1006 tar.add(source_file, arcname=os.path.basename(source_file))
1007 tar.add(target_file, arcname=os.path.basename(target_file))
1008 tar.close()
1009 # Let's extract it to the location which contains the symlink
1010 tar = tarfile.open(temparchive,'r')
1011 # this should not raise OSError: [Errno 17] File exists
1012 try:
1013 tar.extractall(path=tempdir)
1014 except OSError:
1015 self.fail("extractall failed with symlinked files")
1016 finally:
1017 tar.close()
1018 finally:
1019 os.unlink(temparchive)
1020 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001021
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +08001022 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
1023 def test_extractall_broken_symlinks(self):
1024 # Test if extractall works properly when tarfile contains broken
1025 # symlinks
1026 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1027 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1028 os.mkdir(tempdir)
1029 try:
1030 source_file = os.path.join(tempdir,'source')
1031 target_file = os.path.join(tempdir,'symlink')
1032 with open(source_file,'w') as f:
1033 f.write('something\n')
1034 os.symlink(source_file, target_file)
1035 tar = tarfile.open(temparchive,'w')
1036 tar.add(target_file, arcname=os.path.basename(target_file))
1037 tar.close()
1038 # remove the real file
1039 os.unlink(source_file)
1040 # Let's extract it to the location which contains the symlink
1041 tar = tarfile.open(temparchive,'r')
1042 # this should not raise OSError: [Errno 17] File exists
1043 try:
1044 tar.extractall(path=tempdir)
1045 except OSError:
1046 self.fail("extractall failed with broken symlinked files")
1047 finally:
1048 tar.close()
1049 finally:
1050 os.unlink(temparchive)
1051 shutil.rmtree(tempdir)
1052
1053 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
1054 def test_extractall_hardlinks(self):
1055 # Test if extractall works properly when tarfile contains symlinks
1056 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1057 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1058 os.mkdir(tempdir)
1059 try:
1060 source_file = os.path.join(tempdir,'source')
1061 target_file = os.path.join(tempdir,'symlink')
1062 with open(source_file,'w') as f:
1063 f.write('something\n')
1064 os.link(source_file, target_file)
1065 tar = tarfile.open(temparchive,'w')
1066 tar.add(source_file, arcname=os.path.basename(source_file))
1067 tar.add(target_file, arcname=os.path.basename(target_file))
1068 tar.close()
1069 # Let's extract it to the location which contains the symlink
1070 tar = tarfile.open(temparchive,'r')
1071 # this should not raise OSError: [Errno 17] File exists
1072 try:
1073 tar.extractall(path=tempdir)
1074 except OSError:
1075 self.fail("extractall failed with linked files")
1076 finally:
1077 tar.close()
1078 finally:
1079 os.unlink(temparchive)
1080 shutil.rmtree(tempdir)
1081
Serhiy Storchaka7a278da2014-01-18 16:14:00 +02001082 def test_open_nonwritable_fileobj(self):
1083 for exctype in IOError, EOFError, RuntimeError:
1084 class BadFile(StringIO.StringIO):
1085 first = True
1086 def write(self, data):
1087 if self.first:
1088 self.first = False
1089 raise exctype
1090
1091 f = BadFile()
1092 with self.assertRaises(exctype):
1093 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1094 format=tarfile.PAX_FORMAT,
1095 pax_headers={'non': 'empty'})
1096 self.assertFalse(f.closed)
1097
Lars Gustäbelb1a54a32008-05-27 12:39:23 +00001098class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001099
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001100 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +00001101
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001102 def test_stream_padding(self):
1103 # Test for bug #1543303.
1104 tar = tarfile.open(tmpname, self.mode)
1105 tar.close()
1106
1107 if self.mode.endswith("gz"):
1108 fobj = gzip.GzipFile(tmpname)
1109 data = fobj.read()
1110 fobj.close()
1111 elif self.mode.endswith("bz2"):
1112 dec = bz2.BZ2Decompressor()
1113 data = open(tmpname, "rb").read()
1114 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001115 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001116 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +00001117 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001118 fobj = open(tmpname, "rb")
1119 data = fobj.read()
1120 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +00001121
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001122 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +00001123 "incorrect zero padding")
1124
Zachary Ware1f702212013-12-10 14:09:20 -06001125 @unittest.skipIf(sys.platform == 'win32', 'not appropriate for Windows')
1126 @unittest.skipUnless(hasattr(os, 'umask'), 'requires os.umask')
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001127 def test_file_mode(self):
1128 # Test for issue #8464: Create files with correct
1129 # permissions.
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001130 if os.path.exists(tmpname):
1131 os.remove(tmpname)
1132
1133 original_umask = os.umask(0022)
1134 try:
1135 tar = tarfile.open(tmpname, self.mode)
1136 tar.close()
1137 mode = os.stat(tmpname).st_mode & 0777
1138 self.assertEqual(mode, 0644, "wrong file permissions")
1139 finally:
1140 os.umask(original_umask)
1141
Lars Gustäbel7d4d0742011-12-21 19:27:50 +01001142 def test_issue13639(self):
1143 try:
1144 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1145 pass
1146 except UnicodeDecodeError:
1147 self.fail("_Stream failed to write unicode filename")
1148
Neal Norwitz8a519392006-08-21 17:59:46 +00001149
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001150class GNUWriteTest(unittest.TestCase):
1151 # This testcase checks for correct creation of GNU Longname
1152 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001153
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001154 def _length(self, s):
1155 blocks, remainder = divmod(len(s) + 1, 512)
1156 if remainder:
1157 blocks += 1
1158 return blocks * 512
1159
1160 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001161 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001162 count = 512
1163
1164 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001165 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001166 count += 512
1167 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001168 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001169 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001170 count += 512
1171 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001172 return count
1173
1174 def _test(self, name, link=None):
1175 tarinfo = tarfile.TarInfo(name)
1176 if link:
1177 tarinfo.linkname = link
1178 tarinfo.type = tarfile.LNKTYPE
1179
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001180 tar = tarfile.open(tmpname, "w")
1181 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001182 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001183
1184 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001185 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001186 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001187
Georg Brandl87fa5592006-12-06 22:21:18 +00001188 tar.close()
1189
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001190 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001191 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001192 self.assertIsNotNone(member,
1193 "unable to read longname member")
1194 self.assertEqual(tarinfo.name, member.name,
1195 "unable to read longname member")
1196 self.assertEqual(tarinfo.linkname, member.linkname,
1197 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001198
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001199 def test_longname_1023(self):
1200 self._test(("longnam/" * 127) + "longnam")
1201
1202 def test_longname_1024(self):
1203 self._test(("longnam/" * 127) + "longname")
1204
1205 def test_longname_1025(self):
1206 self._test(("longnam/" * 127) + "longname_")
1207
1208 def test_longlink_1023(self):
1209 self._test("name", ("longlnk/" * 127) + "longlnk")
1210
1211 def test_longlink_1024(self):
1212 self._test("name", ("longlnk/" * 127) + "longlink")
1213
1214 def test_longlink_1025(self):
1215 self._test("name", ("longlnk/" * 127) + "longlink_")
1216
1217 def test_longnamelink_1023(self):
1218 self._test(("longnam/" * 127) + "longnam",
1219 ("longlnk/" * 127) + "longlnk")
1220
1221 def test_longnamelink_1024(self):
1222 self._test(("longnam/" * 127) + "longname",
1223 ("longlnk/" * 127) + "longlink")
1224
1225 def test_longnamelink_1025(self):
1226 self._test(("longnam/" * 127) + "longname_",
1227 ("longlnk/" * 127) + "longlink_")
1228
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001229
1230class HardlinkTest(unittest.TestCase):
1231 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001232
1233 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001234 self.foo = os.path.join(TEMPDIR, "foo")
1235 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001236
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001237 fobj = open(self.foo, "wb")
1238 fobj.write("foo")
1239 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001240
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001241 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001242
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001243 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001244 self.tar.add(self.foo)
1245
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001246 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001247 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001248 os.remove(self.foo)
1249 os.remove(self.bar)
1250
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001251 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001252 # The same name will be added as a REGTYPE every
1253 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001254 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001255 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001256 "add file as regular failed")
1257
1258 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001259 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001260 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001261 "add file as hardlink failed")
1262
1263 def test_dereference_hardlink(self):
1264 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001265 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001266 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001267 "dereferencing hardlink failed")
1268
Neal Norwitza4f651a2004-07-20 22:07:44 +00001269
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001270class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001271
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001272 def _test(self, name, link=None):
1273 # See GNUWriteTest.
1274 tarinfo = tarfile.TarInfo(name)
1275 if link:
1276 tarinfo.linkname = link
1277 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001278
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001279 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1280 tar.addfile(tarinfo)
1281 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001282
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001283 tar = tarfile.open(tmpname)
1284 if link:
1285 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001286 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001287 else:
1288 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001289 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001290
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001291 def test_pax_global_header(self):
1292 pax_headers = {
1293 u"foo": u"bar",
1294 u"uid": u"0",
1295 u"mtime": u"1.23",
1296 u"test": u"äöü",
1297 u"äöü": u"test"}
1298
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001299 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001300 pax_headers=pax_headers)
1301 tar.addfile(tarfile.TarInfo("test"))
1302 tar.close()
1303
1304 # Test if the global header was written correctly.
1305 tar = tarfile.open(tmpname, encoding="iso8859-1")
1306 self.assertEqual(tar.pax_headers, pax_headers)
1307 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1308
1309 # Test if all the fields are unicode.
1310 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001311 self.assertTrue(type(key) is unicode)
1312 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001313 if key in tarfile.PAX_NUMBER_FIELDS:
1314 try:
1315 tarfile.PAX_NUMBER_FIELDS[key](val)
1316 except (TypeError, ValueError):
1317 self.fail("unable to convert pax header field")
1318
1319 def test_pax_extended_header(self):
1320 # The fields from the pax header have priority over the
1321 # TarInfo.
1322 pax_headers = {u"path": u"foo", u"uid": u"123"}
1323
1324 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1325 t = tarfile.TarInfo()
1326 t.name = u"äöü" # non-ASCII
1327 t.uid = 8**8 # too large
1328 t.pax_headers = pax_headers
1329 tar.addfile(t)
1330 tar.close()
1331
1332 tar = tarfile.open(tmpname, encoding="iso8859-1")
1333 t = tar.getmembers()[0]
1334 self.assertEqual(t.pax_headers, pax_headers)
1335 self.assertEqual(t.name, "foo")
1336 self.assertEqual(t.uid, 123)
1337
1338
1339class UstarUnicodeTest(unittest.TestCase):
1340 # All *UnicodeTests FIXME
1341
1342 format = tarfile.USTAR_FORMAT
1343
1344 def test_iso8859_1_filename(self):
1345 self._test_unicode_filename("iso8859-1")
1346
1347 def test_utf7_filename(self):
1348 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001349
1350 def test_utf8_filename(self):
1351 self._test_unicode_filename("utf8")
1352
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001353 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001354 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1355 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001356 tar.addfile(tarfile.TarInfo(name))
1357 tar.close()
1358
1359 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001360 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001361 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001362 tar.close()
1363
1364 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001365 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1366 tarinfo = tarfile.TarInfo()
1367
1368 tarinfo.name = "äöü"
1369 if self.format == tarfile.PAX_FORMAT:
1370 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1371 else:
1372 tar.addfile(tarinfo)
1373
1374 tarinfo.name = u"äöü"
1375 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1376
1377 tarinfo.name = "foo"
1378 tarinfo.uname = u"äöü"
1379 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1380
1381 def test_unicode_argument(self):
1382 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1383 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001384 self.assertTrue(type(t.name) is str)
1385 self.assertTrue(type(t.linkname) is str)
1386 self.assertTrue(type(t.uname) is str)
1387 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001388 tar.close()
1389
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001390 def test_uname_unicode(self):
1391 for name in (u"äöü", "äöü"):
1392 t = tarfile.TarInfo("foo")
1393 t.uname = name
1394 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001395
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001396 fobj = StringIO.StringIO()
1397 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1398 tar.addfile(t)
1399 tar.close()
1400 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001401
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001402 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1403 t = tar.getmember("foo")
1404 self.assertEqual(t.uname, "äöü")
1405 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001406
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001407
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001408class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001409
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001410 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001411
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001412
1413class PaxUnicodeTest(UstarUnicodeTest):
1414
1415 format = tarfile.PAX_FORMAT
1416
1417 def _create_unicode_name(self, name):
1418 tar = tarfile.open(tmpname, "w", format=self.format)
1419 t = tarfile.TarInfo()
1420 t.pax_headers["path"] = name
1421 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001422 tar.close()
1423
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001424 def test_error_handlers(self):
1425 # Test if the unicode error handlers work correctly for characters
1426 # that cannot be expressed in a given encoding.
1427 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001428
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001429 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1430 ("replace", "???"), ("ignore", "")):
1431 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1432 errors=handler)
1433 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001434
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001435 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1436 encoding="ascii", errors="strict")
1437
1438 def test_error_handler_utf8(self):
1439 # Create a pathname that has one component representable using
1440 # iso8859-1 and the other only in iso8859-15.
1441 self._create_unicode_name(u"äöü/¤")
1442
1443 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1444 errors="utf-8")
1445 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001446
Georg Brandlded1c4d2006-12-20 11:55:16 +00001447
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001448class AppendTest(unittest.TestCase):
1449 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001450
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001451 def setUp(self):
1452 self.tarname = tmpname
1453 if os.path.exists(self.tarname):
1454 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001455
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001456 def _add_testfile(self, fileobj=None):
1457 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1458 tar.addfile(tarfile.TarInfo("bar"))
1459 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001460
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001461 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001462 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001463 t = src.getmember("ustar/regtype")
1464 t.name = "foo"
1465 f = src.extractfile(t)
1466 tar = tarfile.open(self.tarname, mode)
1467 tar.addfile(t, f)
1468 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001469
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001470 def _test(self, names=["bar"], fileobj=None):
1471 tar = tarfile.open(self.tarname, fileobj=fileobj)
1472 self.assertEqual(tar.getnames(), names)
1473
1474 def test_non_existing(self):
1475 self._add_testfile()
1476 self._test()
1477
1478 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001479 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001480 self._add_testfile()
1481 self._test()
1482
1483 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001484 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001485 self._add_testfile(fobj)
1486 fobj.seek(0)
1487 self._test(fileobj=fobj)
1488
1489 def test_fileobj(self):
1490 self._create_testtar()
1491 data = open(self.tarname).read()
1492 fobj = StringIO.StringIO(data)
1493 self._add_testfile(fobj)
1494 fobj.seek(0)
1495 self._test(names=["foo", "bar"], fileobj=fobj)
1496
1497 def test_existing(self):
1498 self._create_testtar()
1499 self._add_testfile()
1500 self._test(names=["foo", "bar"])
1501
Zachary Ware1f702212013-12-10 14:09:20 -06001502 @unittest.skipUnless(gzip, 'requires gzip')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001503 def test_append_gz(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001504 self._create_testtar("w:gz")
1505 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1506
Zachary Ware1f702212013-12-10 14:09:20 -06001507 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001508 def test_append_bz2(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001509 self._create_testtar("w:bz2")
1510 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1511
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001512 # Append mode is supposed to fail if the tarfile to append to
1513 # does not end with a zero block.
1514 def _test_error(self, data):
1515 open(self.tarname, "wb").write(data)
1516 self.assertRaises(tarfile.ReadError, self._add_testfile)
1517
1518 def test_null(self):
1519 self._test_error("")
1520
1521 def test_incomplete(self):
1522 self._test_error("\0" * 13)
1523
1524 def test_premature_eof(self):
1525 data = tarfile.TarInfo("foo").tobuf()
1526 self._test_error(data)
1527
1528 def test_trailing_garbage(self):
1529 data = tarfile.TarInfo("foo").tobuf()
1530 self._test_error(data + "\0" * 13)
1531
1532 def test_invalid(self):
1533 self._test_error("a" * 512)
1534
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001535
1536class LimitsTest(unittest.TestCase):
1537
1538 def test_ustar_limits(self):
1539 # 100 char name
1540 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001541 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001542
1543 # 101 char name that cannot be stored
1544 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001545 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001546
1547 # 256 char name with a slash at pos 156
1548 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001549 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001550
1551 # 256 char name that cannot be stored
1552 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001553 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001554
1555 # 512 char name
1556 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001557 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001558
1559 # 512 char linkname
1560 tarinfo = tarfile.TarInfo("longlink")
1561 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001562 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001563
1564 # uid > 8 digits
1565 tarinfo = tarfile.TarInfo("name")
1566 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001567 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001568
1569 def test_gnu_limits(self):
1570 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001571 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001572
1573 tarinfo = tarfile.TarInfo("longlink")
1574 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001575 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001576
1577 # uid >= 256 ** 7
1578 tarinfo = tarfile.TarInfo("name")
1579 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001580 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001581
1582 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001583 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001584 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001585
1586 tarinfo = tarfile.TarInfo("longlink")
1587 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001588 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001589
1590 tarinfo = tarfile.TarInfo("name")
1591 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001592 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001593
1594
Lars Gustäbel64581042010-03-03 11:55:48 +00001595class ContextManagerTest(unittest.TestCase):
1596
1597 def test_basic(self):
1598 with tarfile.open(tarname) as tar:
1599 self.assertFalse(tar.closed, "closed inside runtime context")
1600 self.assertTrue(tar.closed, "context manager failed")
1601
1602 def test_closed(self):
1603 # The __enter__() method is supposed to raise IOError
1604 # if the TarFile object is already closed.
1605 tar = tarfile.open(tarname)
1606 tar.close()
1607 with self.assertRaises(IOError):
1608 with tar:
1609 pass
1610
1611 def test_exception(self):
1612 # Test if the IOError exception is passed through properly.
1613 with self.assertRaises(Exception) as exc:
1614 with tarfile.open(tarname) as tar:
1615 raise IOError
1616 self.assertIsInstance(exc.exception, IOError,
1617 "wrong exception raised in context manager")
1618 self.assertTrue(tar.closed, "context manager failed")
1619
1620 def test_no_eof(self):
1621 # __exit__() must not write end-of-archive blocks if an
1622 # exception was raised.
1623 try:
1624 with tarfile.open(tmpname, "w") as tar:
1625 raise Exception
1626 except:
1627 pass
1628 self.assertEqual(os.path.getsize(tmpname), 0,
1629 "context manager wrote an end-of-archive block")
1630 self.assertTrue(tar.closed, "context manager failed")
1631
1632 def test_eof(self):
1633 # __exit__() must write end-of-archive blocks, i.e. call
1634 # TarFile.close() if there was no error.
1635 with tarfile.open(tmpname, "w"):
1636 pass
1637 self.assertNotEqual(os.path.getsize(tmpname), 0,
1638 "context manager wrote no end-of-archive block")
1639
1640 def test_fileobj(self):
1641 # Test that __exit__() did not close the external file
1642 # object.
1643 fobj = open(tmpname, "wb")
1644 try:
1645 with tarfile.open(fileobj=fobj, mode="w") as tar:
1646 raise Exception
1647 except:
1648 pass
1649 self.assertFalse(fobj.closed, "external file object was closed")
1650 self.assertTrue(tar.closed, "context manager failed")
1651 fobj.close()
1652
1653
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001654class LinkEmulationTest(ReadTest):
1655
1656 # Test for issue #8741 regression. On platforms that do not support
1657 # symbolic or hard links tarfile tries to extract these types of members as
1658 # the regular files they point to.
1659 def _test_link_extraction(self, name):
1660 self.tar.extract(name, TEMPDIR)
1661 data = open(os.path.join(TEMPDIR, name), "rb").read()
1662 self.assertEqual(md5sum(data), md5_regtype)
1663
1664 def test_hardlink_extraction1(self):
1665 self._test_link_extraction("ustar/lnktype")
1666
1667 def test_hardlink_extraction2(self):
1668 self._test_link_extraction("./ustar/linktest2/lnktype")
1669
1670 def test_symlink_extraction1(self):
1671 self._test_link_extraction("ustar/symtype")
1672
1673 def test_symlink_extraction2(self):
1674 self._test_link_extraction("./ustar/linktest2/symtype")
1675
1676
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001677class GzipMiscReadTest(MiscReadTest):
1678 tarname = gzipname
1679 mode = "r:gz"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001680 taropen = tarfile.TarFile.gzopen
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001681class GzipUstarReadTest(UstarReadTest):
1682 tarname = gzipname
1683 mode = "r:gz"
1684class GzipStreamReadTest(StreamReadTest):
1685 tarname = gzipname
1686 mode = "r|gz"
1687class GzipWriteTest(WriteTest):
1688 mode = "w:gz"
1689class GzipStreamWriteTest(StreamWriteTest):
1690 mode = "w|gz"
1691
1692
1693class Bz2MiscReadTest(MiscReadTest):
1694 tarname = bz2name
1695 mode = "r:bz2"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001696 taropen = tarfile.TarFile.bz2open
Serhiy Storchakae7829bd2014-07-16 23:58:12 +03001697 def requires_name_attribute(self):
1698 self.skipTest("BZ2File have no name attribute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001699class Bz2UstarReadTest(UstarReadTest):
1700 tarname = bz2name
1701 mode = "r:bz2"
1702class Bz2StreamReadTest(StreamReadTest):
1703 tarname = bz2name
1704 mode = "r|bz2"
1705class Bz2WriteTest(WriteTest):
1706 mode = "w:bz2"
1707class Bz2StreamWriteTest(StreamWriteTest):
1708 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001709
Lars Gustäbel2020a592009-03-22 20:09:33 +00001710class Bz2PartialReadTest(unittest.TestCase):
1711 # Issue5068: The _BZ2Proxy.read() method loops forever
1712 # on an empty or partial bzipped file.
1713
1714 def _test_partial_input(self, mode):
1715 class MyStringIO(StringIO.StringIO):
1716 hit_eof = False
1717 def read(self, n):
1718 if self.hit_eof:
1719 raise AssertionError("infinite loop detected in tarfile.open()")
1720 self.hit_eof = self.pos == self.len
1721 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001722 def seek(self, *args):
1723 self.hit_eof = False
1724 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001725
1726 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1727 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001728 try:
1729 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1730 except tarfile.ReadError:
1731 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001732
1733 def test_partial_input(self):
1734 self._test_partial_input("r")
1735
1736 def test_partial_input_bz2(self):
1737 self._test_partial_input("r:bz2")
1738
1739
Neal Norwitz996acf12003-02-17 14:51:41 +00001740def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001741 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001742
Walter Dörwald21d3a322003-05-01 17:45:56 +00001743 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001744 UstarReadTest,
1745 MiscReadTest,
1746 StreamReadTest,
1747 DetectReadTest,
1748 MemberReadTest,
1749 GNUReadTest,
1750 PaxReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001751 ListTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001752 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001753 StreamWriteTest,
1754 GNUWriteTest,
1755 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001756 UstarUnicodeTest,
1757 GNUUnicodeTest,
1758 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001759 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001760 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001761 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001762 ]
1763
Neal Norwitza4f651a2004-07-20 22:07:44 +00001764 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001765 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001766 else:
1767 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001768
1769 fobj = open(tarname, "rb")
1770 data = fobj.read()
1771 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001772
Walter Dörwald21d3a322003-05-01 17:45:56 +00001773 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001774 # Create testtar.tar.gz and add gzip-specific tests.
1775 tar = gzip.open(gzipname, "wb")
1776 tar.write(data)
1777 tar.close()
1778
1779 tests += [
1780 GzipMiscReadTest,
1781 GzipUstarReadTest,
1782 GzipStreamReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001783 GzipListTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001784 GzipWriteTest,
1785 GzipStreamWriteTest,
1786 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001787
1788 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001789 # Create testtar.tar.bz2 and add bz2-specific tests.
1790 tar = bz2.BZ2File(bz2name, "wb")
1791 tar.write(data)
1792 tar.close()
1793
1794 tests += [
1795 Bz2MiscReadTest,
1796 Bz2UstarReadTest,
1797 Bz2StreamReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001798 Bz2ListTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001799 Bz2WriteTest,
1800 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001801 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001802 ]
1803
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001804 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001805 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001806 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001807 if os.path.exists(TEMPDIR):
1808 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001809
Neal Norwitz996acf12003-02-17 14:51:41 +00001810if __name__ == "__main__":
1811 test_main()