blob: 49469fdd8037fdfd845c058d05fc4449ce89965c [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
4import os
5import shutil
Georg Brandl38c6a222006-05-10 16:26:03 +00006import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00007from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00008import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00009
10import unittest
11import tarfile
12
13from test import test_support
14
15# Check for our compression modules.
16try:
17 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000018 gzip.GzipFile
19except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000020 gzip = None
21try:
22 import bz2
23except ImportError:
24 bz2 = None
25
Lars Gustäbelc64e4022007-03-13 10:47:19 +000026def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000027 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000028
Antoine Pitrou310c9fe2009-11-11 20:55:07 +000029TEMPDIR = os.path.abspath(test_support.TESTFN)
30tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000031gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
32bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
33tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000034
Lars Gustäbelc64e4022007-03-13 10:47:19 +000035md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
36md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000037
38
Lars Gustäbelc64e4022007-03-13 10:47:19 +000039class ReadTest(unittest.TestCase):
40
41 tarname = tarname
42 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000043
44 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000045 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000046
47 def tearDown(self):
48 self.tar.close()
49
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000050
Lars Gustäbelc64e4022007-03-13 10:47:19 +000051class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000052
Lars Gustäbelc64e4022007-03-13 10:47:19 +000053 def test_fileobj_regular_file(self):
54 tarinfo = self.tar.getmember("ustar/regtype")
55 fobj = self.tar.extractfile(tarinfo)
56 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000057 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000058 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000059
Lars Gustäbelc64e4022007-03-13 10:47:19 +000060 def test_fileobj_readlines(self):
61 self.tar.extract("ustar/regtype", TEMPDIR)
62 tarinfo = self.tar.getmember("ustar/regtype")
63 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
64 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000065
Lars Gustäbelc64e4022007-03-13 10:47:19 +000066 lines1 = fobj1.readlines()
67 lines2 = fobj2.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000068 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000069 "fileobj.readlines() failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000070 self.assertTrue(len(lines2) == 114,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000071 "fileobj.readlines() failed")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +000072 self.assertTrue(lines2[83] ==
Lars Gustäbelc64e4022007-03-13 10:47:19 +000073 "I will gladly admit that Python is not the fastest running scripting language.\n",
74 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000075
Lars Gustäbelc64e4022007-03-13 10:47:19 +000076 def test_fileobj_iter(self):
77 self.tar.extract("ustar/regtype", TEMPDIR)
78 tarinfo = self.tar.getmember("ustar/regtype")
79 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
80 fobj2 = self.tar.extractfile(tarinfo)
81 lines1 = fobj1.readlines()
82 lines2 = [line for line in fobj2]
Benjamin Peterson5c8da862009-06-30 22:57:08 +000083 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000084 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000085
Lars Gustäbelc64e4022007-03-13 10:47:19 +000086 def test_fileobj_seek(self):
87 self.tar.extract("ustar/regtype", TEMPDIR)
88 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
89 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000090 fobj.close()
91
Lars Gustäbelc64e4022007-03-13 10:47:19 +000092 tarinfo = self.tar.getmember("ustar/regtype")
93 fobj = self.tar.extractfile(tarinfo)
94
95 text = fobj.read()
96 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000097 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000098 "seek() to file's start failed")
99 fobj.seek(2048, 0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000100 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000101 "seek() to absolute position failed")
102 fobj.seek(-1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000103 self.assertTrue(1024 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000104 "seek() to negative relative position failed")
105 fobj.seek(1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000106 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000107 "seek() to positive relative position failed")
108 s = fobj.read(10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000109 self.assertTrue(s == data[2048:2058],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000110 "read() after seek failed")
111 fobj.seek(0, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000112 self.assertTrue(tarinfo.size == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000113 "seek() to file's end failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000114 self.assertTrue(fobj.read() == "",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000115 "read() at file's end did not return empty string")
116 fobj.seek(-tarinfo.size, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000117 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000118 "relative seek() to file's start failed")
119 fobj.seek(512)
120 s1 = fobj.readlines()
121 fobj.seek(512)
122 s2 = fobj.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000123 self.assertTrue(s1 == s2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000124 "readlines() after seek failed")
125 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000126 self.assertTrue(len(fobj.readline()) == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000127 "tell() after readline() failed")
128 fobj.seek(512)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000129 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000130 "tell() after seek() and readline() failed")
131 fobj.seek(0)
132 line = fobj.readline()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000133 self.assertTrue(fobj.read() == data[len(line):],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000134 "read() after readline() failed")
135 fobj.close()
136
Lars Gustäbel4da7d412010-06-03 12:34:14 +0000137 # Test if symbolic and hard links are resolved by extractfile(). The
138 # test link members each point to a regular member whose data is
139 # supposed to be exported.
140 def _test_fileobj_link(self, lnktype, regtype):
141 a = self.tar.extractfile(lnktype)
142 b = self.tar.extractfile(regtype)
143 self.assertEqual(a.name, b.name)
144
145 def test_fileobj_link1(self):
146 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
147
148 def test_fileobj_link2(self):
149 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
150
151 def test_fileobj_symlink1(self):
152 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
153
154 def test_fileobj_symlink2(self):
155 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
156
Lars Gustäbel231d4742012-04-24 22:42:08 +0200157 def test_issue14160(self):
158 self._test_fileobj_link("symtype2", "ustar/regtype")
159
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000160
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000161class CommonReadTest(ReadTest):
162
163 def test_empty_tarfile(self):
164 # Test for issue6123: Allow opening empty archives.
165 # This test checks if tarfile.open() is able to open an empty tar
166 # archive successfully. Note that an empty tar archive is not the
167 # same as an empty file!
168 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
169 try:
170 tar = tarfile.open(tmpname, self.mode)
171 tar.getnames()
172 except tarfile.ReadError:
173 self.fail("tarfile.open() failed on empty archive")
174 self.assertListEqual(tar.getmembers(), [])
175
176 def test_null_tarfile(self):
177 # Test for issue6123: Allow opening empty archives.
178 # This test guarantees that tarfile.open() does not treat an empty
179 # file as an empty tar archive.
180 open(tmpname, "wb").close()
181 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
182 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
183
Serhiy Storchakad804f532014-01-13 19:08:51 +0200184 def test_non_existent_tarfile(self):
185 # Test for issue11513: prevent non-existent gzipped tarfiles raising
186 # multiple exceptions.
187 exctype = OSError if '|' in self.mode else IOError
188 with self.assertRaisesRegexp(exctype, "xxx") as ex:
189 tarfile.open("xxx", self.mode)
190 self.assertEqual(ex.exception.errno, errno.ENOENT)
191
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000192 def test_ignore_zeros(self):
193 # Test TarFile's ignore_zeros option.
194 if self.mode.endswith(":gz"):
195 _open = gzip.GzipFile
196 elif self.mode.endswith(":bz2"):
197 _open = bz2.BZ2File
198 else:
199 _open = open
200
201 for char in ('\0', 'a'):
202 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
203 # are ignored correctly.
204 fobj = _open(tmpname, "wb")
205 fobj.write(char * 1024)
206 fobj.write(tarfile.TarInfo("foo").tobuf())
207 fobj.close()
208
209 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
210 self.assertListEqual(tar.getnames(), ["foo"],
211 "ignore_zeros=True should have skipped the %r-blocks" % char)
212 tar.close()
213
214
215class MiscReadTest(CommonReadTest):
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200216 taropen = tarfile.TarFile.taropen
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000217
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000218 def test_no_name_argument(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000219 fobj = open(self.tarname, "rb")
220 tar = tarfile.open(fileobj=fobj, mode=self.mode)
221 self.assertEqual(tar.name, os.path.abspath(fobj.name))
222
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000223 def test_no_name_attribute(self):
224 data = open(self.tarname, "rb").read()
225 fobj = StringIO.StringIO(data)
226 self.assertRaises(AttributeError, getattr, fobj, "name")
227 tar = tarfile.open(fileobj=fobj, mode=self.mode)
228 self.assertEqual(tar.name, None)
229
230 def test_empty_name_attribute(self):
231 data = open(self.tarname, "rb").read()
232 fobj = StringIO.StringIO(data)
233 fobj.name = ""
234 tar = tarfile.open(fileobj=fobj, mode=self.mode)
235 self.assertEqual(tar.name, None)
236
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200237 def test_illegal_mode_arg(self):
238 with open(tmpname, 'wb'):
239 pass
240 self.addCleanup(os.unlink, tmpname)
241 with self.assertRaisesRegexp(ValueError, 'mode must be '):
242 tar = self.taropen(tmpname, 'q')
243 with self.assertRaisesRegexp(ValueError, 'mode must be '):
244 tar = self.taropen(tmpname, 'rw')
245 with self.assertRaisesRegexp(ValueError, 'mode must be '):
246 tar = self.taropen(tmpname, '')
247
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000248 def test_fileobj_with_offset(self):
249 # Skip the first member and store values from the second member
250 # of the testtar.
251 tar = tarfile.open(self.tarname, mode=self.mode)
252 tar.next()
253 t = tar.next()
254 name = t.name
255 offset = t.offset
256 data = tar.extractfile(t).read()
257 tar.close()
258
259 # Open the testtar and seek to the offset of the second member.
260 if self.mode.endswith(":gz"):
261 _open = gzip.GzipFile
262 elif self.mode.endswith(":bz2"):
263 _open = bz2.BZ2File
264 else:
265 _open = open
266 fobj = _open(self.tarname, "rb")
267 fobj.seek(offset)
268
269 # Test if the tarfile starts with the second member.
270 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
271 t = tar.next()
272 self.assertEqual(t.name, name)
273 # Read to the end of fileobj and test if seeking back to the
274 # beginning works.
275 tar.getmembers()
276 self.assertEqual(tar.extractfile(t).read(), data,
277 "seek back did not work")
278 tar.close()
279
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000280 def test_fail_comp(self):
281 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
282 if self.mode == "r:":
Zachary Ware1f702212013-12-10 14:09:20 -0600283 self.skipTest('needs a gz or bz2 mode')
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000284 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
285 fobj = open(tarname, "rb")
286 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
287
288 def test_v7_dirtype(self):
289 # Test old style dirtype member (bug #1336623):
290 # Old V7 tars create directory members using an AREGTYPE
291 # header with a "/" appended to the filename field.
292 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000293 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000294 "v7 dirtype failed")
295
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000296 def test_xstar_type(self):
297 # The xstar format stores extra atime and ctime fields inside the
298 # space reserved for the prefix field. The prefix field must be
299 # ignored in this case, otherwise it will mess up the name.
300 try:
301 self.tar.getmember("misc/regtype-xstar")
302 except KeyError:
303 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
304
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000305 def test_check_members(self):
306 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000307 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000308 "wrong mtime for %s" % tarinfo.name)
309 if not tarinfo.name.startswith("ustar/"):
310 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000311 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000312 "wrong uname for %s" % tarinfo.name)
313
314 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000315 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000316 "could not find all members")
317
318 def test_extract_hardlink(self):
319 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200320 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
321 tar.extract("ustar/regtype", TEMPDIR)
322 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000323
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000324 tar.extract("ustar/lnktype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200325 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
326 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
327 data = f.read()
328 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000329
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000330 tar.extract("ustar/symtype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200331 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
332 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
333 data = f.read()
334 self.assertEqual(md5sum(data), md5_regtype)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000335
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000336 def test_extractall(self):
337 # Test if extractall() correctly restores directory permissions
338 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000339 tar = tarfile.open(tarname, encoding="iso8859-1")
340 directories = [t for t in tar if t.isdir()]
341 tar.extractall(TEMPDIR, directories)
342 for tarinfo in directories:
343 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000344 if sys.platform != "win32":
345 # Win32 has no support for fine grained permissions.
346 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000347 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
348 tar.close()
349
Lars Gustäbel12adc652009-11-23 15:46:19 +0000350 def test_init_close_fobj(self):
351 # Issue #7341: Close the internal file object in the TarFile
352 # constructor in case of an error. For the test we rely on
353 # the fact that opening an empty file raises a ReadError.
354 empty = os.path.join(TEMPDIR, "empty")
355 open(empty, "wb").write("")
356
357 try:
358 tar = object.__new__(tarfile.TarFile)
359 try:
360 tar.__init__(empty)
361 except tarfile.ReadError:
362 self.assertTrue(tar.fileobj.closed)
363 else:
364 self.fail("ReadError not raised")
365 finally:
366 os.remove(empty)
367
Serhiy Storchakace34ba62013-05-09 14:22:05 +0300368 def test_parallel_iteration(self):
369 # Issue #16601: Restarting iteration over tarfile continued
370 # from where it left off.
371 with tarfile.open(self.tarname) as tar:
372 for m1, m2 in zip(tar, tar):
373 self.assertEqual(m1.offset, m2.offset)
374 self.assertEqual(m1.name, m2.name)
375
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000376
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000377class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000378
379 mode="r|"
380
381 def test_fileobj_regular_file(self):
382 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
383 fobj = self.tar.extractfile(tarinfo)
384 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000385 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000386 "regular file extraction failed")
387
388 def test_provoke_stream_error(self):
389 tarinfos = self.tar.getmembers()
390 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000391 self.assertRaises(tarfile.StreamError, f.read)
392
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000393 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000394 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000395 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000396
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000397 while True:
398 t1 = tar1.next()
399 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000400 if t1 is None:
401 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000402 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000403
404 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000405 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000406 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000407
408 v1 = tar1.extractfile(t1)
409 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000410 if v1 is None:
411 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000412 self.assertTrue(v2 is not None, "stream.extractfile() failed")
413 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000414
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000415 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000416
Georg Brandla32e0a02006-10-24 16:54:16 +0000417
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000418class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000419
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000420 def _testfunc_file(self, name, mode):
421 try:
422 tarfile.open(name, mode)
423 except tarfile.ReadError:
424 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000425
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000426 def _testfunc_fileobj(self, name, mode):
427 try:
428 tarfile.open(name, mode, fileobj=open(name, "rb"))
429 except tarfile.ReadError:
430 self.fail()
431
432 def _test_modes(self, testfunc):
433 testfunc(tarname, "r")
434 testfunc(tarname, "r:")
435 testfunc(tarname, "r:*")
436 testfunc(tarname, "r|")
437 testfunc(tarname, "r|*")
438
439 if gzip:
440 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
441 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
442 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
443 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
444
445 testfunc(gzipname, "r")
446 testfunc(gzipname, "r:*")
447 testfunc(gzipname, "r:gz")
448 testfunc(gzipname, "r|*")
449 testfunc(gzipname, "r|gz")
450
451 if bz2:
452 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
453 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
454 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
455 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
456
457 testfunc(bz2name, "r")
458 testfunc(bz2name, "r:*")
459 testfunc(bz2name, "r:bz2")
460 testfunc(bz2name, "r|*")
461 testfunc(bz2name, "r|bz2")
462
463 def test_detect_file(self):
464 self._test_modes(self._testfunc_file)
465
466 def test_detect_fileobj(self):
467 self._test_modes(self._testfunc_fileobj)
468
Zachary Ware1f702212013-12-10 14:09:20 -0600469 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbel9a388632011-12-06 13:07:09 +0100470 def test_detect_stream_bz2(self):
471 # Originally, tarfile's stream detection looked for the string
472 # "BZh91" at the start of the file. This is incorrect because
473 # the '9' represents the blocksize (900kB). If the file was
474 # compressed using another blocksize autodetection fails.
Lars Gustäbel9a388632011-12-06 13:07:09 +0100475 with open(tarname, "rb") as fobj:
476 data = fobj.read()
477
478 # Compress with blocksize 100kB, the file starts with "BZh11".
479 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
480 fobj.write(data)
481
482 self._testfunc_file(tmpname, "r|*")
483
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000484
485class MemberReadTest(ReadTest):
486
487 def _test_member(self, tarinfo, chksum=None, **kwargs):
488 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000489 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000490 "wrong md5sum for %s" % tarinfo.name)
491
492 kwargs["mtime"] = 07606136617
493 kwargs["uid"] = 1000
494 kwargs["gid"] = 100
495 if "old-v7" not in tarinfo.name:
496 # V7 tar can't handle alphabetic owners.
497 kwargs["uname"] = "tarfile"
498 kwargs["gname"] = "tarfile"
499 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000500 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000501 "wrong value in %s field of %s" % (k, tarinfo.name))
502
503 def test_find_regtype(self):
504 tarinfo = self.tar.getmember("ustar/regtype")
505 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
506
507 def test_find_conttype(self):
508 tarinfo = self.tar.getmember("ustar/conttype")
509 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
510
511 def test_find_dirtype(self):
512 tarinfo = self.tar.getmember("ustar/dirtype")
513 self._test_member(tarinfo, size=0)
514
515 def test_find_dirtype_with_size(self):
516 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
517 self._test_member(tarinfo, size=255)
518
519 def test_find_lnktype(self):
520 tarinfo = self.tar.getmember("ustar/lnktype")
521 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
522
523 def test_find_symtype(self):
524 tarinfo = self.tar.getmember("ustar/symtype")
525 self._test_member(tarinfo, size=0, linkname="regtype")
526
527 def test_find_blktype(self):
528 tarinfo = self.tar.getmember("ustar/blktype")
529 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
530
531 def test_find_chrtype(self):
532 tarinfo = self.tar.getmember("ustar/chrtype")
533 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
534
535 def test_find_fifotype(self):
536 tarinfo = self.tar.getmember("ustar/fifotype")
537 self._test_member(tarinfo, size=0)
538
539 def test_find_sparse(self):
540 tarinfo = self.tar.getmember("ustar/sparse")
541 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
542
543 def test_find_umlauts(self):
544 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
545 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
546
547 def test_find_ustar_longname(self):
548 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000549 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000550
551 def test_find_regtype_oldv7(self):
552 tarinfo = self.tar.getmember("misc/regtype-old-v7")
553 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
554
555 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000556 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000557 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
558 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
559
560
561class LongnameTest(ReadTest):
562
563 def test_read_longname(self):
564 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000565 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000566 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000567 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000568 except KeyError:
569 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000570 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000571
572 def test_read_longlink(self):
573 longname = self.subdir + "/" + "123/" * 125 + "longname"
574 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
575 try:
576 tarinfo = self.tar.getmember(longlink)
577 except KeyError:
578 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000579 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000580
581 def test_truncated_longname(self):
582 longname = self.subdir + "/" + "123/" * 125 + "longname"
583 tarinfo = self.tar.getmember(longname)
584 offset = tarinfo.offset
585 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000586 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000587 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
588
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000589 def test_header_offset(self):
590 # Test if the start offset of the TarInfo object includes
591 # the preceding extended header.
592 longname = self.subdir + "/" + "123/" * 125 + "longname"
593 offset = self.tar.getmember(longname).offset
594 fobj = open(tarname)
595 fobj.seek(offset)
596 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
597 self.assertEqual(tarinfo.type, self.longnametype)
598
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000599
600class GNUReadTest(LongnameTest):
601
602 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000603 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000604
605 def test_sparse_file(self):
606 tarinfo1 = self.tar.getmember("ustar/sparse")
607 fobj1 = self.tar.extractfile(tarinfo1)
608 tarinfo2 = self.tar.getmember("gnu/sparse")
609 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000610 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000611 "sparse file extraction failed")
612
613
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000614class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000615
616 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000617 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000618
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000619 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000620 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000621
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000622 tarinfo = tar.getmember("pax/regtype1")
623 self.assertEqual(tarinfo.uname, "foo")
624 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000625 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000626
627 tarinfo = tar.getmember("pax/regtype2")
628 self.assertEqual(tarinfo.uname, "")
629 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000630 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000631
632 tarinfo = tar.getmember("pax/regtype3")
633 self.assertEqual(tarinfo.uname, "tarfile")
634 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000635 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
636
637 def test_pax_number_fields(self):
638 # All following number fields are read from the pax header.
639 tar = tarfile.open(tarname, encoding="iso8859-1")
640 tarinfo = tar.getmember("pax/regtype4")
641 self.assertEqual(tarinfo.size, 7011)
642 self.assertEqual(tarinfo.uid, 123)
643 self.assertEqual(tarinfo.gid, 123)
644 self.assertEqual(tarinfo.mtime, 1041808783.0)
645 self.assertEqual(type(tarinfo.mtime), float)
646 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
647 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000648
649
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000650class WriteTestBase(unittest.TestCase):
651 # Put all write tests in here that are supposed to be tested
652 # in all possible mode combinations.
653
654 def test_fileobj_no_close(self):
655 fobj = StringIO.StringIO()
656 tar = tarfile.open(fileobj=fobj, mode=self.mode)
657 tar.addfile(tarfile.TarInfo("foo"))
658 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000659 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000660
661
662class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000663
664 mode = "w:"
665
666 def test_100_char_name(self):
667 # The name field in a tar header stores strings of at most 100 chars.
668 # If a string is shorter than 100 chars it has to be padded with '\0',
669 # which implies that a string of exactly 100 chars is stored without
670 # a trailing '\0'.
671 name = "0123456789" * 10
672 tar = tarfile.open(tmpname, self.mode)
673 t = tarfile.TarInfo(name)
674 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000675 tar.close()
676
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000677 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000678 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000679 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000680 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000681
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000682 def test_tar_size(self):
683 # Test for bug #1013882.
684 tar = tarfile.open(tmpname, self.mode)
685 path = os.path.join(TEMPDIR, "file")
686 fobj = open(path, "wb")
687 fobj.write("aaa")
688 fobj.close()
689 tar.add(path)
690 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000691 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000692 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000693
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000694 # The test_*_size tests test for bug #1167128.
695 def test_file_size(self):
696 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000697
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000698 path = os.path.join(TEMPDIR, "file")
699 fobj = open(path, "wb")
700 fobj.close()
701 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000702 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000703
704 fobj = open(path, "wb")
705 fobj.write("aaa")
706 fobj.close()
707 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000708 self.assertEqual(tarinfo.size, 3)
709
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000710 tar.close()
711
712 def test_directory_size(self):
713 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000714 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000715 try:
716 tar = tarfile.open(tmpname, self.mode)
717 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000718 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000719 finally:
720 os.rmdir(path)
721
722 def test_link_size(self):
723 if hasattr(os, "link"):
724 link = os.path.join(TEMPDIR, "link")
725 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000726 fobj = open(target, "wb")
727 fobj.write("aaa")
728 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000729 os.link(target, link)
730 try:
731 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000732 # Record the link target in the inodes list.
733 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000734 tarinfo = tar.gettarinfo(link)
735 self.assertEqual(tarinfo.size, 0)
736 finally:
737 os.remove(target)
738 os.remove(link)
739
740 def test_symlink_size(self):
741 if hasattr(os, "symlink"):
742 path = os.path.join(TEMPDIR, "symlink")
743 os.symlink("link_target", path)
744 try:
745 tar = tarfile.open(tmpname, self.mode)
746 tarinfo = tar.gettarinfo(path)
747 self.assertEqual(tarinfo.size, 0)
748 finally:
749 os.remove(path)
750
751 def test_add_self(self):
752 # Test for #1257255.
753 dstname = os.path.abspath(tmpname)
754
755 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000756 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000757
758 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000759 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000760
761 cwd = os.getcwd()
762 os.chdir(TEMPDIR)
763 tar.add(dstname)
764 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000765 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000766
Lars Gustäbel104490e2007-06-18 11:42:11 +0000767 def test_exclude(self):
768 tempdir = os.path.join(TEMPDIR, "exclude")
769 os.mkdir(tempdir)
770 try:
771 for name in ("foo", "bar", "baz"):
772 name = os.path.join(tempdir, name)
773 open(name, "wb").close()
774
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000775 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000776
777 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000778 with test_support.check_warnings(("use the filter argument",
779 DeprecationWarning)):
780 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000781 tar.close()
782
783 tar = tarfile.open(tmpname, "r")
784 self.assertEqual(len(tar.getmembers()), 1)
785 self.assertEqual(tar.getnames()[0], "empty_dir")
786 finally:
787 shutil.rmtree(tempdir)
788
Lars Gustäbel21121e62009-09-12 10:28:15 +0000789 def test_filter(self):
790 tempdir = os.path.join(TEMPDIR, "filter")
791 os.mkdir(tempdir)
792 try:
793 for name in ("foo", "bar", "baz"):
794 name = os.path.join(tempdir, name)
795 open(name, "wb").close()
796
797 def filter(tarinfo):
798 if os.path.basename(tarinfo.name) == "bar":
799 return
800 tarinfo.uid = 123
801 tarinfo.uname = "foo"
802 return tarinfo
803
804 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
805 tar.add(tempdir, arcname="empty_dir", filter=filter)
806 tar.close()
807
808 tar = tarfile.open(tmpname, "r")
809 for tarinfo in tar:
810 self.assertEqual(tarinfo.uid, 123)
811 self.assertEqual(tarinfo.uname, "foo")
812 self.assertEqual(len(tar.getmembers()), 3)
813 tar.close()
814 finally:
815 shutil.rmtree(tempdir)
816
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000817 # Guarantee that stored pathnames are not modified. Don't
818 # remove ./ or ../ or double slashes. Still make absolute
819 # pathnames relative.
820 # For details see bug #6054.
821 def _test_pathname(self, path, cmp_path=None, dir=False):
822 # Create a tarfile with an empty member named path
823 # and compare the stored name with the original.
824 foo = os.path.join(TEMPDIR, "foo")
825 if not dir:
826 open(foo, "w").close()
827 else:
828 os.mkdir(foo)
829
830 tar = tarfile.open(tmpname, self.mode)
831 tar.add(foo, arcname=path)
832 tar.close()
833
834 tar = tarfile.open(tmpname, "r")
835 t = tar.next()
836 tar.close()
837
838 if not dir:
839 os.remove(foo)
840 else:
841 os.rmdir(foo)
842
843 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
844
845 def test_pathnames(self):
846 self._test_pathname("foo")
847 self._test_pathname(os.path.join("foo", ".", "bar"))
848 self._test_pathname(os.path.join("foo", "..", "bar"))
849 self._test_pathname(os.path.join(".", "foo"))
850 self._test_pathname(os.path.join(".", "foo", "."))
851 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
852 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
853 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
854 self._test_pathname(os.path.join("..", "foo"))
855 self._test_pathname(os.path.join("..", "foo", ".."))
856 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
857 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
858
859 self._test_pathname("foo" + os.sep + os.sep + "bar")
860 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
861
862 def test_abs_pathnames(self):
863 if sys.platform == "win32":
864 self._test_pathname("C:\\foo", "foo")
865 else:
866 self._test_pathname("/foo", "foo")
867 self._test_pathname("///foo", "foo")
868
869 def test_cwd(self):
870 # Test adding the current working directory.
871 cwd = os.getcwd()
872 os.chdir(TEMPDIR)
873 try:
874 open("foo", "w").close()
875
876 tar = tarfile.open(tmpname, self.mode)
877 tar.add(".")
878 tar.close()
879
880 tar = tarfile.open(tmpname, "r")
881 for t in tar:
Serhiy Storchaka88761452012-12-28 00:32:19 +0200882 self.assertTrue(t.name == "." or t.name.startswith("./"))
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000883 tar.close()
884 finally:
885 os.chdir(cwd)
886
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800887 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800888 def test_extractall_symlinks(self):
889 # Test if extractall works properly when tarfile contains symlinks
890 tempdir = os.path.join(TEMPDIR, "testsymlinks")
891 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
892 os.mkdir(tempdir)
893 try:
894 source_file = os.path.join(tempdir,'source')
895 target_file = os.path.join(tempdir,'symlink')
896 with open(source_file,'w') as f:
897 f.write('something\n')
898 os.symlink(source_file, target_file)
899 tar = tarfile.open(temparchive,'w')
900 tar.add(source_file, arcname=os.path.basename(source_file))
901 tar.add(target_file, arcname=os.path.basename(target_file))
902 tar.close()
903 # Let's extract it to the location which contains the symlink
904 tar = tarfile.open(temparchive,'r')
905 # this should not raise OSError: [Errno 17] File exists
906 try:
907 tar.extractall(path=tempdir)
908 except OSError:
909 self.fail("extractall failed with symlinked files")
910 finally:
911 tar.close()
912 finally:
913 os.unlink(temparchive)
914 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000915
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +0800916 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
917 def test_extractall_broken_symlinks(self):
918 # Test if extractall works properly when tarfile contains broken
919 # symlinks
920 tempdir = os.path.join(TEMPDIR, "testsymlinks")
921 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
922 os.mkdir(tempdir)
923 try:
924 source_file = os.path.join(tempdir,'source')
925 target_file = os.path.join(tempdir,'symlink')
926 with open(source_file,'w') as f:
927 f.write('something\n')
928 os.symlink(source_file, target_file)
929 tar = tarfile.open(temparchive,'w')
930 tar.add(target_file, arcname=os.path.basename(target_file))
931 tar.close()
932 # remove the real file
933 os.unlink(source_file)
934 # Let's extract it to the location which contains the symlink
935 tar = tarfile.open(temparchive,'r')
936 # this should not raise OSError: [Errno 17] File exists
937 try:
938 tar.extractall(path=tempdir)
939 except OSError:
940 self.fail("extractall failed with broken symlinked files")
941 finally:
942 tar.close()
943 finally:
944 os.unlink(temparchive)
945 shutil.rmtree(tempdir)
946
947 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
948 def test_extractall_hardlinks(self):
949 # Test if extractall works properly when tarfile contains symlinks
950 tempdir = os.path.join(TEMPDIR, "testsymlinks")
951 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
952 os.mkdir(tempdir)
953 try:
954 source_file = os.path.join(tempdir,'source')
955 target_file = os.path.join(tempdir,'symlink')
956 with open(source_file,'w') as f:
957 f.write('something\n')
958 os.link(source_file, target_file)
959 tar = tarfile.open(temparchive,'w')
960 tar.add(source_file, arcname=os.path.basename(source_file))
961 tar.add(target_file, arcname=os.path.basename(target_file))
962 tar.close()
963 # Let's extract it to the location which contains the symlink
964 tar = tarfile.open(temparchive,'r')
965 # this should not raise OSError: [Errno 17] File exists
966 try:
967 tar.extractall(path=tempdir)
968 except OSError:
969 self.fail("extractall failed with linked files")
970 finally:
971 tar.close()
972 finally:
973 os.unlink(temparchive)
974 shutil.rmtree(tempdir)
975
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000976class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000977
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000978 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +0000979
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000980 def test_stream_padding(self):
981 # Test for bug #1543303.
982 tar = tarfile.open(tmpname, self.mode)
983 tar.close()
984
985 if self.mode.endswith("gz"):
986 fobj = gzip.GzipFile(tmpname)
987 data = fobj.read()
988 fobj.close()
989 elif self.mode.endswith("bz2"):
990 dec = bz2.BZ2Decompressor()
991 data = open(tmpname, "rb").read()
992 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000993 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000994 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +0000995 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000996 fobj = open(tmpname, "rb")
997 data = fobj.read()
998 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +0000999
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001000 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +00001001 "incorrect zero padding")
1002
Zachary Ware1f702212013-12-10 14:09:20 -06001003 @unittest.skipIf(sys.platform == 'win32', 'not appropriate for Windows')
1004 @unittest.skipUnless(hasattr(os, 'umask'), 'requires os.umask')
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001005 def test_file_mode(self):
1006 # Test for issue #8464: Create files with correct
1007 # permissions.
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001008 if os.path.exists(tmpname):
1009 os.remove(tmpname)
1010
1011 original_umask = os.umask(0022)
1012 try:
1013 tar = tarfile.open(tmpname, self.mode)
1014 tar.close()
1015 mode = os.stat(tmpname).st_mode & 0777
1016 self.assertEqual(mode, 0644, "wrong file permissions")
1017 finally:
1018 os.umask(original_umask)
1019
Lars Gustäbel7d4d0742011-12-21 19:27:50 +01001020 def test_issue13639(self):
1021 try:
1022 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1023 pass
1024 except UnicodeDecodeError:
1025 self.fail("_Stream failed to write unicode filename")
1026
Neal Norwitz8a519392006-08-21 17:59:46 +00001027
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001028class GNUWriteTest(unittest.TestCase):
1029 # This testcase checks for correct creation of GNU Longname
1030 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001031
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001032 def _length(self, s):
1033 blocks, remainder = divmod(len(s) + 1, 512)
1034 if remainder:
1035 blocks += 1
1036 return blocks * 512
1037
1038 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001039 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001040 count = 512
1041
1042 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001043 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001044 count += 512
1045 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001046 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001047 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001048 count += 512
1049 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001050 return count
1051
1052 def _test(self, name, link=None):
1053 tarinfo = tarfile.TarInfo(name)
1054 if link:
1055 tarinfo.linkname = link
1056 tarinfo.type = tarfile.LNKTYPE
1057
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001058 tar = tarfile.open(tmpname, "w")
1059 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001060 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001061
1062 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001063 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001064 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001065
Georg Brandl87fa5592006-12-06 22:21:18 +00001066 tar.close()
1067
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001068 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001069 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001070 self.assertIsNotNone(member,
1071 "unable to read longname member")
1072 self.assertEqual(tarinfo.name, member.name,
1073 "unable to read longname member")
1074 self.assertEqual(tarinfo.linkname, member.linkname,
1075 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001076
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001077 def test_longname_1023(self):
1078 self._test(("longnam/" * 127) + "longnam")
1079
1080 def test_longname_1024(self):
1081 self._test(("longnam/" * 127) + "longname")
1082
1083 def test_longname_1025(self):
1084 self._test(("longnam/" * 127) + "longname_")
1085
1086 def test_longlink_1023(self):
1087 self._test("name", ("longlnk/" * 127) + "longlnk")
1088
1089 def test_longlink_1024(self):
1090 self._test("name", ("longlnk/" * 127) + "longlink")
1091
1092 def test_longlink_1025(self):
1093 self._test("name", ("longlnk/" * 127) + "longlink_")
1094
1095 def test_longnamelink_1023(self):
1096 self._test(("longnam/" * 127) + "longnam",
1097 ("longlnk/" * 127) + "longlnk")
1098
1099 def test_longnamelink_1024(self):
1100 self._test(("longnam/" * 127) + "longname",
1101 ("longlnk/" * 127) + "longlink")
1102
1103 def test_longnamelink_1025(self):
1104 self._test(("longnam/" * 127) + "longname_",
1105 ("longlnk/" * 127) + "longlink_")
1106
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001107
1108class HardlinkTest(unittest.TestCase):
1109 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001110
1111 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001112 self.foo = os.path.join(TEMPDIR, "foo")
1113 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001114
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001115 fobj = open(self.foo, "wb")
1116 fobj.write("foo")
1117 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001118
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001119 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001120
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001121 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001122 self.tar.add(self.foo)
1123
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001124 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001125 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001126 os.remove(self.foo)
1127 os.remove(self.bar)
1128
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001129 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001130 # The same name will be added as a REGTYPE every
1131 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001132 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001133 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001134 "add file as regular failed")
1135
1136 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001137 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001138 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001139 "add file as hardlink failed")
1140
1141 def test_dereference_hardlink(self):
1142 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001143 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001144 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001145 "dereferencing hardlink failed")
1146
Neal Norwitza4f651a2004-07-20 22:07:44 +00001147
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001148class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001149
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001150 def _test(self, name, link=None):
1151 # See GNUWriteTest.
1152 tarinfo = tarfile.TarInfo(name)
1153 if link:
1154 tarinfo.linkname = link
1155 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001156
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001157 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1158 tar.addfile(tarinfo)
1159 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001160
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001161 tar = tarfile.open(tmpname)
1162 if link:
1163 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001164 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001165 else:
1166 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001167 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001168
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001169 def test_pax_global_header(self):
1170 pax_headers = {
1171 u"foo": u"bar",
1172 u"uid": u"0",
1173 u"mtime": u"1.23",
1174 u"test": u"äöü",
1175 u"äöü": u"test"}
1176
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001177 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001178 pax_headers=pax_headers)
1179 tar.addfile(tarfile.TarInfo("test"))
1180 tar.close()
1181
1182 # Test if the global header was written correctly.
1183 tar = tarfile.open(tmpname, encoding="iso8859-1")
1184 self.assertEqual(tar.pax_headers, pax_headers)
1185 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1186
1187 # Test if all the fields are unicode.
1188 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001189 self.assertTrue(type(key) is unicode)
1190 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001191 if key in tarfile.PAX_NUMBER_FIELDS:
1192 try:
1193 tarfile.PAX_NUMBER_FIELDS[key](val)
1194 except (TypeError, ValueError):
1195 self.fail("unable to convert pax header field")
1196
1197 def test_pax_extended_header(self):
1198 # The fields from the pax header have priority over the
1199 # TarInfo.
1200 pax_headers = {u"path": u"foo", u"uid": u"123"}
1201
1202 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1203 t = tarfile.TarInfo()
1204 t.name = u"äöü" # non-ASCII
1205 t.uid = 8**8 # too large
1206 t.pax_headers = pax_headers
1207 tar.addfile(t)
1208 tar.close()
1209
1210 tar = tarfile.open(tmpname, encoding="iso8859-1")
1211 t = tar.getmembers()[0]
1212 self.assertEqual(t.pax_headers, pax_headers)
1213 self.assertEqual(t.name, "foo")
1214 self.assertEqual(t.uid, 123)
1215
1216
1217class UstarUnicodeTest(unittest.TestCase):
1218 # All *UnicodeTests FIXME
1219
1220 format = tarfile.USTAR_FORMAT
1221
1222 def test_iso8859_1_filename(self):
1223 self._test_unicode_filename("iso8859-1")
1224
1225 def test_utf7_filename(self):
1226 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001227
1228 def test_utf8_filename(self):
1229 self._test_unicode_filename("utf8")
1230
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001231 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001232 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1233 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001234 tar.addfile(tarfile.TarInfo(name))
1235 tar.close()
1236
1237 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001238 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001239 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001240 tar.close()
1241
1242 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001243 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1244 tarinfo = tarfile.TarInfo()
1245
1246 tarinfo.name = "äöü"
1247 if self.format == tarfile.PAX_FORMAT:
1248 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1249 else:
1250 tar.addfile(tarinfo)
1251
1252 tarinfo.name = u"äöü"
1253 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1254
1255 tarinfo.name = "foo"
1256 tarinfo.uname = u"äöü"
1257 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1258
1259 def test_unicode_argument(self):
1260 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1261 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001262 self.assertTrue(type(t.name) is str)
1263 self.assertTrue(type(t.linkname) is str)
1264 self.assertTrue(type(t.uname) is str)
1265 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001266 tar.close()
1267
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001268 def test_uname_unicode(self):
1269 for name in (u"äöü", "äöü"):
1270 t = tarfile.TarInfo("foo")
1271 t.uname = name
1272 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001273
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001274 fobj = StringIO.StringIO()
1275 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1276 tar.addfile(t)
1277 tar.close()
1278 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001279
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001280 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1281 t = tar.getmember("foo")
1282 self.assertEqual(t.uname, "äöü")
1283 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001284
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001285
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001286class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001287
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001288 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001289
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001290
1291class PaxUnicodeTest(UstarUnicodeTest):
1292
1293 format = tarfile.PAX_FORMAT
1294
1295 def _create_unicode_name(self, name):
1296 tar = tarfile.open(tmpname, "w", format=self.format)
1297 t = tarfile.TarInfo()
1298 t.pax_headers["path"] = name
1299 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001300 tar.close()
1301
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001302 def test_error_handlers(self):
1303 # Test if the unicode error handlers work correctly for characters
1304 # that cannot be expressed in a given encoding.
1305 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001306
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001307 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1308 ("replace", "???"), ("ignore", "")):
1309 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1310 errors=handler)
1311 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001312
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001313 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1314 encoding="ascii", errors="strict")
1315
1316 def test_error_handler_utf8(self):
1317 # Create a pathname that has one component representable using
1318 # iso8859-1 and the other only in iso8859-15.
1319 self._create_unicode_name(u"äöü/¤")
1320
1321 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1322 errors="utf-8")
1323 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001324
Georg Brandlded1c4d2006-12-20 11:55:16 +00001325
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001326class AppendTest(unittest.TestCase):
1327 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001328
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001329 def setUp(self):
1330 self.tarname = tmpname
1331 if os.path.exists(self.tarname):
1332 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001333
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001334 def _add_testfile(self, fileobj=None):
1335 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1336 tar.addfile(tarfile.TarInfo("bar"))
1337 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001338
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001339 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001340 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001341 t = src.getmember("ustar/regtype")
1342 t.name = "foo"
1343 f = src.extractfile(t)
1344 tar = tarfile.open(self.tarname, mode)
1345 tar.addfile(t, f)
1346 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001347
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001348 def _test(self, names=["bar"], fileobj=None):
1349 tar = tarfile.open(self.tarname, fileobj=fileobj)
1350 self.assertEqual(tar.getnames(), names)
1351
1352 def test_non_existing(self):
1353 self._add_testfile()
1354 self._test()
1355
1356 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001357 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001358 self._add_testfile()
1359 self._test()
1360
1361 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001362 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001363 self._add_testfile(fobj)
1364 fobj.seek(0)
1365 self._test(fileobj=fobj)
1366
1367 def test_fileobj(self):
1368 self._create_testtar()
1369 data = open(self.tarname).read()
1370 fobj = StringIO.StringIO(data)
1371 self._add_testfile(fobj)
1372 fobj.seek(0)
1373 self._test(names=["foo", "bar"], fileobj=fobj)
1374
1375 def test_existing(self):
1376 self._create_testtar()
1377 self._add_testfile()
1378 self._test(names=["foo", "bar"])
1379
Zachary Ware1f702212013-12-10 14:09:20 -06001380 @unittest.skipUnless(gzip, 'requires gzip')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001381 def test_append_gz(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001382 self._create_testtar("w:gz")
1383 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1384
Zachary Ware1f702212013-12-10 14:09:20 -06001385 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001386 def test_append_bz2(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001387 self._create_testtar("w:bz2")
1388 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1389
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001390 # Append mode is supposed to fail if the tarfile to append to
1391 # does not end with a zero block.
1392 def _test_error(self, data):
1393 open(self.tarname, "wb").write(data)
1394 self.assertRaises(tarfile.ReadError, self._add_testfile)
1395
1396 def test_null(self):
1397 self._test_error("")
1398
1399 def test_incomplete(self):
1400 self._test_error("\0" * 13)
1401
1402 def test_premature_eof(self):
1403 data = tarfile.TarInfo("foo").tobuf()
1404 self._test_error(data)
1405
1406 def test_trailing_garbage(self):
1407 data = tarfile.TarInfo("foo").tobuf()
1408 self._test_error(data + "\0" * 13)
1409
1410 def test_invalid(self):
1411 self._test_error("a" * 512)
1412
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001413
1414class LimitsTest(unittest.TestCase):
1415
1416 def test_ustar_limits(self):
1417 # 100 char name
1418 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001419 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001420
1421 # 101 char name that cannot be stored
1422 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001423 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001424
1425 # 256 char name with a slash at pos 156
1426 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001427 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001428
1429 # 256 char name that cannot be stored
1430 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001431 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001432
1433 # 512 char name
1434 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001435 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001436
1437 # 512 char linkname
1438 tarinfo = tarfile.TarInfo("longlink")
1439 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001440 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001441
1442 # uid > 8 digits
1443 tarinfo = tarfile.TarInfo("name")
1444 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001445 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001446
1447 def test_gnu_limits(self):
1448 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001449 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001450
1451 tarinfo = tarfile.TarInfo("longlink")
1452 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001453 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001454
1455 # uid >= 256 ** 7
1456 tarinfo = tarfile.TarInfo("name")
1457 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001458 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001459
1460 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001461 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001462 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001463
1464 tarinfo = tarfile.TarInfo("longlink")
1465 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001466 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001467
1468 tarinfo = tarfile.TarInfo("name")
1469 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001470 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001471
1472
Lars Gustäbel64581042010-03-03 11:55:48 +00001473class ContextManagerTest(unittest.TestCase):
1474
1475 def test_basic(self):
1476 with tarfile.open(tarname) as tar:
1477 self.assertFalse(tar.closed, "closed inside runtime context")
1478 self.assertTrue(tar.closed, "context manager failed")
1479
1480 def test_closed(self):
1481 # The __enter__() method is supposed to raise IOError
1482 # if the TarFile object is already closed.
1483 tar = tarfile.open(tarname)
1484 tar.close()
1485 with self.assertRaises(IOError):
1486 with tar:
1487 pass
1488
1489 def test_exception(self):
1490 # Test if the IOError exception is passed through properly.
1491 with self.assertRaises(Exception) as exc:
1492 with tarfile.open(tarname) as tar:
1493 raise IOError
1494 self.assertIsInstance(exc.exception, IOError,
1495 "wrong exception raised in context manager")
1496 self.assertTrue(tar.closed, "context manager failed")
1497
1498 def test_no_eof(self):
1499 # __exit__() must not write end-of-archive blocks if an
1500 # exception was raised.
1501 try:
1502 with tarfile.open(tmpname, "w") as tar:
1503 raise Exception
1504 except:
1505 pass
1506 self.assertEqual(os.path.getsize(tmpname), 0,
1507 "context manager wrote an end-of-archive block")
1508 self.assertTrue(tar.closed, "context manager failed")
1509
1510 def test_eof(self):
1511 # __exit__() must write end-of-archive blocks, i.e. call
1512 # TarFile.close() if there was no error.
1513 with tarfile.open(tmpname, "w"):
1514 pass
1515 self.assertNotEqual(os.path.getsize(tmpname), 0,
1516 "context manager wrote no end-of-archive block")
1517
1518 def test_fileobj(self):
1519 # Test that __exit__() did not close the external file
1520 # object.
1521 fobj = open(tmpname, "wb")
1522 try:
1523 with tarfile.open(fileobj=fobj, mode="w") as tar:
1524 raise Exception
1525 except:
1526 pass
1527 self.assertFalse(fobj.closed, "external file object was closed")
1528 self.assertTrue(tar.closed, "context manager failed")
1529 fobj.close()
1530
1531
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001532class LinkEmulationTest(ReadTest):
1533
1534 # Test for issue #8741 regression. On platforms that do not support
1535 # symbolic or hard links tarfile tries to extract these types of members as
1536 # the regular files they point to.
1537 def _test_link_extraction(self, name):
1538 self.tar.extract(name, TEMPDIR)
1539 data = open(os.path.join(TEMPDIR, name), "rb").read()
1540 self.assertEqual(md5sum(data), md5_regtype)
1541
1542 def test_hardlink_extraction1(self):
1543 self._test_link_extraction("ustar/lnktype")
1544
1545 def test_hardlink_extraction2(self):
1546 self._test_link_extraction("./ustar/linktest2/lnktype")
1547
1548 def test_symlink_extraction1(self):
1549 self._test_link_extraction("ustar/symtype")
1550
1551 def test_symlink_extraction2(self):
1552 self._test_link_extraction("./ustar/linktest2/symtype")
1553
1554
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001555class GzipMiscReadTest(MiscReadTest):
1556 tarname = gzipname
1557 mode = "r:gz"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001558 taropen = tarfile.TarFile.gzopen
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001559class GzipUstarReadTest(UstarReadTest):
1560 tarname = gzipname
1561 mode = "r:gz"
1562class GzipStreamReadTest(StreamReadTest):
1563 tarname = gzipname
1564 mode = "r|gz"
1565class GzipWriteTest(WriteTest):
1566 mode = "w:gz"
1567class GzipStreamWriteTest(StreamWriteTest):
1568 mode = "w|gz"
1569
1570
1571class Bz2MiscReadTest(MiscReadTest):
1572 tarname = bz2name
1573 mode = "r:bz2"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001574 taropen = tarfile.TarFile.bz2open
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001575class Bz2UstarReadTest(UstarReadTest):
1576 tarname = bz2name
1577 mode = "r:bz2"
1578class Bz2StreamReadTest(StreamReadTest):
1579 tarname = bz2name
1580 mode = "r|bz2"
1581class Bz2WriteTest(WriteTest):
1582 mode = "w:bz2"
1583class Bz2StreamWriteTest(StreamWriteTest):
1584 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001585
Lars Gustäbel2020a592009-03-22 20:09:33 +00001586class Bz2PartialReadTest(unittest.TestCase):
1587 # Issue5068: The _BZ2Proxy.read() method loops forever
1588 # on an empty or partial bzipped file.
1589
1590 def _test_partial_input(self, mode):
1591 class MyStringIO(StringIO.StringIO):
1592 hit_eof = False
1593 def read(self, n):
1594 if self.hit_eof:
1595 raise AssertionError("infinite loop detected in tarfile.open()")
1596 self.hit_eof = self.pos == self.len
1597 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001598 def seek(self, *args):
1599 self.hit_eof = False
1600 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001601
1602 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1603 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001604 try:
1605 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1606 except tarfile.ReadError:
1607 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001608
1609 def test_partial_input(self):
1610 self._test_partial_input("r")
1611
1612 def test_partial_input_bz2(self):
1613 self._test_partial_input("r:bz2")
1614
1615
Neal Norwitz996acf12003-02-17 14:51:41 +00001616def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001617 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001618
Walter Dörwald21d3a322003-05-01 17:45:56 +00001619 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001620 UstarReadTest,
1621 MiscReadTest,
1622 StreamReadTest,
1623 DetectReadTest,
1624 MemberReadTest,
1625 GNUReadTest,
1626 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001627 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001628 StreamWriteTest,
1629 GNUWriteTest,
1630 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001631 UstarUnicodeTest,
1632 GNUUnicodeTest,
1633 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001634 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001635 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001636 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001637 ]
1638
Neal Norwitza4f651a2004-07-20 22:07:44 +00001639 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001640 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001641 else:
1642 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001643
1644 fobj = open(tarname, "rb")
1645 data = fobj.read()
1646 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001647
Walter Dörwald21d3a322003-05-01 17:45:56 +00001648 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001649 # Create testtar.tar.gz and add gzip-specific tests.
1650 tar = gzip.open(gzipname, "wb")
1651 tar.write(data)
1652 tar.close()
1653
1654 tests += [
1655 GzipMiscReadTest,
1656 GzipUstarReadTest,
1657 GzipStreamReadTest,
1658 GzipWriteTest,
1659 GzipStreamWriteTest,
1660 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001661
1662 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001663 # Create testtar.tar.bz2 and add bz2-specific tests.
1664 tar = bz2.BZ2File(bz2name, "wb")
1665 tar.write(data)
1666 tar.close()
1667
1668 tests += [
1669 Bz2MiscReadTest,
1670 Bz2UstarReadTest,
1671 Bz2StreamReadTest,
1672 Bz2WriteTest,
1673 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001674 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001675 ]
1676
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001677 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001678 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001679 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001680 if os.path.exists(TEMPDIR):
1681 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001682
Neal Norwitz996acf12003-02-17 14:51:41 +00001683if __name__ == "__main__":
1684 test_main()