blob: 18aa68974b31a6301142db05bcedcc623fdf96f2 [file] [log] [blame]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001import sys
2import os
3import shutil
Georg Brandl38c6a222006-05-10 16:26:03 +00004import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00005from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00006import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00007
8import unittest
9import tarfile
10
11from test import test_support
Serhiy Storchaka7c7b4b52015-09-06 14:16:18 +030012from test import test_support as support
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000013
14# Check for our compression modules.
15try:
16 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000017 gzip.GzipFile
18except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000019 gzip = None
20try:
21 import bz2
22except ImportError:
23 bz2 = None
24
Lars Gustäbelc64e4022007-03-13 10:47:19 +000025def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000026 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000027
Antoine Pitrou310c9fe2009-11-11 20:55:07 +000028TEMPDIR = os.path.abspath(test_support.TESTFN)
29tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000030gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
31bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
32tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000033
Lars Gustäbelc64e4022007-03-13 10:47:19 +000034md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
35md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000036
37
Lars Gustäbelc64e4022007-03-13 10:47:19 +000038class ReadTest(unittest.TestCase):
39
40 tarname = tarname
41 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000042
43 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000044 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000045
46 def tearDown(self):
47 self.tar.close()
48
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000049
Lars Gustäbelc64e4022007-03-13 10:47:19 +000050class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000051
Lars Gustäbelc64e4022007-03-13 10:47:19 +000052 def test_fileobj_regular_file(self):
53 tarinfo = self.tar.getmember("ustar/regtype")
54 fobj = self.tar.extractfile(tarinfo)
55 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000056 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000057 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000058
Lars Gustäbelc64e4022007-03-13 10:47:19 +000059 def test_fileobj_readlines(self):
60 self.tar.extract("ustar/regtype", TEMPDIR)
61 tarinfo = self.tar.getmember("ustar/regtype")
62 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
63 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000064
Lars Gustäbelc64e4022007-03-13 10:47:19 +000065 lines1 = fobj1.readlines()
66 lines2 = fobj2.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000067 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000068 "fileobj.readlines() failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000069 self.assertTrue(len(lines2) == 114,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000070 "fileobj.readlines() failed")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +000071 self.assertTrue(lines2[83] ==
Lars Gustäbelc64e4022007-03-13 10:47:19 +000072 "I will gladly admit that Python is not the fastest running scripting language.\n",
73 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000074
Lars Gustäbelc64e4022007-03-13 10:47:19 +000075 def test_fileobj_iter(self):
76 self.tar.extract("ustar/regtype", TEMPDIR)
77 tarinfo = self.tar.getmember("ustar/regtype")
78 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
79 fobj2 = self.tar.extractfile(tarinfo)
80 lines1 = fobj1.readlines()
81 lines2 = [line for line in fobj2]
Benjamin Peterson5c8da862009-06-30 22:57:08 +000082 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000083 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000084
Lars Gustäbelc64e4022007-03-13 10:47:19 +000085 def test_fileobj_seek(self):
86 self.tar.extract("ustar/regtype", TEMPDIR)
87 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
88 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000089 fobj.close()
90
Lars Gustäbelc64e4022007-03-13 10:47:19 +000091 tarinfo = self.tar.getmember("ustar/regtype")
92 fobj = self.tar.extractfile(tarinfo)
93
94 text = fobj.read()
95 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000096 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000097 "seek() to file's start failed")
98 fobj.seek(2048, 0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000099 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000100 "seek() to absolute position failed")
101 fobj.seek(-1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000102 self.assertTrue(1024 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000103 "seek() to negative relative position failed")
104 fobj.seek(1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000105 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000106 "seek() to positive relative position failed")
107 s = fobj.read(10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000108 self.assertTrue(s == data[2048:2058],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000109 "read() after seek failed")
110 fobj.seek(0, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000111 self.assertTrue(tarinfo.size == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000112 "seek() to file's end failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000113 self.assertTrue(fobj.read() == "",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000114 "read() at file's end did not return empty string")
115 fobj.seek(-tarinfo.size, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000116 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000117 "relative seek() to file's start failed")
118 fobj.seek(512)
119 s1 = fobj.readlines()
120 fobj.seek(512)
121 s2 = fobj.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000122 self.assertTrue(s1 == s2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000123 "readlines() after seek failed")
124 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000125 self.assertTrue(len(fobj.readline()) == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000126 "tell() after readline() failed")
127 fobj.seek(512)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000128 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000129 "tell() after seek() and readline() failed")
130 fobj.seek(0)
131 line = fobj.readline()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000132 self.assertTrue(fobj.read() == data[len(line):],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000133 "read() after readline() failed")
134 fobj.close()
135
Lars Gustäbel4da7d412010-06-03 12:34:14 +0000136 # Test if symbolic and hard links are resolved by extractfile(). The
137 # test link members each point to a regular member whose data is
138 # supposed to be exported.
139 def _test_fileobj_link(self, lnktype, regtype):
140 a = self.tar.extractfile(lnktype)
141 b = self.tar.extractfile(regtype)
142 self.assertEqual(a.name, b.name)
143
144 def test_fileobj_link1(self):
145 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
146
147 def test_fileobj_link2(self):
148 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
149
150 def test_fileobj_symlink1(self):
151 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
152
153 def test_fileobj_symlink2(self):
154 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
155
Lars Gustäbel231d4742012-04-24 22:42:08 +0200156 def test_issue14160(self):
157 self._test_fileobj_link("symtype2", "ustar/regtype")
158
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000159
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +0200160class ListTest(ReadTest, unittest.TestCase):
161
162 # Override setUp to use default encoding (UTF-8)
163 def setUp(self):
164 self.tar = tarfile.open(self.tarname, mode=self.mode)
165
166 def test_list(self):
167 with test_support.captured_stdout() as t:
168 self.tar.list(verbose=False)
169 out = t.getvalue()
170 self.assertIn('ustar/conttype', out)
171 self.assertIn('ustar/regtype', out)
172 self.assertIn('ustar/lnktype', out)
173 self.assertIn('ustar' + ('/12345' * 40) + '67/longname', out)
174 self.assertIn('./ustar/linktest2/symtype', out)
175 self.assertIn('./ustar/linktest2/lnktype', out)
176 # Make sure it puts trailing slash for directory
177 self.assertIn('ustar/dirtype/', out)
178 self.assertIn('ustar/dirtype-with-size/', out)
179 # Make sure it is able to print non-ASCII characters
180 self.assertIn('ustar/umlauts-'
181 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
182 self.assertIn('misc/regtype-hpux-signed-chksum-'
183 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
184 self.assertIn('misc/regtype-old-v7-signed-chksum-'
185 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
186 # Make sure it prints files separated by one newline without any
187 # 'ls -l'-like accessories if verbose flag is not being used
188 # ...
189 # ustar/conttype
190 # ustar/regtype
191 # ...
192 self.assertRegexpMatches(out, r'ustar/conttype ?\r?\n'
193 r'ustar/regtype ?\r?\n')
194 # Make sure it does not print the source of link without verbose flag
195 self.assertNotIn('link to', out)
196 self.assertNotIn('->', out)
197
198 def test_list_verbose(self):
199 with test_support.captured_stdout() as t:
200 self.tar.list(verbose=True)
201 out = t.getvalue()
202 # Make sure it prints files separated by one newline with 'ls -l'-like
203 # accessories if verbose flag is being used
204 # ...
205 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
206 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
207 # ...
208 self.assertRegexpMatches(out, (r'-rw-r--r-- tarfile/tarfile\s+7011 '
209 r'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
210 r'ustar/\w+type ?\r?\n') * 2)
211 # Make sure it prints the source of link with verbose flag
212 self.assertIn('ustar/symtype -> regtype', out)
213 self.assertIn('./ustar/linktest2/symtype -> ../linktest1/regtype', out)
214 self.assertIn('./ustar/linktest2/lnktype link to '
215 './ustar/linktest1/regtype', out)
216 self.assertIn('gnu' + ('/123' * 125) + '/longlink link to gnu' +
217 ('/123' * 125) + '/longname', out)
218 self.assertIn('pax' + ('/123' * 125) + '/longlink link to pax' +
219 ('/123' * 125) + '/longname', out)
220
221
222class GzipListTest(ListTest):
223 tarname = gzipname
224 mode = "r:gz"
225 taropen = tarfile.TarFile.gzopen
226
227
228class Bz2ListTest(ListTest):
229 tarname = bz2name
230 mode = "r:bz2"
231 taropen = tarfile.TarFile.bz2open
232
233
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000234class CommonReadTest(ReadTest):
235
236 def test_empty_tarfile(self):
237 # Test for issue6123: Allow opening empty archives.
238 # This test checks if tarfile.open() is able to open an empty tar
239 # archive successfully. Note that an empty tar archive is not the
240 # same as an empty file!
241 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
242 try:
243 tar = tarfile.open(tmpname, self.mode)
244 tar.getnames()
245 except tarfile.ReadError:
246 self.fail("tarfile.open() failed on empty archive")
247 self.assertListEqual(tar.getmembers(), [])
248
249 def test_null_tarfile(self):
250 # Test for issue6123: Allow opening empty archives.
251 # This test guarantees that tarfile.open() does not treat an empty
252 # file as an empty tar archive.
253 open(tmpname, "wb").close()
254 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
255 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
256
Serhiy Storchakad804f532014-01-13 19:08:51 +0200257 def test_non_existent_tarfile(self):
258 # Test for issue11513: prevent non-existent gzipped tarfiles raising
259 # multiple exceptions.
260 exctype = OSError if '|' in self.mode else IOError
261 with self.assertRaisesRegexp(exctype, "xxx") as ex:
262 tarfile.open("xxx", self.mode)
263 self.assertEqual(ex.exception.errno, errno.ENOENT)
264
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000265 def test_ignore_zeros(self):
266 # Test TarFile's ignore_zeros option.
267 if self.mode.endswith(":gz"):
268 _open = gzip.GzipFile
269 elif self.mode.endswith(":bz2"):
270 _open = bz2.BZ2File
271 else:
272 _open = open
273
274 for char in ('\0', 'a'):
275 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
276 # are ignored correctly.
277 fobj = _open(tmpname, "wb")
278 fobj.write(char * 1024)
279 fobj.write(tarfile.TarInfo("foo").tobuf())
280 fobj.close()
281
282 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
283 self.assertListEqual(tar.getnames(), ["foo"],
284 "ignore_zeros=True should have skipped the %r-blocks" % char)
285 tar.close()
286
Lars Gustäbel518602a2015-07-06 09:23:04 +0200287 def test_premature_end_of_archive(self):
288 for size in (512, 600, 1024, 1200):
289 with tarfile.open(tmpname, "w:") as tar:
290 t = tarfile.TarInfo("foo")
291 t.size = 1024
292 tar.addfile(t, StringIO.StringIO("a" * 1024))
293
294 with open(tmpname, "r+b") as fobj:
295 fobj.truncate(size)
296
297 with tarfile.open(tmpname) as tar:
298 with self.assertRaisesRegexp(tarfile.ReadError, "unexpected end of data"):
299 for t in tar:
300 pass
301
302 with tarfile.open(tmpname) as tar:
303 t = tar.next()
304
305 with self.assertRaisesRegexp(tarfile.ReadError, "unexpected end of data"):
306 tar.extract(t, TEMPDIR)
307
308 with self.assertRaisesRegexp(tarfile.ReadError, "unexpected end of data"):
309 tar.extractfile(t).read()
310
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000311
312class MiscReadTest(CommonReadTest):
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200313 taropen = tarfile.TarFile.taropen
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000314
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000315 def test_no_name_argument(self):
Serhiy Storchaka7cc3b0a2014-07-22 10:39:59 +0300316 fobj = open(self.tarname, "rb")
317 tar = tarfile.open(fileobj=fobj, mode=self.mode)
318 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000319
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000320 def test_no_name_attribute(self):
321 data = open(self.tarname, "rb").read()
322 fobj = StringIO.StringIO(data)
323 self.assertRaises(AttributeError, getattr, fobj, "name")
324 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka7cc3b0a2014-07-22 10:39:59 +0300325 self.assertEqual(tar.name, None)
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000326
327 def test_empty_name_attribute(self):
328 data = open(self.tarname, "rb").read()
329 fobj = StringIO.StringIO(data)
330 fobj.name = ""
331 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka7cc3b0a2014-07-22 10:39:59 +0300332 self.assertEqual(tar.name, None)
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000333
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200334 def test_illegal_mode_arg(self):
335 with open(tmpname, 'wb'):
336 pass
337 self.addCleanup(os.unlink, tmpname)
338 with self.assertRaisesRegexp(ValueError, 'mode must be '):
339 tar = self.taropen(tmpname, 'q')
340 with self.assertRaisesRegexp(ValueError, 'mode must be '):
341 tar = self.taropen(tmpname, 'rw')
342 with self.assertRaisesRegexp(ValueError, 'mode must be '):
343 tar = self.taropen(tmpname, '')
344
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000345 def test_fileobj_with_offset(self):
346 # Skip the first member and store values from the second member
347 # of the testtar.
348 tar = tarfile.open(self.tarname, mode=self.mode)
349 tar.next()
350 t = tar.next()
351 name = t.name
352 offset = t.offset
353 data = tar.extractfile(t).read()
354 tar.close()
355
356 # Open the testtar and seek to the offset of the second member.
357 if self.mode.endswith(":gz"):
358 _open = gzip.GzipFile
359 elif self.mode.endswith(":bz2"):
360 _open = bz2.BZ2File
361 else:
362 _open = open
363 fobj = _open(self.tarname, "rb")
364 fobj.seek(offset)
365
366 # Test if the tarfile starts with the second member.
367 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
368 t = tar.next()
369 self.assertEqual(t.name, name)
370 # Read to the end of fileobj and test if seeking back to the
371 # beginning works.
372 tar.getmembers()
373 self.assertEqual(tar.extractfile(t).read(), data,
374 "seek back did not work")
375 tar.close()
376
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000377 def test_fail_comp(self):
378 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
379 if self.mode == "r:":
Zachary Ware1f702212013-12-10 14:09:20 -0600380 self.skipTest('needs a gz or bz2 mode')
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000381 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
382 fobj = open(tarname, "rb")
383 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
384
385 def test_v7_dirtype(self):
386 # Test old style dirtype member (bug #1336623):
387 # Old V7 tars create directory members using an AREGTYPE
388 # header with a "/" appended to the filename field.
389 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000390 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000391 "v7 dirtype failed")
392
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000393 def test_xstar_type(self):
394 # The xstar format stores extra atime and ctime fields inside the
395 # space reserved for the prefix field. The prefix field must be
396 # ignored in this case, otherwise it will mess up the name.
397 try:
398 self.tar.getmember("misc/regtype-xstar")
399 except KeyError:
400 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
401
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000402 def test_check_members(self):
403 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000404 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000405 "wrong mtime for %s" % tarinfo.name)
406 if not tarinfo.name.startswith("ustar/"):
407 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000408 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000409 "wrong uname for %s" % tarinfo.name)
410
411 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000412 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000413 "could not find all members")
414
415 def test_extract_hardlink(self):
416 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200417 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
418 tar.extract("ustar/regtype", TEMPDIR)
419 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000420
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000421 tar.extract("ustar/lnktype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200422 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
423 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
424 data = f.read()
425 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000426
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000427 tar.extract("ustar/symtype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200428 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
429 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
430 data = f.read()
431 self.assertEqual(md5sum(data), md5_regtype)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000432
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000433 def test_extractall(self):
434 # Test if extractall() correctly restores directory permissions
435 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000436 tar = tarfile.open(tarname, encoding="iso8859-1")
437 directories = [t for t in tar if t.isdir()]
438 tar.extractall(TEMPDIR, directories)
439 for tarinfo in directories:
440 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000441 if sys.platform != "win32":
442 # Win32 has no support for fine grained permissions.
443 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000444 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
445 tar.close()
446
Lars Gustäbel12adc652009-11-23 15:46:19 +0000447 def test_init_close_fobj(self):
448 # Issue #7341: Close the internal file object in the TarFile
449 # constructor in case of an error. For the test we rely on
450 # the fact that opening an empty file raises a ReadError.
451 empty = os.path.join(TEMPDIR, "empty")
452 open(empty, "wb").write("")
453
454 try:
455 tar = object.__new__(tarfile.TarFile)
456 try:
457 tar.__init__(empty)
458 except tarfile.ReadError:
459 self.assertTrue(tar.fileobj.closed)
460 else:
461 self.fail("ReadError not raised")
462 finally:
463 os.remove(empty)
464
Serhiy Storchakace34ba62013-05-09 14:22:05 +0300465 def test_parallel_iteration(self):
466 # Issue #16601: Restarting iteration over tarfile continued
467 # from where it left off.
468 with tarfile.open(self.tarname) as tar:
469 for m1, m2 in zip(tar, tar):
470 self.assertEqual(m1.offset, m2.offset)
471 self.assertEqual(m1.name, m2.name)
472
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000473
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000474class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000475
476 mode="r|"
477
478 def test_fileobj_regular_file(self):
479 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
480 fobj = self.tar.extractfile(tarinfo)
481 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000482 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000483 "regular file extraction failed")
484
485 def test_provoke_stream_error(self):
486 tarinfos = self.tar.getmembers()
487 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000488 self.assertRaises(tarfile.StreamError, f.read)
489
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000490 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000491 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000492 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000493
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000494 while True:
495 t1 = tar1.next()
496 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000497 if t1 is None:
498 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000499 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000500
501 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000502 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000503 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000504
505 v1 = tar1.extractfile(t1)
506 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000507 if v1 is None:
508 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000509 self.assertTrue(v2 is not None, "stream.extractfile() failed")
510 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000511
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000512 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000513
Georg Brandla32e0a02006-10-24 16:54:16 +0000514
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000515class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000516
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000517 def _testfunc_file(self, name, mode):
518 try:
519 tarfile.open(name, mode)
520 except tarfile.ReadError:
521 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000522
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000523 def _testfunc_fileobj(self, name, mode):
524 try:
525 tarfile.open(name, mode, fileobj=open(name, "rb"))
526 except tarfile.ReadError:
527 self.fail()
528
529 def _test_modes(self, testfunc):
530 testfunc(tarname, "r")
531 testfunc(tarname, "r:")
532 testfunc(tarname, "r:*")
533 testfunc(tarname, "r|")
534 testfunc(tarname, "r|*")
535
536 if gzip:
537 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
538 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
539 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
540 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
541
542 testfunc(gzipname, "r")
543 testfunc(gzipname, "r:*")
544 testfunc(gzipname, "r:gz")
545 testfunc(gzipname, "r|*")
546 testfunc(gzipname, "r|gz")
547
548 if bz2:
549 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
550 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
551 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
552 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
553
554 testfunc(bz2name, "r")
555 testfunc(bz2name, "r:*")
556 testfunc(bz2name, "r:bz2")
557 testfunc(bz2name, "r|*")
558 testfunc(bz2name, "r|bz2")
559
560 def test_detect_file(self):
561 self._test_modes(self._testfunc_file)
562
563 def test_detect_fileobj(self):
564 self._test_modes(self._testfunc_fileobj)
565
Zachary Ware1f702212013-12-10 14:09:20 -0600566 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbel9a388632011-12-06 13:07:09 +0100567 def test_detect_stream_bz2(self):
568 # Originally, tarfile's stream detection looked for the string
569 # "BZh91" at the start of the file. This is incorrect because
570 # the '9' represents the blocksize (900kB). If the file was
571 # compressed using another blocksize autodetection fails.
Lars Gustäbel9a388632011-12-06 13:07:09 +0100572 with open(tarname, "rb") as fobj:
573 data = fobj.read()
574
575 # Compress with blocksize 100kB, the file starts with "BZh11".
576 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
577 fobj.write(data)
578
579 self._testfunc_file(tmpname, "r|*")
580
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000581
582class MemberReadTest(ReadTest):
583
584 def _test_member(self, tarinfo, chksum=None, **kwargs):
585 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000586 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000587 "wrong md5sum for %s" % tarinfo.name)
588
589 kwargs["mtime"] = 07606136617
590 kwargs["uid"] = 1000
591 kwargs["gid"] = 100
592 if "old-v7" not in tarinfo.name:
593 # V7 tar can't handle alphabetic owners.
594 kwargs["uname"] = "tarfile"
595 kwargs["gname"] = "tarfile"
596 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000597 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000598 "wrong value in %s field of %s" % (k, tarinfo.name))
599
600 def test_find_regtype(self):
601 tarinfo = self.tar.getmember("ustar/regtype")
602 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
603
604 def test_find_conttype(self):
605 tarinfo = self.tar.getmember("ustar/conttype")
606 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
607
608 def test_find_dirtype(self):
609 tarinfo = self.tar.getmember("ustar/dirtype")
610 self._test_member(tarinfo, size=0)
611
612 def test_find_dirtype_with_size(self):
613 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
614 self._test_member(tarinfo, size=255)
615
616 def test_find_lnktype(self):
617 tarinfo = self.tar.getmember("ustar/lnktype")
618 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
619
620 def test_find_symtype(self):
621 tarinfo = self.tar.getmember("ustar/symtype")
622 self._test_member(tarinfo, size=0, linkname="regtype")
623
624 def test_find_blktype(self):
625 tarinfo = self.tar.getmember("ustar/blktype")
626 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
627
628 def test_find_chrtype(self):
629 tarinfo = self.tar.getmember("ustar/chrtype")
630 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
631
632 def test_find_fifotype(self):
633 tarinfo = self.tar.getmember("ustar/fifotype")
634 self._test_member(tarinfo, size=0)
635
636 def test_find_sparse(self):
637 tarinfo = self.tar.getmember("ustar/sparse")
638 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
639
640 def test_find_umlauts(self):
Ezio Melotti8861b292016-01-13 19:36:49 +0200641 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000642 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
643
644 def test_find_ustar_longname(self):
645 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000646 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000647
648 def test_find_regtype_oldv7(self):
649 tarinfo = self.tar.getmember("misc/regtype-old-v7")
650 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
651
652 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000653 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Ezio Melotti8861b292016-01-13 19:36:49 +0200654 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000655 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
656
657
658class LongnameTest(ReadTest):
659
660 def test_read_longname(self):
661 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000662 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000663 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000664 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000665 except KeyError:
666 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000667 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000668
669 def test_read_longlink(self):
670 longname = self.subdir + "/" + "123/" * 125 + "longname"
671 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
672 try:
673 tarinfo = self.tar.getmember(longlink)
674 except KeyError:
675 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000676 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000677
678 def test_truncated_longname(self):
679 longname = self.subdir + "/" + "123/" * 125 + "longname"
680 tarinfo = self.tar.getmember(longname)
681 offset = tarinfo.offset
682 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000683 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000684 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
685
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000686 def test_header_offset(self):
687 # Test if the start offset of the TarInfo object includes
688 # the preceding extended header.
689 longname = self.subdir + "/" + "123/" * 125 + "longname"
690 offset = self.tar.getmember(longname).offset
691 fobj = open(tarname)
692 fobj.seek(offset)
693 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
694 self.assertEqual(tarinfo.type, self.longnametype)
695
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000696
697class GNUReadTest(LongnameTest):
698
699 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000700 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000701
702 def test_sparse_file(self):
703 tarinfo1 = self.tar.getmember("ustar/sparse")
704 fobj1 = self.tar.extractfile(tarinfo1)
705 tarinfo2 = self.tar.getmember("gnu/sparse")
706 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000707 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000708 "sparse file extraction failed")
709
710
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000711class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000712
713 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000714 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000715
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000716 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000717 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000718
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000719 tarinfo = tar.getmember("pax/regtype1")
720 self.assertEqual(tarinfo.uname, "foo")
721 self.assertEqual(tarinfo.gname, "bar")
Ezio Melotti8861b292016-01-13 19:36:49 +0200722 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000723
724 tarinfo = tar.getmember("pax/regtype2")
725 self.assertEqual(tarinfo.uname, "")
726 self.assertEqual(tarinfo.gname, "bar")
Ezio Melotti8861b292016-01-13 19:36:49 +0200727 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000728
729 tarinfo = tar.getmember("pax/regtype3")
730 self.assertEqual(tarinfo.uname, "tarfile")
731 self.assertEqual(tarinfo.gname, "tarfile")
Ezio Melotti8861b292016-01-13 19:36:49 +0200732 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000733
734 def test_pax_number_fields(self):
735 # All following number fields are read from the pax header.
736 tar = tarfile.open(tarname, encoding="iso8859-1")
737 tarinfo = tar.getmember("pax/regtype4")
738 self.assertEqual(tarinfo.size, 7011)
739 self.assertEqual(tarinfo.uid, 123)
740 self.assertEqual(tarinfo.gid, 123)
741 self.assertEqual(tarinfo.mtime, 1041808783.0)
742 self.assertEqual(type(tarinfo.mtime), float)
743 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
744 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000745
746
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000747class WriteTestBase(unittest.TestCase):
748 # Put all write tests in here that are supposed to be tested
749 # in all possible mode combinations.
750
751 def test_fileobj_no_close(self):
752 fobj = StringIO.StringIO()
753 tar = tarfile.open(fileobj=fobj, mode=self.mode)
754 tar.addfile(tarfile.TarInfo("foo"))
755 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000756 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Serhiy Storchakacdf1ebd2014-01-18 15:54:32 +0200757 # Issue #20238: Incomplete gzip output with mode="w:gz"
758 data = fobj.getvalue()
759 del tar
760 test_support.gc_collect()
761 self.assertFalse(fobj.closed)
762 self.assertEqual(data, fobj.getvalue())
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000763
764
765class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000766
767 mode = "w:"
768
769 def test_100_char_name(self):
770 # The name field in a tar header stores strings of at most 100 chars.
771 # If a string is shorter than 100 chars it has to be padded with '\0',
772 # which implies that a string of exactly 100 chars is stored without
773 # a trailing '\0'.
774 name = "0123456789" * 10
775 tar = tarfile.open(tmpname, self.mode)
776 t = tarfile.TarInfo(name)
777 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000778 tar.close()
779
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000780 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000781 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000782 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000783 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000784
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000785 def test_tar_size(self):
786 # Test for bug #1013882.
787 tar = tarfile.open(tmpname, self.mode)
788 path = os.path.join(TEMPDIR, "file")
789 fobj = open(path, "wb")
790 fobj.write("aaa")
791 fobj.close()
792 tar.add(path)
793 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000794 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000795 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000796
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000797 # The test_*_size tests test for bug #1167128.
798 def test_file_size(self):
799 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000800
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000801 path = os.path.join(TEMPDIR, "file")
802 fobj = open(path, "wb")
803 fobj.close()
804 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000805 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000806
807 fobj = open(path, "wb")
808 fobj.write("aaa")
809 fobj.close()
810 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000811 self.assertEqual(tarinfo.size, 3)
812
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000813 tar.close()
814
815 def test_directory_size(self):
816 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000817 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000818 try:
819 tar = tarfile.open(tmpname, self.mode)
820 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000821 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000822 finally:
823 os.rmdir(path)
824
825 def test_link_size(self):
826 if hasattr(os, "link"):
827 link = os.path.join(TEMPDIR, "link")
828 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000829 fobj = open(target, "wb")
830 fobj.write("aaa")
831 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000832 os.link(target, link)
833 try:
834 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000835 # Record the link target in the inodes list.
836 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000837 tarinfo = tar.gettarinfo(link)
838 self.assertEqual(tarinfo.size, 0)
839 finally:
840 os.remove(target)
841 os.remove(link)
842
843 def test_symlink_size(self):
844 if hasattr(os, "symlink"):
845 path = os.path.join(TEMPDIR, "symlink")
846 os.symlink("link_target", path)
847 try:
848 tar = tarfile.open(tmpname, self.mode)
849 tarinfo = tar.gettarinfo(path)
850 self.assertEqual(tarinfo.size, 0)
851 finally:
852 os.remove(path)
853
854 def test_add_self(self):
855 # Test for #1257255.
856 dstname = os.path.abspath(tmpname)
857
858 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000859 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000860
861 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000862 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000863
864 cwd = os.getcwd()
865 os.chdir(TEMPDIR)
866 tar.add(dstname)
867 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000868 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000869
Lars Gustäbel104490e2007-06-18 11:42:11 +0000870 def test_exclude(self):
871 tempdir = os.path.join(TEMPDIR, "exclude")
872 os.mkdir(tempdir)
873 try:
874 for name in ("foo", "bar", "baz"):
875 name = os.path.join(tempdir, name)
876 open(name, "wb").close()
877
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000878 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000879
880 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000881 with test_support.check_warnings(("use the filter argument",
882 DeprecationWarning)):
883 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000884 tar.close()
885
886 tar = tarfile.open(tmpname, "r")
887 self.assertEqual(len(tar.getmembers()), 1)
888 self.assertEqual(tar.getnames()[0], "empty_dir")
889 finally:
890 shutil.rmtree(tempdir)
891
Lars Gustäbel21121e62009-09-12 10:28:15 +0000892 def test_filter(self):
893 tempdir = os.path.join(TEMPDIR, "filter")
894 os.mkdir(tempdir)
895 try:
896 for name in ("foo", "bar", "baz"):
897 name = os.path.join(tempdir, name)
898 open(name, "wb").close()
899
900 def filter(tarinfo):
901 if os.path.basename(tarinfo.name) == "bar":
902 return
903 tarinfo.uid = 123
904 tarinfo.uname = "foo"
905 return tarinfo
906
907 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
908 tar.add(tempdir, arcname="empty_dir", filter=filter)
909 tar.close()
910
911 tar = tarfile.open(tmpname, "r")
912 for tarinfo in tar:
913 self.assertEqual(tarinfo.uid, 123)
914 self.assertEqual(tarinfo.uname, "foo")
915 self.assertEqual(len(tar.getmembers()), 3)
916 tar.close()
917 finally:
918 shutil.rmtree(tempdir)
919
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000920 # Guarantee that stored pathnames are not modified. Don't
921 # remove ./ or ../ or double slashes. Still make absolute
922 # pathnames relative.
923 # For details see bug #6054.
924 def _test_pathname(self, path, cmp_path=None, dir=False):
925 # Create a tarfile with an empty member named path
926 # and compare the stored name with the original.
927 foo = os.path.join(TEMPDIR, "foo")
928 if not dir:
929 open(foo, "w").close()
930 else:
931 os.mkdir(foo)
932
933 tar = tarfile.open(tmpname, self.mode)
934 tar.add(foo, arcname=path)
935 tar.close()
936
937 tar = tarfile.open(tmpname, "r")
938 t = tar.next()
939 tar.close()
940
941 if not dir:
942 os.remove(foo)
943 else:
944 os.rmdir(foo)
945
946 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
947
948 def test_pathnames(self):
949 self._test_pathname("foo")
950 self._test_pathname(os.path.join("foo", ".", "bar"))
951 self._test_pathname(os.path.join("foo", "..", "bar"))
952 self._test_pathname(os.path.join(".", "foo"))
953 self._test_pathname(os.path.join(".", "foo", "."))
954 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
955 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
956 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
957 self._test_pathname(os.path.join("..", "foo"))
958 self._test_pathname(os.path.join("..", "foo", ".."))
959 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
960 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
961
962 self._test_pathname("foo" + os.sep + os.sep + "bar")
963 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
964
965 def test_abs_pathnames(self):
966 if sys.platform == "win32":
967 self._test_pathname("C:\\foo", "foo")
968 else:
969 self._test_pathname("/foo", "foo")
970 self._test_pathname("///foo", "foo")
971
972 def test_cwd(self):
973 # Test adding the current working directory.
Serhiy Storchaka7c7b4b52015-09-06 14:16:18 +0300974 with support.change_cwd(TEMPDIR):
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000975 open("foo", "w").close()
976
977 tar = tarfile.open(tmpname, self.mode)
978 tar.add(".")
979 tar.close()
980
981 tar = tarfile.open(tmpname, "r")
982 for t in tar:
Serhiy Storchaka88761452012-12-28 00:32:19 +0200983 self.assertTrue(t.name == "." or t.name.startswith("./"))
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000984 tar.close()
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000985
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800986 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800987 def test_extractall_symlinks(self):
988 # Test if extractall works properly when tarfile contains symlinks
989 tempdir = os.path.join(TEMPDIR, "testsymlinks")
990 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
991 os.mkdir(tempdir)
992 try:
993 source_file = os.path.join(tempdir,'source')
994 target_file = os.path.join(tempdir,'symlink')
995 with open(source_file,'w') as f:
996 f.write('something\n')
997 os.symlink(source_file, target_file)
998 tar = tarfile.open(temparchive,'w')
999 tar.add(source_file, arcname=os.path.basename(source_file))
1000 tar.add(target_file, arcname=os.path.basename(target_file))
1001 tar.close()
1002 # Let's extract it to the location which contains the symlink
1003 tar = tarfile.open(temparchive,'r')
1004 # this should not raise OSError: [Errno 17] File exists
1005 try:
1006 tar.extractall(path=tempdir)
1007 except OSError:
1008 self.fail("extractall failed with symlinked files")
1009 finally:
1010 tar.close()
1011 finally:
1012 os.unlink(temparchive)
1013 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001014
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +08001015 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
1016 def test_extractall_broken_symlinks(self):
1017 # Test if extractall works properly when tarfile contains broken
1018 # symlinks
1019 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1020 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1021 os.mkdir(tempdir)
1022 try:
1023 source_file = os.path.join(tempdir,'source')
1024 target_file = os.path.join(tempdir,'symlink')
1025 with open(source_file,'w') as f:
1026 f.write('something\n')
1027 os.symlink(source_file, target_file)
1028 tar = tarfile.open(temparchive,'w')
1029 tar.add(target_file, arcname=os.path.basename(target_file))
1030 tar.close()
1031 # remove the real file
1032 os.unlink(source_file)
1033 # Let's extract it to the location which contains the symlink
1034 tar = tarfile.open(temparchive,'r')
1035 # this should not raise OSError: [Errno 17] File exists
1036 try:
1037 tar.extractall(path=tempdir)
1038 except OSError:
1039 self.fail("extractall failed with broken symlinked files")
1040 finally:
1041 tar.close()
1042 finally:
1043 os.unlink(temparchive)
1044 shutil.rmtree(tempdir)
1045
1046 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
1047 def test_extractall_hardlinks(self):
1048 # Test if extractall works properly when tarfile contains symlinks
1049 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1050 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1051 os.mkdir(tempdir)
1052 try:
1053 source_file = os.path.join(tempdir,'source')
1054 target_file = os.path.join(tempdir,'symlink')
1055 with open(source_file,'w') as f:
1056 f.write('something\n')
1057 os.link(source_file, target_file)
1058 tar = tarfile.open(temparchive,'w')
1059 tar.add(source_file, arcname=os.path.basename(source_file))
1060 tar.add(target_file, arcname=os.path.basename(target_file))
1061 tar.close()
1062 # Let's extract it to the location which contains the symlink
1063 tar = tarfile.open(temparchive,'r')
1064 # this should not raise OSError: [Errno 17] File exists
1065 try:
1066 tar.extractall(path=tempdir)
1067 except OSError:
1068 self.fail("extractall failed with linked files")
1069 finally:
1070 tar.close()
1071 finally:
1072 os.unlink(temparchive)
1073 shutil.rmtree(tempdir)
1074
Serhiy Storchaka7a278da2014-01-18 16:14:00 +02001075 def test_open_nonwritable_fileobj(self):
1076 for exctype in IOError, EOFError, RuntimeError:
1077 class BadFile(StringIO.StringIO):
1078 first = True
1079 def write(self, data):
1080 if self.first:
1081 self.first = False
1082 raise exctype
1083
1084 f = BadFile()
1085 with self.assertRaises(exctype):
1086 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1087 format=tarfile.PAX_FORMAT,
1088 pax_headers={'non': 'empty'})
1089 self.assertFalse(f.closed)
1090
Lars Gustäbelb1a54a32008-05-27 12:39:23 +00001091class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001092
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001093 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +00001094
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001095 def test_stream_padding(self):
1096 # Test for bug #1543303.
1097 tar = tarfile.open(tmpname, self.mode)
1098 tar.close()
1099
1100 if self.mode.endswith("gz"):
1101 fobj = gzip.GzipFile(tmpname)
1102 data = fobj.read()
1103 fobj.close()
1104 elif self.mode.endswith("bz2"):
1105 dec = bz2.BZ2Decompressor()
1106 data = open(tmpname, "rb").read()
1107 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001108 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001109 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +00001110 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001111 fobj = open(tmpname, "rb")
1112 data = fobj.read()
1113 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +00001114
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001115 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +00001116 "incorrect zero padding")
1117
Zachary Ware1f702212013-12-10 14:09:20 -06001118 @unittest.skipIf(sys.platform == 'win32', 'not appropriate for Windows')
1119 @unittest.skipUnless(hasattr(os, 'umask'), 'requires os.umask')
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001120 def test_file_mode(self):
1121 # Test for issue #8464: Create files with correct
1122 # permissions.
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001123 if os.path.exists(tmpname):
1124 os.remove(tmpname)
1125
1126 original_umask = os.umask(0022)
1127 try:
1128 tar = tarfile.open(tmpname, self.mode)
1129 tar.close()
1130 mode = os.stat(tmpname).st_mode & 0777
1131 self.assertEqual(mode, 0644, "wrong file permissions")
1132 finally:
1133 os.umask(original_umask)
1134
Lars Gustäbel7d4d0742011-12-21 19:27:50 +01001135 def test_issue13639(self):
1136 try:
1137 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1138 pass
1139 except UnicodeDecodeError:
1140 self.fail("_Stream failed to write unicode filename")
1141
Neal Norwitz8a519392006-08-21 17:59:46 +00001142
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001143class GNUWriteTest(unittest.TestCase):
1144 # This testcase checks for correct creation of GNU Longname
1145 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001146
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001147 def _length(self, s):
1148 blocks, remainder = divmod(len(s) + 1, 512)
1149 if remainder:
1150 blocks += 1
1151 return blocks * 512
1152
1153 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001154 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001155 count = 512
1156
1157 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001158 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001159 count += 512
1160 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001161 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001162 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001163 count += 512
1164 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001165 return count
1166
1167 def _test(self, name, link=None):
1168 tarinfo = tarfile.TarInfo(name)
1169 if link:
1170 tarinfo.linkname = link
1171 tarinfo.type = tarfile.LNKTYPE
1172
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001173 tar = tarfile.open(tmpname, "w")
1174 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001175 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001176
1177 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001178 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001179 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001180
Georg Brandl87fa5592006-12-06 22:21:18 +00001181 tar.close()
1182
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001183 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001184 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001185 self.assertIsNotNone(member,
1186 "unable to read longname member")
1187 self.assertEqual(tarinfo.name, member.name,
1188 "unable to read longname member")
1189 self.assertEqual(tarinfo.linkname, member.linkname,
1190 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001191
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001192 def test_longname_1023(self):
1193 self._test(("longnam/" * 127) + "longnam")
1194
1195 def test_longname_1024(self):
1196 self._test(("longnam/" * 127) + "longname")
1197
1198 def test_longname_1025(self):
1199 self._test(("longnam/" * 127) + "longname_")
1200
1201 def test_longlink_1023(self):
1202 self._test("name", ("longlnk/" * 127) + "longlnk")
1203
1204 def test_longlink_1024(self):
1205 self._test("name", ("longlnk/" * 127) + "longlink")
1206
1207 def test_longlink_1025(self):
1208 self._test("name", ("longlnk/" * 127) + "longlink_")
1209
1210 def test_longnamelink_1023(self):
1211 self._test(("longnam/" * 127) + "longnam",
1212 ("longlnk/" * 127) + "longlnk")
1213
1214 def test_longnamelink_1024(self):
1215 self._test(("longnam/" * 127) + "longname",
1216 ("longlnk/" * 127) + "longlink")
1217
1218 def test_longnamelink_1025(self):
1219 self._test(("longnam/" * 127) + "longname_",
1220 ("longlnk/" * 127) + "longlink_")
1221
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001222
1223class HardlinkTest(unittest.TestCase):
1224 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001225
1226 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001227 self.foo = os.path.join(TEMPDIR, "foo")
1228 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001229
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001230 fobj = open(self.foo, "wb")
1231 fobj.write("foo")
1232 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001233
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001234 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001235
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001236 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001237 self.tar.add(self.foo)
1238
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001239 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001240 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001241 os.remove(self.foo)
1242 os.remove(self.bar)
1243
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001244 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001245 # The same name will be added as a REGTYPE every
1246 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001247 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001248 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001249 "add file as regular failed")
1250
1251 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001252 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001253 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001254 "add file as hardlink failed")
1255
1256 def test_dereference_hardlink(self):
1257 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001258 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001259 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001260 "dereferencing hardlink failed")
1261
Neal Norwitza4f651a2004-07-20 22:07:44 +00001262
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001263class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001264
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001265 def _test(self, name, link=None):
1266 # See GNUWriteTest.
1267 tarinfo = tarfile.TarInfo(name)
1268 if link:
1269 tarinfo.linkname = link
1270 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001271
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001272 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1273 tar.addfile(tarinfo)
1274 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001275
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001276 tar = tarfile.open(tmpname)
1277 if link:
1278 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001279 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001280 else:
1281 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001282 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001283
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001284 def test_pax_global_header(self):
1285 pax_headers = {
1286 u"foo": u"bar",
1287 u"uid": u"0",
1288 u"mtime": u"1.23",
Ezio Melotti8861b292016-01-13 19:36:49 +02001289 u"test": u"\xe4\xf6\xfc",
1290 u"\xe4\xf6\xfc": u"test"}
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001291
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001292 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001293 pax_headers=pax_headers)
1294 tar.addfile(tarfile.TarInfo("test"))
1295 tar.close()
1296
1297 # Test if the global header was written correctly.
1298 tar = tarfile.open(tmpname, encoding="iso8859-1")
1299 self.assertEqual(tar.pax_headers, pax_headers)
1300 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1301
1302 # Test if all the fields are unicode.
1303 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001304 self.assertTrue(type(key) is unicode)
1305 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001306 if key in tarfile.PAX_NUMBER_FIELDS:
1307 try:
1308 tarfile.PAX_NUMBER_FIELDS[key](val)
1309 except (TypeError, ValueError):
1310 self.fail("unable to convert pax header field")
1311
1312 def test_pax_extended_header(self):
1313 # The fields from the pax header have priority over the
1314 # TarInfo.
1315 pax_headers = {u"path": u"foo", u"uid": u"123"}
1316
1317 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1318 t = tarfile.TarInfo()
Ezio Melotti8861b292016-01-13 19:36:49 +02001319 t.name = u"\xe4\xf6\xfc" # non-ASCII
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001320 t.uid = 8**8 # too large
1321 t.pax_headers = pax_headers
1322 tar.addfile(t)
1323 tar.close()
1324
1325 tar = tarfile.open(tmpname, encoding="iso8859-1")
1326 t = tar.getmembers()[0]
1327 self.assertEqual(t.pax_headers, pax_headers)
1328 self.assertEqual(t.name, "foo")
1329 self.assertEqual(t.uid, 123)
1330
1331
1332class UstarUnicodeTest(unittest.TestCase):
1333 # All *UnicodeTests FIXME
1334
1335 format = tarfile.USTAR_FORMAT
1336
1337 def test_iso8859_1_filename(self):
1338 self._test_unicode_filename("iso8859-1")
1339
1340 def test_utf7_filename(self):
1341 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001342
1343 def test_utf8_filename(self):
1344 self._test_unicode_filename("utf8")
1345
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001346 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001347 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Ezio Melotti8861b292016-01-13 19:36:49 +02001348 name = u"\xe4\xf6\xfc"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001349 tar.addfile(tarfile.TarInfo(name))
1350 tar.close()
1351
1352 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001353 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001354 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001355 tar.close()
1356
1357 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001358 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1359 tarinfo = tarfile.TarInfo()
1360
Ezio Melotti8861b292016-01-13 19:36:49 +02001361 tarinfo.name = "\xe4\xf6\xfc"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001362 if self.format == tarfile.PAX_FORMAT:
1363 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1364 else:
1365 tar.addfile(tarinfo)
1366
Ezio Melotti8861b292016-01-13 19:36:49 +02001367 tarinfo.name = u"\xe4\xf6\xfc"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001368 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1369
1370 tarinfo.name = "foo"
Ezio Melotti8861b292016-01-13 19:36:49 +02001371 tarinfo.uname = u"\xe4\xf6\xfc"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001372 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1373
1374 def test_unicode_argument(self):
1375 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1376 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001377 self.assertTrue(type(t.name) is str)
1378 self.assertTrue(type(t.linkname) is str)
1379 self.assertTrue(type(t.uname) is str)
1380 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001381 tar.close()
1382
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001383 def test_uname_unicode(self):
Ezio Melotti8861b292016-01-13 19:36:49 +02001384 for name in (u"\xe4\xf6\xfc", "\xe4\xf6\xfc"):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001385 t = tarfile.TarInfo("foo")
1386 t.uname = name
1387 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001388
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001389 fobj = StringIO.StringIO()
1390 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1391 tar.addfile(t)
1392 tar.close()
1393 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001394
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001395 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1396 t = tar.getmember("foo")
Ezio Melotti8861b292016-01-13 19:36:49 +02001397 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1398 self.assertEqual(t.gname, "\xe4\xf6\xfc")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001399
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001400
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001401class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001402
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001403 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001404
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001405
1406class PaxUnicodeTest(UstarUnicodeTest):
1407
1408 format = tarfile.PAX_FORMAT
1409
1410 def _create_unicode_name(self, name):
1411 tar = tarfile.open(tmpname, "w", format=self.format)
1412 t = tarfile.TarInfo()
1413 t.pax_headers["path"] = name
1414 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001415 tar.close()
1416
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001417 def test_error_handlers(self):
1418 # Test if the unicode error handlers work correctly for characters
1419 # that cannot be expressed in a given encoding.
Ezio Melotti8861b292016-01-13 19:36:49 +02001420 self._create_unicode_name(u"\xe4\xf6\xfc")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001421
Ezio Melotti8861b292016-01-13 19:36:49 +02001422 for handler, name in (("utf-8", u"\xe4\xf6\xfc".encode("utf8")),
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001423 ("replace", "???"), ("ignore", "")):
1424 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1425 errors=handler)
1426 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001427
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001428 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1429 encoding="ascii", errors="strict")
1430
1431 def test_error_handler_utf8(self):
1432 # Create a pathname that has one component representable using
1433 # iso8859-1 and the other only in iso8859-15.
Ezio Melotti8861b292016-01-13 19:36:49 +02001434 self._create_unicode_name(u"\xe4\xf6\xfc/\u20ac")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001435
1436 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1437 errors="utf-8")
Ezio Melotti8861b292016-01-13 19:36:49 +02001438 self.assertEqual(tar.getnames()[0], "\xe4\xf6\xfc/" + u"\u20ac".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001439
Georg Brandlded1c4d2006-12-20 11:55:16 +00001440
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001441class AppendTest(unittest.TestCase):
1442 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001443
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001444 def setUp(self):
1445 self.tarname = tmpname
1446 if os.path.exists(self.tarname):
1447 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001448
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001449 def _add_testfile(self, fileobj=None):
1450 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1451 tar.addfile(tarfile.TarInfo("bar"))
1452 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001453
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001454 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001455 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001456 t = src.getmember("ustar/regtype")
1457 t.name = "foo"
1458 f = src.extractfile(t)
1459 tar = tarfile.open(self.tarname, mode)
1460 tar.addfile(t, f)
1461 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001462
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001463 def _test(self, names=["bar"], fileobj=None):
1464 tar = tarfile.open(self.tarname, fileobj=fileobj)
1465 self.assertEqual(tar.getnames(), names)
1466
1467 def test_non_existing(self):
1468 self._add_testfile()
1469 self._test()
1470
1471 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001472 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001473 self._add_testfile()
1474 self._test()
1475
1476 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001477 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001478 self._add_testfile(fobj)
1479 fobj.seek(0)
1480 self._test(fileobj=fobj)
1481
1482 def test_fileobj(self):
1483 self._create_testtar()
1484 data = open(self.tarname).read()
1485 fobj = StringIO.StringIO(data)
1486 self._add_testfile(fobj)
1487 fobj.seek(0)
1488 self._test(names=["foo", "bar"], fileobj=fobj)
1489
1490 def test_existing(self):
1491 self._create_testtar()
1492 self._add_testfile()
1493 self._test(names=["foo", "bar"])
1494
Zachary Ware1f702212013-12-10 14:09:20 -06001495 @unittest.skipUnless(gzip, 'requires gzip')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001496 def test_append_gz(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001497 self._create_testtar("w:gz")
1498 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1499
Zachary Ware1f702212013-12-10 14:09:20 -06001500 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001501 def test_append_bz2(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001502 self._create_testtar("w:bz2")
1503 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1504
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001505 # Append mode is supposed to fail if the tarfile to append to
1506 # does not end with a zero block.
1507 def _test_error(self, data):
1508 open(self.tarname, "wb").write(data)
1509 self.assertRaises(tarfile.ReadError, self._add_testfile)
1510
1511 def test_null(self):
1512 self._test_error("")
1513
1514 def test_incomplete(self):
1515 self._test_error("\0" * 13)
1516
1517 def test_premature_eof(self):
1518 data = tarfile.TarInfo("foo").tobuf()
1519 self._test_error(data)
1520
1521 def test_trailing_garbage(self):
1522 data = tarfile.TarInfo("foo").tobuf()
1523 self._test_error(data + "\0" * 13)
1524
1525 def test_invalid(self):
1526 self._test_error("a" * 512)
1527
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001528
1529class LimitsTest(unittest.TestCase):
1530
1531 def test_ustar_limits(self):
1532 # 100 char name
1533 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001534 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001535
1536 # 101 char name that cannot be stored
1537 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001538 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001539
1540 # 256 char name with a slash at pos 156
1541 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001542 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001543
1544 # 256 char name that cannot be stored
1545 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001546 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001547
1548 # 512 char name
1549 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001550 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001551
1552 # 512 char linkname
1553 tarinfo = tarfile.TarInfo("longlink")
1554 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001555 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001556
1557 # uid > 8 digits
1558 tarinfo = tarfile.TarInfo("name")
1559 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001560 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001561
1562 def test_gnu_limits(self):
1563 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001564 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001565
1566 tarinfo = tarfile.TarInfo("longlink")
1567 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001568 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001569
1570 # uid >= 256 ** 7
1571 tarinfo = tarfile.TarInfo("name")
1572 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001573 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001574
1575 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001576 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001577 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001578
1579 tarinfo = tarfile.TarInfo("longlink")
1580 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001581 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001582
1583 tarinfo = tarfile.TarInfo("name")
1584 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001585 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001586
1587
Lars Gustäbeld0480032015-07-02 19:37:08 +02001588class MiscTest(unittest.TestCase):
1589
1590 def test_read_number_fields(self):
1591 # Issue 24514: Test if empty number fields are converted to zero.
1592 self.assertEqual(tarfile.nti("\0"), 0)
1593 self.assertEqual(tarfile.nti(" \0"), 0)
1594
1595
Lars Gustäbel64581042010-03-03 11:55:48 +00001596class ContextManagerTest(unittest.TestCase):
1597
1598 def test_basic(self):
1599 with tarfile.open(tarname) as tar:
1600 self.assertFalse(tar.closed, "closed inside runtime context")
1601 self.assertTrue(tar.closed, "context manager failed")
1602
1603 def test_closed(self):
1604 # The __enter__() method is supposed to raise IOError
1605 # if the TarFile object is already closed.
1606 tar = tarfile.open(tarname)
1607 tar.close()
1608 with self.assertRaises(IOError):
1609 with tar:
1610 pass
1611
1612 def test_exception(self):
1613 # Test if the IOError exception is passed through properly.
1614 with self.assertRaises(Exception) as exc:
1615 with tarfile.open(tarname) as tar:
1616 raise IOError
1617 self.assertIsInstance(exc.exception, IOError,
1618 "wrong exception raised in context manager")
1619 self.assertTrue(tar.closed, "context manager failed")
1620
1621 def test_no_eof(self):
1622 # __exit__() must not write end-of-archive blocks if an
1623 # exception was raised.
1624 try:
1625 with tarfile.open(tmpname, "w") as tar:
1626 raise Exception
1627 except:
1628 pass
1629 self.assertEqual(os.path.getsize(tmpname), 0,
1630 "context manager wrote an end-of-archive block")
1631 self.assertTrue(tar.closed, "context manager failed")
1632
1633 def test_eof(self):
1634 # __exit__() must write end-of-archive blocks, i.e. call
1635 # TarFile.close() if there was no error.
1636 with tarfile.open(tmpname, "w"):
1637 pass
1638 self.assertNotEqual(os.path.getsize(tmpname), 0,
1639 "context manager wrote no end-of-archive block")
1640
1641 def test_fileobj(self):
1642 # Test that __exit__() did not close the external file
1643 # object.
1644 fobj = open(tmpname, "wb")
1645 try:
1646 with tarfile.open(fileobj=fobj, mode="w") as tar:
1647 raise Exception
1648 except:
1649 pass
1650 self.assertFalse(fobj.closed, "external file object was closed")
1651 self.assertTrue(tar.closed, "context manager failed")
1652 fobj.close()
1653
1654
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001655class LinkEmulationTest(ReadTest):
1656
1657 # Test for issue #8741 regression. On platforms that do not support
1658 # symbolic or hard links tarfile tries to extract these types of members as
1659 # the regular files they point to.
1660 def _test_link_extraction(self, name):
1661 self.tar.extract(name, TEMPDIR)
1662 data = open(os.path.join(TEMPDIR, name), "rb").read()
1663 self.assertEqual(md5sum(data), md5_regtype)
1664
1665 def test_hardlink_extraction1(self):
1666 self._test_link_extraction("ustar/lnktype")
1667
1668 def test_hardlink_extraction2(self):
1669 self._test_link_extraction("./ustar/linktest2/lnktype")
1670
1671 def test_symlink_extraction1(self):
1672 self._test_link_extraction("ustar/symtype")
1673
1674 def test_symlink_extraction2(self):
1675 self._test_link_extraction("./ustar/linktest2/symtype")
1676
1677
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001678class GzipMiscReadTest(MiscReadTest):
1679 tarname = gzipname
1680 mode = "r:gz"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001681 taropen = tarfile.TarFile.gzopen
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001682class GzipUstarReadTest(UstarReadTest):
1683 tarname = gzipname
1684 mode = "r:gz"
1685class GzipStreamReadTest(StreamReadTest):
1686 tarname = gzipname
1687 mode = "r|gz"
1688class GzipWriteTest(WriteTest):
1689 mode = "w:gz"
1690class GzipStreamWriteTest(StreamWriteTest):
1691 mode = "w|gz"
1692
1693
1694class Bz2MiscReadTest(MiscReadTest):
1695 tarname = bz2name
1696 mode = "r:bz2"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001697 taropen = tarfile.TarFile.bz2open
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001698class Bz2UstarReadTest(UstarReadTest):
1699 tarname = bz2name
1700 mode = "r:bz2"
1701class Bz2StreamReadTest(StreamReadTest):
1702 tarname = bz2name
1703 mode = "r|bz2"
1704class Bz2WriteTest(WriteTest):
1705 mode = "w:bz2"
1706class Bz2StreamWriteTest(StreamWriteTest):
1707 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001708
Lars Gustäbel2020a592009-03-22 20:09:33 +00001709class Bz2PartialReadTest(unittest.TestCase):
1710 # Issue5068: The _BZ2Proxy.read() method loops forever
1711 # on an empty or partial bzipped file.
1712
1713 def _test_partial_input(self, mode):
1714 class MyStringIO(StringIO.StringIO):
1715 hit_eof = False
1716 def read(self, n):
1717 if self.hit_eof:
1718 raise AssertionError("infinite loop detected in tarfile.open()")
1719 self.hit_eof = self.pos == self.len
1720 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001721 def seek(self, *args):
1722 self.hit_eof = False
1723 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001724
1725 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1726 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001727 try:
1728 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1729 except tarfile.ReadError:
1730 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001731
1732 def test_partial_input(self):
1733 self._test_partial_input("r")
1734
1735 def test_partial_input_bz2(self):
1736 self._test_partial_input("r:bz2")
1737
1738
Neal Norwitz996acf12003-02-17 14:51:41 +00001739def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001740 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001741
Walter Dörwald21d3a322003-05-01 17:45:56 +00001742 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001743 UstarReadTest,
1744 MiscReadTest,
1745 StreamReadTest,
1746 DetectReadTest,
1747 MemberReadTest,
1748 GNUReadTest,
1749 PaxReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001750 ListTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001751 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001752 StreamWriteTest,
1753 GNUWriteTest,
1754 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001755 UstarUnicodeTest,
1756 GNUUnicodeTest,
1757 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001758 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001759 LimitsTest,
Lars Gustäbeld0480032015-07-02 19:37:08 +02001760 MiscTest,
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()