blob: d5b864e238b41c1ceeb82de6356612fb08d44a96 [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
Lars Gustäbel7d4d0742011-12-21 19:27:50 +0100997 def test_issue13639(self):
998 try:
999 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1000 pass
1001 except UnicodeDecodeError:
1002 self.fail("_Stream failed to write unicode filename")
1003
Neal Norwitz8a519392006-08-21 17:59:46 +00001004
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001005class GNUWriteTest(unittest.TestCase):
1006 # This testcase checks for correct creation of GNU Longname
1007 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001008
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001009 def _length(self, s):
1010 blocks, remainder = divmod(len(s) + 1, 512)
1011 if remainder:
1012 blocks += 1
1013 return blocks * 512
1014
1015 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001016 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001017 count = 512
1018
1019 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001020 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001021 count += 512
1022 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001023 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001024 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001025 count += 512
1026 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001027 return count
1028
1029 def _test(self, name, link=None):
1030 tarinfo = tarfile.TarInfo(name)
1031 if link:
1032 tarinfo.linkname = link
1033 tarinfo.type = tarfile.LNKTYPE
1034
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001035 tar = tarfile.open(tmpname, "w")
1036 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001037 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001038
1039 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001040 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001041 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001042
Georg Brandl87fa5592006-12-06 22:21:18 +00001043 tar.close()
1044
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001045 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001046 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001047 self.assertIsNotNone(member,
1048 "unable to read longname member")
1049 self.assertEqual(tarinfo.name, member.name,
1050 "unable to read longname member")
1051 self.assertEqual(tarinfo.linkname, member.linkname,
1052 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001053
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001054 def test_longname_1023(self):
1055 self._test(("longnam/" * 127) + "longnam")
1056
1057 def test_longname_1024(self):
1058 self._test(("longnam/" * 127) + "longname")
1059
1060 def test_longname_1025(self):
1061 self._test(("longnam/" * 127) + "longname_")
1062
1063 def test_longlink_1023(self):
1064 self._test("name", ("longlnk/" * 127) + "longlnk")
1065
1066 def test_longlink_1024(self):
1067 self._test("name", ("longlnk/" * 127) + "longlink")
1068
1069 def test_longlink_1025(self):
1070 self._test("name", ("longlnk/" * 127) + "longlink_")
1071
1072 def test_longnamelink_1023(self):
1073 self._test(("longnam/" * 127) + "longnam",
1074 ("longlnk/" * 127) + "longlnk")
1075
1076 def test_longnamelink_1024(self):
1077 self._test(("longnam/" * 127) + "longname",
1078 ("longlnk/" * 127) + "longlink")
1079
1080 def test_longnamelink_1025(self):
1081 self._test(("longnam/" * 127) + "longname_",
1082 ("longlnk/" * 127) + "longlink_")
1083
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001084
1085class HardlinkTest(unittest.TestCase):
1086 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001087
1088 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001089 self.foo = os.path.join(TEMPDIR, "foo")
1090 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001091
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001092 fobj = open(self.foo, "wb")
1093 fobj.write("foo")
1094 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001095
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001096 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001097
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001098 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001099 self.tar.add(self.foo)
1100
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001101 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001102 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001103 os.remove(self.foo)
1104 os.remove(self.bar)
1105
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001106 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001107 # The same name will be added as a REGTYPE every
1108 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001109 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001110 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001111 "add file as regular failed")
1112
1113 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001114 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001115 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001116 "add file as hardlink failed")
1117
1118 def test_dereference_hardlink(self):
1119 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001120 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001121 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001122 "dereferencing hardlink failed")
1123
Neal Norwitza4f651a2004-07-20 22:07:44 +00001124
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001125class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001126
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001127 def _test(self, name, link=None):
1128 # See GNUWriteTest.
1129 tarinfo = tarfile.TarInfo(name)
1130 if link:
1131 tarinfo.linkname = link
1132 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001133
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001134 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1135 tar.addfile(tarinfo)
1136 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001137
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001138 tar = tarfile.open(tmpname)
1139 if link:
1140 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001141 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001142 else:
1143 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001144 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001145
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001146 def test_pax_global_header(self):
1147 pax_headers = {
1148 u"foo": u"bar",
1149 u"uid": u"0",
1150 u"mtime": u"1.23",
1151 u"test": u"äöü",
1152 u"äöü": u"test"}
1153
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001154 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001155 pax_headers=pax_headers)
1156 tar.addfile(tarfile.TarInfo("test"))
1157 tar.close()
1158
1159 # Test if the global header was written correctly.
1160 tar = tarfile.open(tmpname, encoding="iso8859-1")
1161 self.assertEqual(tar.pax_headers, pax_headers)
1162 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1163
1164 # Test if all the fields are unicode.
1165 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001166 self.assertTrue(type(key) is unicode)
1167 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001168 if key in tarfile.PAX_NUMBER_FIELDS:
1169 try:
1170 tarfile.PAX_NUMBER_FIELDS[key](val)
1171 except (TypeError, ValueError):
1172 self.fail("unable to convert pax header field")
1173
1174 def test_pax_extended_header(self):
1175 # The fields from the pax header have priority over the
1176 # TarInfo.
1177 pax_headers = {u"path": u"foo", u"uid": u"123"}
1178
1179 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1180 t = tarfile.TarInfo()
1181 t.name = u"äöü" # non-ASCII
1182 t.uid = 8**8 # too large
1183 t.pax_headers = pax_headers
1184 tar.addfile(t)
1185 tar.close()
1186
1187 tar = tarfile.open(tmpname, encoding="iso8859-1")
1188 t = tar.getmembers()[0]
1189 self.assertEqual(t.pax_headers, pax_headers)
1190 self.assertEqual(t.name, "foo")
1191 self.assertEqual(t.uid, 123)
1192
1193
1194class UstarUnicodeTest(unittest.TestCase):
1195 # All *UnicodeTests FIXME
1196
1197 format = tarfile.USTAR_FORMAT
1198
1199 def test_iso8859_1_filename(self):
1200 self._test_unicode_filename("iso8859-1")
1201
1202 def test_utf7_filename(self):
1203 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001204
1205 def test_utf8_filename(self):
1206 self._test_unicode_filename("utf8")
1207
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001208 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001209 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1210 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001211 tar.addfile(tarfile.TarInfo(name))
1212 tar.close()
1213
1214 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001215 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001216 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001217 tar.close()
1218
1219 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001220 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1221 tarinfo = tarfile.TarInfo()
1222
1223 tarinfo.name = "äöü"
1224 if self.format == tarfile.PAX_FORMAT:
1225 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1226 else:
1227 tar.addfile(tarinfo)
1228
1229 tarinfo.name = u"äöü"
1230 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1231
1232 tarinfo.name = "foo"
1233 tarinfo.uname = u"äöü"
1234 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1235
1236 def test_unicode_argument(self):
1237 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1238 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001239 self.assertTrue(type(t.name) is str)
1240 self.assertTrue(type(t.linkname) is str)
1241 self.assertTrue(type(t.uname) is str)
1242 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001243 tar.close()
1244
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001245 def test_uname_unicode(self):
1246 for name in (u"äöü", "äöü"):
1247 t = tarfile.TarInfo("foo")
1248 t.uname = name
1249 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001250
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001251 fobj = StringIO.StringIO()
1252 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1253 tar.addfile(t)
1254 tar.close()
1255 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001256
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001257 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1258 t = tar.getmember("foo")
1259 self.assertEqual(t.uname, "äöü")
1260 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001261
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001262
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001263class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001264
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001265 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001266
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001267
1268class PaxUnicodeTest(UstarUnicodeTest):
1269
1270 format = tarfile.PAX_FORMAT
1271
1272 def _create_unicode_name(self, name):
1273 tar = tarfile.open(tmpname, "w", format=self.format)
1274 t = tarfile.TarInfo()
1275 t.pax_headers["path"] = name
1276 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001277 tar.close()
1278
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001279 def test_error_handlers(self):
1280 # Test if the unicode error handlers work correctly for characters
1281 # that cannot be expressed in a given encoding.
1282 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001283
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001284 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1285 ("replace", "???"), ("ignore", "")):
1286 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1287 errors=handler)
1288 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001289
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001290 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1291 encoding="ascii", errors="strict")
1292
1293 def test_error_handler_utf8(self):
1294 # Create a pathname that has one component representable using
1295 # iso8859-1 and the other only in iso8859-15.
1296 self._create_unicode_name(u"äöü/¤")
1297
1298 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1299 errors="utf-8")
1300 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001301
Georg Brandlded1c4d2006-12-20 11:55:16 +00001302
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001303class AppendTest(unittest.TestCase):
1304 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001305
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001306 def setUp(self):
1307 self.tarname = tmpname
1308 if os.path.exists(self.tarname):
1309 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001310
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001311 def _add_testfile(self, fileobj=None):
1312 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1313 tar.addfile(tarfile.TarInfo("bar"))
1314 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001315
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001316 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001317 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001318 t = src.getmember("ustar/regtype")
1319 t.name = "foo"
1320 f = src.extractfile(t)
1321 tar = tarfile.open(self.tarname, mode)
1322 tar.addfile(t, f)
1323 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001324
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001325 def _test(self, names=["bar"], fileobj=None):
1326 tar = tarfile.open(self.tarname, fileobj=fileobj)
1327 self.assertEqual(tar.getnames(), names)
1328
1329 def test_non_existing(self):
1330 self._add_testfile()
1331 self._test()
1332
1333 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001334 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001335 self._add_testfile()
1336 self._test()
1337
1338 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001339 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001340 self._add_testfile(fobj)
1341 fobj.seek(0)
1342 self._test(fileobj=fobj)
1343
1344 def test_fileobj(self):
1345 self._create_testtar()
1346 data = open(self.tarname).read()
1347 fobj = StringIO.StringIO(data)
1348 self._add_testfile(fobj)
1349 fobj.seek(0)
1350 self._test(names=["foo", "bar"], fileobj=fobj)
1351
1352 def test_existing(self):
1353 self._create_testtar()
1354 self._add_testfile()
1355 self._test(names=["foo", "bar"])
1356
1357 def test_append_gz(self):
1358 if gzip is None:
1359 return
1360 self._create_testtar("w:gz")
1361 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1362
1363 def test_append_bz2(self):
1364 if bz2 is None:
1365 return
1366 self._create_testtar("w:bz2")
1367 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1368
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001369 # Append mode is supposed to fail if the tarfile to append to
1370 # does not end with a zero block.
1371 def _test_error(self, data):
1372 open(self.tarname, "wb").write(data)
1373 self.assertRaises(tarfile.ReadError, self._add_testfile)
1374
1375 def test_null(self):
1376 self._test_error("")
1377
1378 def test_incomplete(self):
1379 self._test_error("\0" * 13)
1380
1381 def test_premature_eof(self):
1382 data = tarfile.TarInfo("foo").tobuf()
1383 self._test_error(data)
1384
1385 def test_trailing_garbage(self):
1386 data = tarfile.TarInfo("foo").tobuf()
1387 self._test_error(data + "\0" * 13)
1388
1389 def test_invalid(self):
1390 self._test_error("a" * 512)
1391
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001392
1393class LimitsTest(unittest.TestCase):
1394
1395 def test_ustar_limits(self):
1396 # 100 char name
1397 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001398 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001399
1400 # 101 char name that cannot be stored
1401 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001402 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001403
1404 # 256 char name with a slash at pos 156
1405 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001406 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001407
1408 # 256 char name that cannot be stored
1409 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001410 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001411
1412 # 512 char name
1413 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001414 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001415
1416 # 512 char linkname
1417 tarinfo = tarfile.TarInfo("longlink")
1418 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001419 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001420
1421 # uid > 8 digits
1422 tarinfo = tarfile.TarInfo("name")
1423 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001424 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001425
1426 def test_gnu_limits(self):
1427 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001428 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001429
1430 tarinfo = tarfile.TarInfo("longlink")
1431 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001432 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001433
1434 # uid >= 256 ** 7
1435 tarinfo = tarfile.TarInfo("name")
1436 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001437 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001438
1439 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001440 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001441 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001442
1443 tarinfo = tarfile.TarInfo("longlink")
1444 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001445 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001446
1447 tarinfo = tarfile.TarInfo("name")
1448 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001449 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001450
1451
Lars Gustäbel64581042010-03-03 11:55:48 +00001452class ContextManagerTest(unittest.TestCase):
1453
1454 def test_basic(self):
1455 with tarfile.open(tarname) as tar:
1456 self.assertFalse(tar.closed, "closed inside runtime context")
1457 self.assertTrue(tar.closed, "context manager failed")
1458
1459 def test_closed(self):
1460 # The __enter__() method is supposed to raise IOError
1461 # if the TarFile object is already closed.
1462 tar = tarfile.open(tarname)
1463 tar.close()
1464 with self.assertRaises(IOError):
1465 with tar:
1466 pass
1467
1468 def test_exception(self):
1469 # Test if the IOError exception is passed through properly.
1470 with self.assertRaises(Exception) as exc:
1471 with tarfile.open(tarname) as tar:
1472 raise IOError
1473 self.assertIsInstance(exc.exception, IOError,
1474 "wrong exception raised in context manager")
1475 self.assertTrue(tar.closed, "context manager failed")
1476
1477 def test_no_eof(self):
1478 # __exit__() must not write end-of-archive blocks if an
1479 # exception was raised.
1480 try:
1481 with tarfile.open(tmpname, "w") as tar:
1482 raise Exception
1483 except:
1484 pass
1485 self.assertEqual(os.path.getsize(tmpname), 0,
1486 "context manager wrote an end-of-archive block")
1487 self.assertTrue(tar.closed, "context manager failed")
1488
1489 def test_eof(self):
1490 # __exit__() must write end-of-archive blocks, i.e. call
1491 # TarFile.close() if there was no error.
1492 with tarfile.open(tmpname, "w"):
1493 pass
1494 self.assertNotEqual(os.path.getsize(tmpname), 0,
1495 "context manager wrote no end-of-archive block")
1496
1497 def test_fileobj(self):
1498 # Test that __exit__() did not close the external file
1499 # object.
1500 fobj = open(tmpname, "wb")
1501 try:
1502 with tarfile.open(fileobj=fobj, mode="w") as tar:
1503 raise Exception
1504 except:
1505 pass
1506 self.assertFalse(fobj.closed, "external file object was closed")
1507 self.assertTrue(tar.closed, "context manager failed")
1508 fobj.close()
1509
1510
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001511class LinkEmulationTest(ReadTest):
1512
1513 # Test for issue #8741 regression. On platforms that do not support
1514 # symbolic or hard links tarfile tries to extract these types of members as
1515 # the regular files they point to.
1516 def _test_link_extraction(self, name):
1517 self.tar.extract(name, TEMPDIR)
1518 data = open(os.path.join(TEMPDIR, name), "rb").read()
1519 self.assertEqual(md5sum(data), md5_regtype)
1520
1521 def test_hardlink_extraction1(self):
1522 self._test_link_extraction("ustar/lnktype")
1523
1524 def test_hardlink_extraction2(self):
1525 self._test_link_extraction("./ustar/linktest2/lnktype")
1526
1527 def test_symlink_extraction1(self):
1528 self._test_link_extraction("ustar/symtype")
1529
1530 def test_symlink_extraction2(self):
1531 self._test_link_extraction("./ustar/linktest2/symtype")
1532
1533
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001534class GzipMiscReadTest(MiscReadTest):
1535 tarname = gzipname
1536 mode = "r:gz"
1537class GzipUstarReadTest(UstarReadTest):
1538 tarname = gzipname
1539 mode = "r:gz"
1540class GzipStreamReadTest(StreamReadTest):
1541 tarname = gzipname
1542 mode = "r|gz"
1543class GzipWriteTest(WriteTest):
1544 mode = "w:gz"
1545class GzipStreamWriteTest(StreamWriteTest):
1546 mode = "w|gz"
1547
1548
1549class Bz2MiscReadTest(MiscReadTest):
1550 tarname = bz2name
1551 mode = "r:bz2"
1552class Bz2UstarReadTest(UstarReadTest):
1553 tarname = bz2name
1554 mode = "r:bz2"
1555class Bz2StreamReadTest(StreamReadTest):
1556 tarname = bz2name
1557 mode = "r|bz2"
1558class Bz2WriteTest(WriteTest):
1559 mode = "w:bz2"
1560class Bz2StreamWriteTest(StreamWriteTest):
1561 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001562
Lars Gustäbel2020a592009-03-22 20:09:33 +00001563class Bz2PartialReadTest(unittest.TestCase):
1564 # Issue5068: The _BZ2Proxy.read() method loops forever
1565 # on an empty or partial bzipped file.
1566
1567 def _test_partial_input(self, mode):
1568 class MyStringIO(StringIO.StringIO):
1569 hit_eof = False
1570 def read(self, n):
1571 if self.hit_eof:
1572 raise AssertionError("infinite loop detected in tarfile.open()")
1573 self.hit_eof = self.pos == self.len
1574 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001575 def seek(self, *args):
1576 self.hit_eof = False
1577 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001578
1579 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1580 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001581 try:
1582 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1583 except tarfile.ReadError:
1584 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001585
1586 def test_partial_input(self):
1587 self._test_partial_input("r")
1588
1589 def test_partial_input_bz2(self):
1590 self._test_partial_input("r:bz2")
1591
1592
Neal Norwitz996acf12003-02-17 14:51:41 +00001593def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001594 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001595
Walter Dörwald21d3a322003-05-01 17:45:56 +00001596 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001597 UstarReadTest,
1598 MiscReadTest,
1599 StreamReadTest,
1600 DetectReadTest,
1601 MemberReadTest,
1602 GNUReadTest,
1603 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001604 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001605 StreamWriteTest,
1606 GNUWriteTest,
1607 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001608 UstarUnicodeTest,
1609 GNUUnicodeTest,
1610 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001611 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001612 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001613 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001614 ]
1615
Neal Norwitza4f651a2004-07-20 22:07:44 +00001616 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001617 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001618 else:
1619 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001620
1621 fobj = open(tarname, "rb")
1622 data = fobj.read()
1623 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001624
Walter Dörwald21d3a322003-05-01 17:45:56 +00001625 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001626 # Create testtar.tar.gz and add gzip-specific tests.
1627 tar = gzip.open(gzipname, "wb")
1628 tar.write(data)
1629 tar.close()
1630
1631 tests += [
1632 GzipMiscReadTest,
1633 GzipUstarReadTest,
1634 GzipStreamReadTest,
1635 GzipWriteTest,
1636 GzipStreamWriteTest,
1637 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001638
1639 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001640 # Create testtar.tar.bz2 and add bz2-specific tests.
1641 tar = bz2.BZ2File(bz2name, "wb")
1642 tar.write(data)
1643 tar.close()
1644
1645 tests += [
1646 Bz2MiscReadTest,
1647 Bz2UstarReadTest,
1648 Bz2StreamReadTest,
1649 Bz2WriteTest,
1650 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001651 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001652 ]
1653
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001654 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001655 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001656 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001657 if os.path.exists(TEMPDIR):
1658 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001659
Neal Norwitz996acf12003-02-17 14:51:41 +00001660if __name__ == "__main__":
1661 test_main()