blob: 49d2d07d90a8fc81e4dbddfd6248e8e6dc83bd85 [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äbelc64e4022007-03-13 10:47:19 +0000157
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000158class CommonReadTest(ReadTest):
159
160 def test_empty_tarfile(self):
161 # Test for issue6123: Allow opening empty archives.
162 # This test checks if tarfile.open() is able to open an empty tar
163 # archive successfully. Note that an empty tar archive is not the
164 # same as an empty file!
165 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
166 try:
167 tar = tarfile.open(tmpname, self.mode)
168 tar.getnames()
169 except tarfile.ReadError:
170 self.fail("tarfile.open() failed on empty archive")
171 self.assertListEqual(tar.getmembers(), [])
172
173 def test_null_tarfile(self):
174 # Test for issue6123: Allow opening empty archives.
175 # This test guarantees that tarfile.open() does not treat an empty
176 # file as an empty tar archive.
177 open(tmpname, "wb").close()
178 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
179 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
180
181 def test_ignore_zeros(self):
182 # Test TarFile's ignore_zeros option.
183 if self.mode.endswith(":gz"):
184 _open = gzip.GzipFile
185 elif self.mode.endswith(":bz2"):
186 _open = bz2.BZ2File
187 else:
188 _open = open
189
190 for char in ('\0', 'a'):
191 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
192 # are ignored correctly.
193 fobj = _open(tmpname, "wb")
194 fobj.write(char * 1024)
195 fobj.write(tarfile.TarInfo("foo").tobuf())
196 fobj.close()
197
198 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
199 self.assertListEqual(tar.getnames(), ["foo"],
200 "ignore_zeros=True should have skipped the %r-blocks" % char)
201 tar.close()
202
203
204class MiscReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000205
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000206 def test_no_name_argument(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000207 fobj = open(self.tarname, "rb")
208 tar = tarfile.open(fileobj=fobj, mode=self.mode)
209 self.assertEqual(tar.name, os.path.abspath(fobj.name))
210
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000211 def test_no_name_attribute(self):
212 data = open(self.tarname, "rb").read()
213 fobj = StringIO.StringIO(data)
214 self.assertRaises(AttributeError, getattr, fobj, "name")
215 tar = tarfile.open(fileobj=fobj, mode=self.mode)
216 self.assertEqual(tar.name, None)
217
218 def test_empty_name_attribute(self):
219 data = open(self.tarname, "rb").read()
220 fobj = StringIO.StringIO(data)
221 fobj.name = ""
222 tar = tarfile.open(fileobj=fobj, mode=self.mode)
223 self.assertEqual(tar.name, None)
224
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000225 def test_fileobj_with_offset(self):
226 # Skip the first member and store values from the second member
227 # of the testtar.
228 tar = tarfile.open(self.tarname, mode=self.mode)
229 tar.next()
230 t = tar.next()
231 name = t.name
232 offset = t.offset
233 data = tar.extractfile(t).read()
234 tar.close()
235
236 # Open the testtar and seek to the offset of the second member.
237 if self.mode.endswith(":gz"):
238 _open = gzip.GzipFile
239 elif self.mode.endswith(":bz2"):
240 _open = bz2.BZ2File
241 else:
242 _open = open
243 fobj = _open(self.tarname, "rb")
244 fobj.seek(offset)
245
246 # Test if the tarfile starts with the second member.
247 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
248 t = tar.next()
249 self.assertEqual(t.name, name)
250 # Read to the end of fileobj and test if seeking back to the
251 # beginning works.
252 tar.getmembers()
253 self.assertEqual(tar.extractfile(t).read(), data,
254 "seek back did not work")
255 tar.close()
256
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000257 def test_fail_comp(self):
258 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
259 if self.mode == "r:":
260 return
261 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
262 fobj = open(tarname, "rb")
263 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
264
265 def test_v7_dirtype(self):
266 # Test old style dirtype member (bug #1336623):
267 # Old V7 tars create directory members using an AREGTYPE
268 # header with a "/" appended to the filename field.
269 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000270 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000271 "v7 dirtype failed")
272
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000273 def test_xstar_type(self):
274 # The xstar format stores extra atime and ctime fields inside the
275 # space reserved for the prefix field. The prefix field must be
276 # ignored in this case, otherwise it will mess up the name.
277 try:
278 self.tar.getmember("misc/regtype-xstar")
279 except KeyError:
280 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
281
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000282 def test_check_members(self):
283 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000284 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000285 "wrong mtime for %s" % tarinfo.name)
286 if not tarinfo.name.startswith("ustar/"):
287 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000288 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000289 "wrong uname for %s" % tarinfo.name)
290
291 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000292 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000293 "could not find all members")
294
295 def test_extract_hardlink(self):
296 # Test hardlink extraction (e.g. bug #857297).
Lars Gustäbela36cde42007-03-13 15:47:07 +0000297 tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000298
299 tar.extract("ustar/regtype", TEMPDIR)
Neal Norwitzf3396542005-10-28 05:52:22 +0000300 try:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000301 tar.extract("ustar/lnktype", TEMPDIR)
302 except EnvironmentError, e:
303 if e.errno == errno.ENOENT:
304 self.fail("hardlink not extracted properly")
Neal Norwitzf3396542005-10-28 05:52:22 +0000305
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000306 data = open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb").read()
307 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000308
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000309 try:
310 tar.extract("ustar/symtype", TEMPDIR)
311 except EnvironmentError, e:
312 if e.errno == errno.ENOENT:
313 self.fail("symlink not extracted properly")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000314
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000315 data = open(os.path.join(TEMPDIR, "ustar/symtype"), "rb").read()
316 self.assertEqual(md5sum(data), md5_regtype)
317
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000318 def test_extractall(self):
319 # Test if extractall() correctly restores directory permissions
320 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000321 tar = tarfile.open(tarname, encoding="iso8859-1")
322 directories = [t for t in tar if t.isdir()]
323 tar.extractall(TEMPDIR, directories)
324 for tarinfo in directories:
325 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000326 if sys.platform != "win32":
327 # Win32 has no support for fine grained permissions.
328 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000329 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
330 tar.close()
331
Lars Gustäbel12adc652009-11-23 15:46:19 +0000332 def test_init_close_fobj(self):
333 # Issue #7341: Close the internal file object in the TarFile
334 # constructor in case of an error. For the test we rely on
335 # the fact that opening an empty file raises a ReadError.
336 empty = os.path.join(TEMPDIR, "empty")
337 open(empty, "wb").write("")
338
339 try:
340 tar = object.__new__(tarfile.TarFile)
341 try:
342 tar.__init__(empty)
343 except tarfile.ReadError:
344 self.assertTrue(tar.fileobj.closed)
345 else:
346 self.fail("ReadError not raised")
347 finally:
348 os.remove(empty)
349
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000350
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000351class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000352
353 mode="r|"
354
355 def test_fileobj_regular_file(self):
356 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
357 fobj = self.tar.extractfile(tarinfo)
358 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000359 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000360 "regular file extraction failed")
361
362 def test_provoke_stream_error(self):
363 tarinfos = self.tar.getmembers()
364 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000365 self.assertRaises(tarfile.StreamError, f.read)
366
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000367 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000368 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000369 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000370
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000371 while True:
372 t1 = tar1.next()
373 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000374 if t1 is None:
375 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000376 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000377
378 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000379 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000380 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000381
382 v1 = tar1.extractfile(t1)
383 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000384 if v1 is None:
385 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000386 self.assertTrue(v2 is not None, "stream.extractfile() failed")
387 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000388
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000389 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000390
Georg Brandla32e0a02006-10-24 16:54:16 +0000391
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000392class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000393
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000394 def _testfunc_file(self, name, mode):
395 try:
396 tarfile.open(name, mode)
397 except tarfile.ReadError:
398 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000399
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000400 def _testfunc_fileobj(self, name, mode):
401 try:
402 tarfile.open(name, mode, fileobj=open(name, "rb"))
403 except tarfile.ReadError:
404 self.fail()
405
406 def _test_modes(self, testfunc):
407 testfunc(tarname, "r")
408 testfunc(tarname, "r:")
409 testfunc(tarname, "r:*")
410 testfunc(tarname, "r|")
411 testfunc(tarname, "r|*")
412
413 if gzip:
414 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
415 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
416 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
417 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
418
419 testfunc(gzipname, "r")
420 testfunc(gzipname, "r:*")
421 testfunc(gzipname, "r:gz")
422 testfunc(gzipname, "r|*")
423 testfunc(gzipname, "r|gz")
424
425 if bz2:
426 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
427 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
428 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
429 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
430
431 testfunc(bz2name, "r")
432 testfunc(bz2name, "r:*")
433 testfunc(bz2name, "r:bz2")
434 testfunc(bz2name, "r|*")
435 testfunc(bz2name, "r|bz2")
436
437 def test_detect_file(self):
438 self._test_modes(self._testfunc_file)
439
440 def test_detect_fileobj(self):
441 self._test_modes(self._testfunc_fileobj)
442
Lars Gustäbel9a388632011-12-06 13:07:09 +0100443 def test_detect_stream_bz2(self):
444 # Originally, tarfile's stream detection looked for the string
445 # "BZh91" at the start of the file. This is incorrect because
446 # the '9' represents the blocksize (900kB). If the file was
447 # compressed using another blocksize autodetection fails.
448 if not bz2:
449 return
450
451 with open(tarname, "rb") as fobj:
452 data = fobj.read()
453
454 # Compress with blocksize 100kB, the file starts with "BZh11".
455 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
456 fobj.write(data)
457
458 self._testfunc_file(tmpname, "r|*")
459
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000460
461class MemberReadTest(ReadTest):
462
463 def _test_member(self, tarinfo, chksum=None, **kwargs):
464 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000465 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000466 "wrong md5sum for %s" % tarinfo.name)
467
468 kwargs["mtime"] = 07606136617
469 kwargs["uid"] = 1000
470 kwargs["gid"] = 100
471 if "old-v7" not in tarinfo.name:
472 # V7 tar can't handle alphabetic owners.
473 kwargs["uname"] = "tarfile"
474 kwargs["gname"] = "tarfile"
475 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000476 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000477 "wrong value in %s field of %s" % (k, tarinfo.name))
478
479 def test_find_regtype(self):
480 tarinfo = self.tar.getmember("ustar/regtype")
481 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
482
483 def test_find_conttype(self):
484 tarinfo = self.tar.getmember("ustar/conttype")
485 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
486
487 def test_find_dirtype(self):
488 tarinfo = self.tar.getmember("ustar/dirtype")
489 self._test_member(tarinfo, size=0)
490
491 def test_find_dirtype_with_size(self):
492 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
493 self._test_member(tarinfo, size=255)
494
495 def test_find_lnktype(self):
496 tarinfo = self.tar.getmember("ustar/lnktype")
497 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
498
499 def test_find_symtype(self):
500 tarinfo = self.tar.getmember("ustar/symtype")
501 self._test_member(tarinfo, size=0, linkname="regtype")
502
503 def test_find_blktype(self):
504 tarinfo = self.tar.getmember("ustar/blktype")
505 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
506
507 def test_find_chrtype(self):
508 tarinfo = self.tar.getmember("ustar/chrtype")
509 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
510
511 def test_find_fifotype(self):
512 tarinfo = self.tar.getmember("ustar/fifotype")
513 self._test_member(tarinfo, size=0)
514
515 def test_find_sparse(self):
516 tarinfo = self.tar.getmember("ustar/sparse")
517 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
518
519 def test_find_umlauts(self):
520 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
521 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
522
523 def test_find_ustar_longname(self):
524 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000525 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000526
527 def test_find_regtype_oldv7(self):
528 tarinfo = self.tar.getmember("misc/regtype-old-v7")
529 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
530
531 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000532 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000533 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
534 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
535
536
537class LongnameTest(ReadTest):
538
539 def test_read_longname(self):
540 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000541 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000542 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000543 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000544 except KeyError:
545 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000546 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000547
548 def test_read_longlink(self):
549 longname = self.subdir + "/" + "123/" * 125 + "longname"
550 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
551 try:
552 tarinfo = self.tar.getmember(longlink)
553 except KeyError:
554 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000555 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000556
557 def test_truncated_longname(self):
558 longname = self.subdir + "/" + "123/" * 125 + "longname"
559 tarinfo = self.tar.getmember(longname)
560 offset = tarinfo.offset
561 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000562 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000563 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
564
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000565 def test_header_offset(self):
566 # Test if the start offset of the TarInfo object includes
567 # the preceding extended header.
568 longname = self.subdir + "/" + "123/" * 125 + "longname"
569 offset = self.tar.getmember(longname).offset
570 fobj = open(tarname)
571 fobj.seek(offset)
572 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
573 self.assertEqual(tarinfo.type, self.longnametype)
574
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000575
576class GNUReadTest(LongnameTest):
577
578 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000579 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000580
581 def test_sparse_file(self):
582 tarinfo1 = self.tar.getmember("ustar/sparse")
583 fobj1 = self.tar.extractfile(tarinfo1)
584 tarinfo2 = self.tar.getmember("gnu/sparse")
585 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000586 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000587 "sparse file extraction failed")
588
589
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000590class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000591
592 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000593 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000594
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000595 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000596 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000597
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000598 tarinfo = tar.getmember("pax/regtype1")
599 self.assertEqual(tarinfo.uname, "foo")
600 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000601 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000602
603 tarinfo = tar.getmember("pax/regtype2")
604 self.assertEqual(tarinfo.uname, "")
605 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000606 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000607
608 tarinfo = tar.getmember("pax/regtype3")
609 self.assertEqual(tarinfo.uname, "tarfile")
610 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000611 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
612
613 def test_pax_number_fields(self):
614 # All following number fields are read from the pax header.
615 tar = tarfile.open(tarname, encoding="iso8859-1")
616 tarinfo = tar.getmember("pax/regtype4")
617 self.assertEqual(tarinfo.size, 7011)
618 self.assertEqual(tarinfo.uid, 123)
619 self.assertEqual(tarinfo.gid, 123)
620 self.assertEqual(tarinfo.mtime, 1041808783.0)
621 self.assertEqual(type(tarinfo.mtime), float)
622 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
623 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000624
625
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000626class WriteTestBase(unittest.TestCase):
627 # Put all write tests in here that are supposed to be tested
628 # in all possible mode combinations.
629
630 def test_fileobj_no_close(self):
631 fobj = StringIO.StringIO()
632 tar = tarfile.open(fileobj=fobj, mode=self.mode)
633 tar.addfile(tarfile.TarInfo("foo"))
634 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000635 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000636
637
638class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000639
640 mode = "w:"
641
642 def test_100_char_name(self):
643 # The name field in a tar header stores strings of at most 100 chars.
644 # If a string is shorter than 100 chars it has to be padded with '\0',
645 # which implies that a string of exactly 100 chars is stored without
646 # a trailing '\0'.
647 name = "0123456789" * 10
648 tar = tarfile.open(tmpname, self.mode)
649 t = tarfile.TarInfo(name)
650 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000651 tar.close()
652
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000653 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000654 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000655 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000656 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000657
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000658 def test_tar_size(self):
659 # Test for bug #1013882.
660 tar = tarfile.open(tmpname, self.mode)
661 path = os.path.join(TEMPDIR, "file")
662 fobj = open(path, "wb")
663 fobj.write("aaa")
664 fobj.close()
665 tar.add(path)
666 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000667 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000668 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000669
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000670 # The test_*_size tests test for bug #1167128.
671 def test_file_size(self):
672 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000673
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000674 path = os.path.join(TEMPDIR, "file")
675 fobj = open(path, "wb")
676 fobj.close()
677 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000678 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000679
680 fobj = open(path, "wb")
681 fobj.write("aaa")
682 fobj.close()
683 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000684 self.assertEqual(tarinfo.size, 3)
685
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000686 tar.close()
687
688 def test_directory_size(self):
689 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000690 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000691 try:
692 tar = tarfile.open(tmpname, self.mode)
693 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000694 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000695 finally:
696 os.rmdir(path)
697
698 def test_link_size(self):
699 if hasattr(os, "link"):
700 link = os.path.join(TEMPDIR, "link")
701 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000702 fobj = open(target, "wb")
703 fobj.write("aaa")
704 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000705 os.link(target, link)
706 try:
707 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000708 # Record the link target in the inodes list.
709 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000710 tarinfo = tar.gettarinfo(link)
711 self.assertEqual(tarinfo.size, 0)
712 finally:
713 os.remove(target)
714 os.remove(link)
715
716 def test_symlink_size(self):
717 if hasattr(os, "symlink"):
718 path = os.path.join(TEMPDIR, "symlink")
719 os.symlink("link_target", path)
720 try:
721 tar = tarfile.open(tmpname, self.mode)
722 tarinfo = tar.gettarinfo(path)
723 self.assertEqual(tarinfo.size, 0)
724 finally:
725 os.remove(path)
726
727 def test_add_self(self):
728 # Test for #1257255.
729 dstname = os.path.abspath(tmpname)
730
731 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000732 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000733
734 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000735 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000736
737 cwd = os.getcwd()
738 os.chdir(TEMPDIR)
739 tar.add(dstname)
740 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000741 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000742
Lars Gustäbel104490e2007-06-18 11:42:11 +0000743 def test_exclude(self):
744 tempdir = os.path.join(TEMPDIR, "exclude")
745 os.mkdir(tempdir)
746 try:
747 for name in ("foo", "bar", "baz"):
748 name = os.path.join(tempdir, name)
749 open(name, "wb").close()
750
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000751 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000752
753 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000754 with test_support.check_warnings(("use the filter argument",
755 DeprecationWarning)):
756 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000757 tar.close()
758
759 tar = tarfile.open(tmpname, "r")
760 self.assertEqual(len(tar.getmembers()), 1)
761 self.assertEqual(tar.getnames()[0], "empty_dir")
762 finally:
763 shutil.rmtree(tempdir)
764
Lars Gustäbel21121e62009-09-12 10:28:15 +0000765 def test_filter(self):
766 tempdir = os.path.join(TEMPDIR, "filter")
767 os.mkdir(tempdir)
768 try:
769 for name in ("foo", "bar", "baz"):
770 name = os.path.join(tempdir, name)
771 open(name, "wb").close()
772
773 def filter(tarinfo):
774 if os.path.basename(tarinfo.name) == "bar":
775 return
776 tarinfo.uid = 123
777 tarinfo.uname = "foo"
778 return tarinfo
779
780 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
781 tar.add(tempdir, arcname="empty_dir", filter=filter)
782 tar.close()
783
784 tar = tarfile.open(tmpname, "r")
785 for tarinfo in tar:
786 self.assertEqual(tarinfo.uid, 123)
787 self.assertEqual(tarinfo.uname, "foo")
788 self.assertEqual(len(tar.getmembers()), 3)
789 tar.close()
790 finally:
791 shutil.rmtree(tempdir)
792
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000793 # Guarantee that stored pathnames are not modified. Don't
794 # remove ./ or ../ or double slashes. Still make absolute
795 # pathnames relative.
796 # For details see bug #6054.
797 def _test_pathname(self, path, cmp_path=None, dir=False):
798 # Create a tarfile with an empty member named path
799 # and compare the stored name with the original.
800 foo = os.path.join(TEMPDIR, "foo")
801 if not dir:
802 open(foo, "w").close()
803 else:
804 os.mkdir(foo)
805
806 tar = tarfile.open(tmpname, self.mode)
807 tar.add(foo, arcname=path)
808 tar.close()
809
810 tar = tarfile.open(tmpname, "r")
811 t = tar.next()
812 tar.close()
813
814 if not dir:
815 os.remove(foo)
816 else:
817 os.rmdir(foo)
818
819 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
820
821 def test_pathnames(self):
822 self._test_pathname("foo")
823 self._test_pathname(os.path.join("foo", ".", "bar"))
824 self._test_pathname(os.path.join("foo", "..", "bar"))
825 self._test_pathname(os.path.join(".", "foo"))
826 self._test_pathname(os.path.join(".", "foo", "."))
827 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
828 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
829 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
830 self._test_pathname(os.path.join("..", "foo"))
831 self._test_pathname(os.path.join("..", "foo", ".."))
832 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
833 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
834
835 self._test_pathname("foo" + os.sep + os.sep + "bar")
836 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
837
838 def test_abs_pathnames(self):
839 if sys.platform == "win32":
840 self._test_pathname("C:\\foo", "foo")
841 else:
842 self._test_pathname("/foo", "foo")
843 self._test_pathname("///foo", "foo")
844
845 def test_cwd(self):
846 # Test adding the current working directory.
847 cwd = os.getcwd()
848 os.chdir(TEMPDIR)
849 try:
850 open("foo", "w").close()
851
852 tar = tarfile.open(tmpname, self.mode)
853 tar.add(".")
854 tar.close()
855
856 tar = tarfile.open(tmpname, "r")
857 for t in tar:
858 self.assert_(t.name == "." or t.name.startswith("./"))
859 tar.close()
860 finally:
861 os.chdir(cwd)
862
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800863 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800864 def test_extractall_symlinks(self):
865 # Test if extractall works properly when tarfile contains symlinks
866 tempdir = os.path.join(TEMPDIR, "testsymlinks")
867 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
868 os.mkdir(tempdir)
869 try:
870 source_file = os.path.join(tempdir,'source')
871 target_file = os.path.join(tempdir,'symlink')
872 with open(source_file,'w') as f:
873 f.write('something\n')
874 os.symlink(source_file, target_file)
875 tar = tarfile.open(temparchive,'w')
876 tar.add(source_file, arcname=os.path.basename(source_file))
877 tar.add(target_file, arcname=os.path.basename(target_file))
878 tar.close()
879 # Let's extract it to the location which contains the symlink
880 tar = tarfile.open(temparchive,'r')
881 # this should not raise OSError: [Errno 17] File exists
882 try:
883 tar.extractall(path=tempdir)
884 except OSError:
885 self.fail("extractall failed with symlinked files")
886 finally:
887 tar.close()
888 finally:
889 os.unlink(temparchive)
890 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000891
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +0800892 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
893 def test_extractall_broken_symlinks(self):
894 # Test if extractall works properly when tarfile contains broken
895 # symlinks
896 tempdir = os.path.join(TEMPDIR, "testsymlinks")
897 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
898 os.mkdir(tempdir)
899 try:
900 source_file = os.path.join(tempdir,'source')
901 target_file = os.path.join(tempdir,'symlink')
902 with open(source_file,'w') as f:
903 f.write('something\n')
904 os.symlink(source_file, target_file)
905 tar = tarfile.open(temparchive,'w')
906 tar.add(target_file, arcname=os.path.basename(target_file))
907 tar.close()
908 # remove the real file
909 os.unlink(source_file)
910 # Let's extract it to the location which contains the symlink
911 tar = tarfile.open(temparchive,'r')
912 # this should not raise OSError: [Errno 17] File exists
913 try:
914 tar.extractall(path=tempdir)
915 except OSError:
916 self.fail("extractall failed with broken symlinked files")
917 finally:
918 tar.close()
919 finally:
920 os.unlink(temparchive)
921 shutil.rmtree(tempdir)
922
923 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
924 def test_extractall_hardlinks(self):
925 # Test if extractall works properly when tarfile contains symlinks
926 tempdir = os.path.join(TEMPDIR, "testsymlinks")
927 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
928 os.mkdir(tempdir)
929 try:
930 source_file = os.path.join(tempdir,'source')
931 target_file = os.path.join(tempdir,'symlink')
932 with open(source_file,'w') as f:
933 f.write('something\n')
934 os.link(source_file, target_file)
935 tar = tarfile.open(temparchive,'w')
936 tar.add(source_file, arcname=os.path.basename(source_file))
937 tar.add(target_file, arcname=os.path.basename(target_file))
938 tar.close()
939 # Let's extract it to the location which contains the symlink
940 tar = tarfile.open(temparchive,'r')
941 # this should not raise OSError: [Errno 17] File exists
942 try:
943 tar.extractall(path=tempdir)
944 except OSError:
945 self.fail("extractall failed with linked files")
946 finally:
947 tar.close()
948 finally:
949 os.unlink(temparchive)
950 shutil.rmtree(tempdir)
951
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000952class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000953
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000954 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +0000955
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000956 def test_stream_padding(self):
957 # Test for bug #1543303.
958 tar = tarfile.open(tmpname, self.mode)
959 tar.close()
960
961 if self.mode.endswith("gz"):
962 fobj = gzip.GzipFile(tmpname)
963 data = fobj.read()
964 fobj.close()
965 elif self.mode.endswith("bz2"):
966 dec = bz2.BZ2Decompressor()
967 data = open(tmpname, "rb").read()
968 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000969 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000970 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +0000971 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000972 fobj = open(tmpname, "rb")
973 data = fobj.read()
974 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +0000975
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000976 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +0000977 "incorrect zero padding")
978
Lars Gustäbel5c4c4612010-04-29 15:23:38 +0000979 def test_file_mode(self):
980 # Test for issue #8464: Create files with correct
981 # permissions.
982 if sys.platform == "win32" or not hasattr(os, "umask"):
983 return
984
985 if os.path.exists(tmpname):
986 os.remove(tmpname)
987
988 original_umask = os.umask(0022)
989 try:
990 tar = tarfile.open(tmpname, self.mode)
991 tar.close()
992 mode = os.stat(tmpname).st_mode & 0777
993 self.assertEqual(mode, 0644, "wrong file permissions")
994 finally:
995 os.umask(original_umask)
996
Neal Norwitz8a519392006-08-21 17:59:46 +0000997
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000998class GNUWriteTest(unittest.TestCase):
999 # This testcase checks for correct creation of GNU Longname
1000 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001001
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001002 def _length(self, s):
1003 blocks, remainder = divmod(len(s) + 1, 512)
1004 if remainder:
1005 blocks += 1
1006 return blocks * 512
1007
1008 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001009 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001010 count = 512
1011
1012 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001013 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001014 count += 512
1015 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001016 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001017 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001018 count += 512
1019 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001020 return count
1021
1022 def _test(self, name, link=None):
1023 tarinfo = tarfile.TarInfo(name)
1024 if link:
1025 tarinfo.linkname = link
1026 tarinfo.type = tarfile.LNKTYPE
1027
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001028 tar = tarfile.open(tmpname, "w")
1029 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001030 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001031
1032 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001033 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001034 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001035
Georg Brandl87fa5592006-12-06 22:21:18 +00001036 tar.close()
1037
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001038 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001039 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001040 self.assertIsNotNone(member,
1041 "unable to read longname member")
1042 self.assertEqual(tarinfo.name, member.name,
1043 "unable to read longname member")
1044 self.assertEqual(tarinfo.linkname, member.linkname,
1045 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001046
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001047 def test_longname_1023(self):
1048 self._test(("longnam/" * 127) + "longnam")
1049
1050 def test_longname_1024(self):
1051 self._test(("longnam/" * 127) + "longname")
1052
1053 def test_longname_1025(self):
1054 self._test(("longnam/" * 127) + "longname_")
1055
1056 def test_longlink_1023(self):
1057 self._test("name", ("longlnk/" * 127) + "longlnk")
1058
1059 def test_longlink_1024(self):
1060 self._test("name", ("longlnk/" * 127) + "longlink")
1061
1062 def test_longlink_1025(self):
1063 self._test("name", ("longlnk/" * 127) + "longlink_")
1064
1065 def test_longnamelink_1023(self):
1066 self._test(("longnam/" * 127) + "longnam",
1067 ("longlnk/" * 127) + "longlnk")
1068
1069 def test_longnamelink_1024(self):
1070 self._test(("longnam/" * 127) + "longname",
1071 ("longlnk/" * 127) + "longlink")
1072
1073 def test_longnamelink_1025(self):
1074 self._test(("longnam/" * 127) + "longname_",
1075 ("longlnk/" * 127) + "longlink_")
1076
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001077
1078class HardlinkTest(unittest.TestCase):
1079 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001080
1081 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001082 self.foo = os.path.join(TEMPDIR, "foo")
1083 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001084
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001085 fobj = open(self.foo, "wb")
1086 fobj.write("foo")
1087 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001088
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001089 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001090
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001091 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001092 self.tar.add(self.foo)
1093
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001094 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001095 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001096 os.remove(self.foo)
1097 os.remove(self.bar)
1098
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001099 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001100 # The same name will be added as a REGTYPE every
1101 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001102 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001103 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001104 "add file as regular failed")
1105
1106 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001107 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001108 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001109 "add file as hardlink failed")
1110
1111 def test_dereference_hardlink(self):
1112 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001113 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001114 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001115 "dereferencing hardlink failed")
1116
Neal Norwitza4f651a2004-07-20 22:07:44 +00001117
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001118class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001119
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001120 def _test(self, name, link=None):
1121 # See GNUWriteTest.
1122 tarinfo = tarfile.TarInfo(name)
1123 if link:
1124 tarinfo.linkname = link
1125 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001126
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001127 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1128 tar.addfile(tarinfo)
1129 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001130
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001131 tar = tarfile.open(tmpname)
1132 if link:
1133 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001134 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001135 else:
1136 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001137 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001138
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001139 def test_pax_global_header(self):
1140 pax_headers = {
1141 u"foo": u"bar",
1142 u"uid": u"0",
1143 u"mtime": u"1.23",
1144 u"test": u"äöü",
1145 u"äöü": u"test"}
1146
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001147 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001148 pax_headers=pax_headers)
1149 tar.addfile(tarfile.TarInfo("test"))
1150 tar.close()
1151
1152 # Test if the global header was written correctly.
1153 tar = tarfile.open(tmpname, encoding="iso8859-1")
1154 self.assertEqual(tar.pax_headers, pax_headers)
1155 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1156
1157 # Test if all the fields are unicode.
1158 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001159 self.assertTrue(type(key) is unicode)
1160 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001161 if key in tarfile.PAX_NUMBER_FIELDS:
1162 try:
1163 tarfile.PAX_NUMBER_FIELDS[key](val)
1164 except (TypeError, ValueError):
1165 self.fail("unable to convert pax header field")
1166
1167 def test_pax_extended_header(self):
1168 # The fields from the pax header have priority over the
1169 # TarInfo.
1170 pax_headers = {u"path": u"foo", u"uid": u"123"}
1171
1172 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1173 t = tarfile.TarInfo()
1174 t.name = u"äöü" # non-ASCII
1175 t.uid = 8**8 # too large
1176 t.pax_headers = pax_headers
1177 tar.addfile(t)
1178 tar.close()
1179
1180 tar = tarfile.open(tmpname, encoding="iso8859-1")
1181 t = tar.getmembers()[0]
1182 self.assertEqual(t.pax_headers, pax_headers)
1183 self.assertEqual(t.name, "foo")
1184 self.assertEqual(t.uid, 123)
1185
1186
1187class UstarUnicodeTest(unittest.TestCase):
1188 # All *UnicodeTests FIXME
1189
1190 format = tarfile.USTAR_FORMAT
1191
1192 def test_iso8859_1_filename(self):
1193 self._test_unicode_filename("iso8859-1")
1194
1195 def test_utf7_filename(self):
1196 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001197
1198 def test_utf8_filename(self):
1199 self._test_unicode_filename("utf8")
1200
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001201 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001202 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1203 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001204 tar.addfile(tarfile.TarInfo(name))
1205 tar.close()
1206
1207 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001208 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001209 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001210 tar.close()
1211
1212 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001213 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1214 tarinfo = tarfile.TarInfo()
1215
1216 tarinfo.name = "äöü"
1217 if self.format == tarfile.PAX_FORMAT:
1218 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1219 else:
1220 tar.addfile(tarinfo)
1221
1222 tarinfo.name = u"äöü"
1223 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1224
1225 tarinfo.name = "foo"
1226 tarinfo.uname = u"äöü"
1227 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1228
1229 def test_unicode_argument(self):
1230 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1231 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001232 self.assertTrue(type(t.name) is str)
1233 self.assertTrue(type(t.linkname) is str)
1234 self.assertTrue(type(t.uname) is str)
1235 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001236 tar.close()
1237
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001238 def test_uname_unicode(self):
1239 for name in (u"äöü", "äöü"):
1240 t = tarfile.TarInfo("foo")
1241 t.uname = name
1242 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001243
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001244 fobj = StringIO.StringIO()
1245 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1246 tar.addfile(t)
1247 tar.close()
1248 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001249
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001250 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1251 t = tar.getmember("foo")
1252 self.assertEqual(t.uname, "äöü")
1253 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001254
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001255
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001256class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001257
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001258 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001259
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001260
1261class PaxUnicodeTest(UstarUnicodeTest):
1262
1263 format = tarfile.PAX_FORMAT
1264
1265 def _create_unicode_name(self, name):
1266 tar = tarfile.open(tmpname, "w", format=self.format)
1267 t = tarfile.TarInfo()
1268 t.pax_headers["path"] = name
1269 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001270 tar.close()
1271
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001272 def test_error_handlers(self):
1273 # Test if the unicode error handlers work correctly for characters
1274 # that cannot be expressed in a given encoding.
1275 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001276
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001277 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1278 ("replace", "???"), ("ignore", "")):
1279 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1280 errors=handler)
1281 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001282
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001283 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1284 encoding="ascii", errors="strict")
1285
1286 def test_error_handler_utf8(self):
1287 # Create a pathname that has one component representable using
1288 # iso8859-1 and the other only in iso8859-15.
1289 self._create_unicode_name(u"äöü/¤")
1290
1291 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1292 errors="utf-8")
1293 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001294
Georg Brandlded1c4d2006-12-20 11:55:16 +00001295
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001296class AppendTest(unittest.TestCase):
1297 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001298
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001299 def setUp(self):
1300 self.tarname = tmpname
1301 if os.path.exists(self.tarname):
1302 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001303
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001304 def _add_testfile(self, fileobj=None):
1305 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1306 tar.addfile(tarfile.TarInfo("bar"))
1307 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001308
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001309 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001310 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001311 t = src.getmember("ustar/regtype")
1312 t.name = "foo"
1313 f = src.extractfile(t)
1314 tar = tarfile.open(self.tarname, mode)
1315 tar.addfile(t, f)
1316 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001317
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001318 def _test(self, names=["bar"], fileobj=None):
1319 tar = tarfile.open(self.tarname, fileobj=fileobj)
1320 self.assertEqual(tar.getnames(), names)
1321
1322 def test_non_existing(self):
1323 self._add_testfile()
1324 self._test()
1325
1326 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001327 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001328 self._add_testfile()
1329 self._test()
1330
1331 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001332 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001333 self._add_testfile(fobj)
1334 fobj.seek(0)
1335 self._test(fileobj=fobj)
1336
1337 def test_fileobj(self):
1338 self._create_testtar()
1339 data = open(self.tarname).read()
1340 fobj = StringIO.StringIO(data)
1341 self._add_testfile(fobj)
1342 fobj.seek(0)
1343 self._test(names=["foo", "bar"], fileobj=fobj)
1344
1345 def test_existing(self):
1346 self._create_testtar()
1347 self._add_testfile()
1348 self._test(names=["foo", "bar"])
1349
1350 def test_append_gz(self):
1351 if gzip is None:
1352 return
1353 self._create_testtar("w:gz")
1354 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1355
1356 def test_append_bz2(self):
1357 if bz2 is None:
1358 return
1359 self._create_testtar("w:bz2")
1360 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1361
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001362 # Append mode is supposed to fail if the tarfile to append to
1363 # does not end with a zero block.
1364 def _test_error(self, data):
1365 open(self.tarname, "wb").write(data)
1366 self.assertRaises(tarfile.ReadError, self._add_testfile)
1367
1368 def test_null(self):
1369 self._test_error("")
1370
1371 def test_incomplete(self):
1372 self._test_error("\0" * 13)
1373
1374 def test_premature_eof(self):
1375 data = tarfile.TarInfo("foo").tobuf()
1376 self._test_error(data)
1377
1378 def test_trailing_garbage(self):
1379 data = tarfile.TarInfo("foo").tobuf()
1380 self._test_error(data + "\0" * 13)
1381
1382 def test_invalid(self):
1383 self._test_error("a" * 512)
1384
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001385
1386class LimitsTest(unittest.TestCase):
1387
1388 def test_ustar_limits(self):
1389 # 100 char name
1390 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001391 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001392
1393 # 101 char name that cannot be stored
1394 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001395 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001396
1397 # 256 char name with a slash at pos 156
1398 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001399 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001400
1401 # 256 char name that cannot be stored
1402 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001403 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001404
1405 # 512 char name
1406 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001407 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001408
1409 # 512 char linkname
1410 tarinfo = tarfile.TarInfo("longlink")
1411 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001412 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001413
1414 # uid > 8 digits
1415 tarinfo = tarfile.TarInfo("name")
1416 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001417 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001418
1419 def test_gnu_limits(self):
1420 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001421 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001422
1423 tarinfo = tarfile.TarInfo("longlink")
1424 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001425 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001426
1427 # uid >= 256 ** 7
1428 tarinfo = tarfile.TarInfo("name")
1429 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001430 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001431
1432 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001433 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001434 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001435
1436 tarinfo = tarfile.TarInfo("longlink")
1437 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001438 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001439
1440 tarinfo = tarfile.TarInfo("name")
1441 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001442 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001443
1444
Lars Gustäbel64581042010-03-03 11:55:48 +00001445class ContextManagerTest(unittest.TestCase):
1446
1447 def test_basic(self):
1448 with tarfile.open(tarname) as tar:
1449 self.assertFalse(tar.closed, "closed inside runtime context")
1450 self.assertTrue(tar.closed, "context manager failed")
1451
1452 def test_closed(self):
1453 # The __enter__() method is supposed to raise IOError
1454 # if the TarFile object is already closed.
1455 tar = tarfile.open(tarname)
1456 tar.close()
1457 with self.assertRaises(IOError):
1458 with tar:
1459 pass
1460
1461 def test_exception(self):
1462 # Test if the IOError exception is passed through properly.
1463 with self.assertRaises(Exception) as exc:
1464 with tarfile.open(tarname) as tar:
1465 raise IOError
1466 self.assertIsInstance(exc.exception, IOError,
1467 "wrong exception raised in context manager")
1468 self.assertTrue(tar.closed, "context manager failed")
1469
1470 def test_no_eof(self):
1471 # __exit__() must not write end-of-archive blocks if an
1472 # exception was raised.
1473 try:
1474 with tarfile.open(tmpname, "w") as tar:
1475 raise Exception
1476 except:
1477 pass
1478 self.assertEqual(os.path.getsize(tmpname), 0,
1479 "context manager wrote an end-of-archive block")
1480 self.assertTrue(tar.closed, "context manager failed")
1481
1482 def test_eof(self):
1483 # __exit__() must write end-of-archive blocks, i.e. call
1484 # TarFile.close() if there was no error.
1485 with tarfile.open(tmpname, "w"):
1486 pass
1487 self.assertNotEqual(os.path.getsize(tmpname), 0,
1488 "context manager wrote no end-of-archive block")
1489
1490 def test_fileobj(self):
1491 # Test that __exit__() did not close the external file
1492 # object.
1493 fobj = open(tmpname, "wb")
1494 try:
1495 with tarfile.open(fileobj=fobj, mode="w") as tar:
1496 raise Exception
1497 except:
1498 pass
1499 self.assertFalse(fobj.closed, "external file object was closed")
1500 self.assertTrue(tar.closed, "context manager failed")
1501 fobj.close()
1502
1503
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001504class LinkEmulationTest(ReadTest):
1505
1506 # Test for issue #8741 regression. On platforms that do not support
1507 # symbolic or hard links tarfile tries to extract these types of members as
1508 # the regular files they point to.
1509 def _test_link_extraction(self, name):
1510 self.tar.extract(name, TEMPDIR)
1511 data = open(os.path.join(TEMPDIR, name), "rb").read()
1512 self.assertEqual(md5sum(data), md5_regtype)
1513
1514 def test_hardlink_extraction1(self):
1515 self._test_link_extraction("ustar/lnktype")
1516
1517 def test_hardlink_extraction2(self):
1518 self._test_link_extraction("./ustar/linktest2/lnktype")
1519
1520 def test_symlink_extraction1(self):
1521 self._test_link_extraction("ustar/symtype")
1522
1523 def test_symlink_extraction2(self):
1524 self._test_link_extraction("./ustar/linktest2/symtype")
1525
1526
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001527class GzipMiscReadTest(MiscReadTest):
1528 tarname = gzipname
1529 mode = "r:gz"
1530class GzipUstarReadTest(UstarReadTest):
1531 tarname = gzipname
1532 mode = "r:gz"
1533class GzipStreamReadTest(StreamReadTest):
1534 tarname = gzipname
1535 mode = "r|gz"
1536class GzipWriteTest(WriteTest):
1537 mode = "w:gz"
1538class GzipStreamWriteTest(StreamWriteTest):
1539 mode = "w|gz"
1540
1541
1542class Bz2MiscReadTest(MiscReadTest):
1543 tarname = bz2name
1544 mode = "r:bz2"
1545class Bz2UstarReadTest(UstarReadTest):
1546 tarname = bz2name
1547 mode = "r:bz2"
1548class Bz2StreamReadTest(StreamReadTest):
1549 tarname = bz2name
1550 mode = "r|bz2"
1551class Bz2WriteTest(WriteTest):
1552 mode = "w:bz2"
1553class Bz2StreamWriteTest(StreamWriteTest):
1554 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001555
Lars Gustäbel2020a592009-03-22 20:09:33 +00001556class Bz2PartialReadTest(unittest.TestCase):
1557 # Issue5068: The _BZ2Proxy.read() method loops forever
1558 # on an empty or partial bzipped file.
1559
1560 def _test_partial_input(self, mode):
1561 class MyStringIO(StringIO.StringIO):
1562 hit_eof = False
1563 def read(self, n):
1564 if self.hit_eof:
1565 raise AssertionError("infinite loop detected in tarfile.open()")
1566 self.hit_eof = self.pos == self.len
1567 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001568 def seek(self, *args):
1569 self.hit_eof = False
1570 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001571
1572 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1573 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001574 try:
1575 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1576 except tarfile.ReadError:
1577 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001578
1579 def test_partial_input(self):
1580 self._test_partial_input("r")
1581
1582 def test_partial_input_bz2(self):
1583 self._test_partial_input("r:bz2")
1584
1585
Neal Norwitz996acf12003-02-17 14:51:41 +00001586def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001587 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001588
Walter Dörwald21d3a322003-05-01 17:45:56 +00001589 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001590 UstarReadTest,
1591 MiscReadTest,
1592 StreamReadTest,
1593 DetectReadTest,
1594 MemberReadTest,
1595 GNUReadTest,
1596 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001597 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001598 StreamWriteTest,
1599 GNUWriteTest,
1600 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001601 UstarUnicodeTest,
1602 GNUUnicodeTest,
1603 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001604 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001605 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001606 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001607 ]
1608
Neal Norwitza4f651a2004-07-20 22:07:44 +00001609 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001610 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001611 else:
1612 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001613
1614 fobj = open(tarname, "rb")
1615 data = fobj.read()
1616 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001617
Walter Dörwald21d3a322003-05-01 17:45:56 +00001618 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001619 # Create testtar.tar.gz and add gzip-specific tests.
1620 tar = gzip.open(gzipname, "wb")
1621 tar.write(data)
1622 tar.close()
1623
1624 tests += [
1625 GzipMiscReadTest,
1626 GzipUstarReadTest,
1627 GzipStreamReadTest,
1628 GzipWriteTest,
1629 GzipStreamWriteTest,
1630 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001631
1632 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001633 # Create testtar.tar.bz2 and add bz2-specific tests.
1634 tar = bz2.BZ2File(bz2name, "wb")
1635 tar.write(data)
1636 tar.close()
1637
1638 tests += [
1639 Bz2MiscReadTest,
1640 Bz2UstarReadTest,
1641 Bz2StreamReadTest,
1642 Bz2WriteTest,
1643 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001644 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001645 ]
1646
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001647 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001648 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001649 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001650 if os.path.exists(TEMPDIR):
1651 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001652
Neal Norwitz996acf12003-02-17 14:51:41 +00001653if __name__ == "__main__":
1654 test_main()