blob: a3685ea273a46fb9507ae6c0dd20205b2fef8d86 [file] [log] [blame]
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001# -*- coding: iso-8859-15 -*-
Lars Gustäbelc64e4022007-03-13 10:47:19 +00002
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00003import sys
4import os
5import shutil
Georg Brandl38c6a222006-05-10 16:26:03 +00006import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00007from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00008import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00009
10import unittest
11import tarfile
12
13from test import test_support
14
15# Check for our compression modules.
16try:
17 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000018 gzip.GzipFile
19except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000020 gzip = None
21try:
22 import bz2
23except ImportError:
24 bz2 = None
25
Lars Gustäbelc64e4022007-03-13 10:47:19 +000026def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000027 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000028
Antoine Pitrou310c9fe2009-11-11 20:55:07 +000029TEMPDIR = os.path.abspath(test_support.TESTFN)
30tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000031gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
32bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
33tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000034
Lars Gustäbelc64e4022007-03-13 10:47:19 +000035md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
36md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000037
38
Lars Gustäbelc64e4022007-03-13 10:47:19 +000039class ReadTest(unittest.TestCase):
40
41 tarname = tarname
42 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000043
44 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000045 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000046
47 def tearDown(self):
48 self.tar.close()
49
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000050
Lars Gustäbelc64e4022007-03-13 10:47:19 +000051class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000052
Lars Gustäbelc64e4022007-03-13 10:47:19 +000053 def test_fileobj_regular_file(self):
54 tarinfo = self.tar.getmember("ustar/regtype")
55 fobj = self.tar.extractfile(tarinfo)
56 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000057 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000058 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000059
Lars Gustäbelc64e4022007-03-13 10:47:19 +000060 def test_fileobj_readlines(self):
61 self.tar.extract("ustar/regtype", TEMPDIR)
62 tarinfo = self.tar.getmember("ustar/regtype")
63 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
64 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000065
Lars Gustäbelc64e4022007-03-13 10:47:19 +000066 lines1 = fobj1.readlines()
67 lines2 = fobj2.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000068 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000069 "fileobj.readlines() failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000070 self.assertTrue(len(lines2) == 114,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000071 "fileobj.readlines() failed")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +000072 self.assertTrue(lines2[83] ==
Lars Gustäbelc64e4022007-03-13 10:47:19 +000073 "I will gladly admit that Python is not the fastest running scripting language.\n",
74 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000075
Lars Gustäbelc64e4022007-03-13 10:47:19 +000076 def test_fileobj_iter(self):
77 self.tar.extract("ustar/regtype", TEMPDIR)
78 tarinfo = self.tar.getmember("ustar/regtype")
79 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
80 fobj2 = self.tar.extractfile(tarinfo)
81 lines1 = fobj1.readlines()
82 lines2 = [line for line in fobj2]
Benjamin Peterson5c8da862009-06-30 22:57:08 +000083 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000084 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000085
Lars Gustäbelc64e4022007-03-13 10:47:19 +000086 def test_fileobj_seek(self):
87 self.tar.extract("ustar/regtype", TEMPDIR)
88 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
89 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000090 fobj.close()
91
Lars Gustäbelc64e4022007-03-13 10:47:19 +000092 tarinfo = self.tar.getmember("ustar/regtype")
93 fobj = self.tar.extractfile(tarinfo)
94
95 text = fobj.read()
96 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000097 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000098 "seek() to file's start failed")
99 fobj.seek(2048, 0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000100 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000101 "seek() to absolute position failed")
102 fobj.seek(-1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000103 self.assertTrue(1024 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000104 "seek() to negative relative position failed")
105 fobj.seek(1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000106 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000107 "seek() to positive relative position failed")
108 s = fobj.read(10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000109 self.assertTrue(s == data[2048:2058],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000110 "read() after seek failed")
111 fobj.seek(0, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000112 self.assertTrue(tarinfo.size == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000113 "seek() to file's end failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000114 self.assertTrue(fobj.read() == "",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000115 "read() at file's end did not return empty string")
116 fobj.seek(-tarinfo.size, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000117 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000118 "relative seek() to file's start failed")
119 fobj.seek(512)
120 s1 = fobj.readlines()
121 fobj.seek(512)
122 s2 = fobj.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000123 self.assertTrue(s1 == s2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000124 "readlines() after seek failed")
125 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000126 self.assertTrue(len(fobj.readline()) == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000127 "tell() after readline() failed")
128 fobj.seek(512)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000129 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000130 "tell() after seek() and readline() failed")
131 fobj.seek(0)
132 line = fobj.readline()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000133 self.assertTrue(fobj.read() == data[len(line):],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000134 "read() after readline() failed")
135 fobj.close()
136
Lars Gustäbel4da7d412010-06-03 12:34:14 +0000137 # Test if symbolic and hard links are resolved by extractfile(). The
138 # test link members each point to a regular member whose data is
139 # supposed to be exported.
140 def _test_fileobj_link(self, lnktype, regtype):
141 a = self.tar.extractfile(lnktype)
142 b = self.tar.extractfile(regtype)
143 self.assertEqual(a.name, b.name)
144
145 def test_fileobj_link1(self):
146 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
147
148 def test_fileobj_link2(self):
149 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
150
151 def test_fileobj_symlink1(self):
152 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
153
154 def test_fileobj_symlink2(self):
155 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
156
Lars Gustäbel231d4742012-04-24 22:42:08 +0200157 def test_issue14160(self):
158 self._test_fileobj_link("symtype2", "ustar/regtype")
159
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000160
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000161class CommonReadTest(ReadTest):
162
163 def test_empty_tarfile(self):
164 # Test for issue6123: Allow opening empty archives.
165 # This test checks if tarfile.open() is able to open an empty tar
166 # archive successfully. Note that an empty tar archive is not the
167 # same as an empty file!
168 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
169 try:
170 tar = tarfile.open(tmpname, self.mode)
171 tar.getnames()
172 except tarfile.ReadError:
173 self.fail("tarfile.open() failed on empty archive")
174 self.assertListEqual(tar.getmembers(), [])
175
176 def test_null_tarfile(self):
177 # Test for issue6123: Allow opening empty archives.
178 # This test guarantees that tarfile.open() does not treat an empty
179 # file as an empty tar archive.
180 open(tmpname, "wb").close()
181 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
182 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
183
184 def test_ignore_zeros(self):
185 # Test TarFile's ignore_zeros option.
186 if self.mode.endswith(":gz"):
187 _open = gzip.GzipFile
188 elif self.mode.endswith(":bz2"):
189 _open = bz2.BZ2File
190 else:
191 _open = open
192
193 for char in ('\0', 'a'):
194 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
195 # are ignored correctly.
196 fobj = _open(tmpname, "wb")
197 fobj.write(char * 1024)
198 fobj.write(tarfile.TarInfo("foo").tobuf())
199 fobj.close()
200
201 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
202 self.assertListEqual(tar.getnames(), ["foo"],
203 "ignore_zeros=True should have skipped the %r-blocks" % char)
204 tar.close()
205
206
207class MiscReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000208
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000209 def test_no_name_argument(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000210 fobj = open(self.tarname, "rb")
211 tar = tarfile.open(fileobj=fobj, mode=self.mode)
212 self.assertEqual(tar.name, os.path.abspath(fobj.name))
213
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000214 def test_no_name_attribute(self):
215 data = open(self.tarname, "rb").read()
216 fobj = StringIO.StringIO(data)
217 self.assertRaises(AttributeError, getattr, fobj, "name")
218 tar = tarfile.open(fileobj=fobj, mode=self.mode)
219 self.assertEqual(tar.name, None)
220
221 def test_empty_name_attribute(self):
222 data = open(self.tarname, "rb").read()
223 fobj = StringIO.StringIO(data)
224 fobj.name = ""
225 tar = tarfile.open(fileobj=fobj, mode=self.mode)
226 self.assertEqual(tar.name, None)
227
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000228 def test_fileobj_with_offset(self):
229 # Skip the first member and store values from the second member
230 # of the testtar.
231 tar = tarfile.open(self.tarname, mode=self.mode)
232 tar.next()
233 t = tar.next()
234 name = t.name
235 offset = t.offset
236 data = tar.extractfile(t).read()
237 tar.close()
238
239 # Open the testtar and seek to the offset of the second member.
240 if self.mode.endswith(":gz"):
241 _open = gzip.GzipFile
242 elif self.mode.endswith(":bz2"):
243 _open = bz2.BZ2File
244 else:
245 _open = open
246 fobj = _open(self.tarname, "rb")
247 fobj.seek(offset)
248
249 # Test if the tarfile starts with the second member.
250 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
251 t = tar.next()
252 self.assertEqual(t.name, name)
253 # Read to the end of fileobj and test if seeking back to the
254 # beginning works.
255 tar.getmembers()
256 self.assertEqual(tar.extractfile(t).read(), data,
257 "seek back did not work")
258 tar.close()
259
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000260 def test_fail_comp(self):
261 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
262 if self.mode == "r:":
263 return
264 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
265 fobj = open(tarname, "rb")
266 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
267
268 def test_v7_dirtype(self):
269 # Test old style dirtype member (bug #1336623):
270 # Old V7 tars create directory members using an AREGTYPE
271 # header with a "/" appended to the filename field.
272 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000273 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000274 "v7 dirtype failed")
275
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000276 def test_xstar_type(self):
277 # The xstar format stores extra atime and ctime fields inside the
278 # space reserved for the prefix field. The prefix field must be
279 # ignored in this case, otherwise it will mess up the name.
280 try:
281 self.tar.getmember("misc/regtype-xstar")
282 except KeyError:
283 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
284
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000285 def test_check_members(self):
286 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000287 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000288 "wrong mtime for %s" % tarinfo.name)
289 if not tarinfo.name.startswith("ustar/"):
290 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000291 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000292 "wrong uname for %s" % tarinfo.name)
293
294 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000295 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000296 "could not find all members")
297
298 def test_extract_hardlink(self):
299 # Test hardlink extraction (e.g. bug #857297).
Lars Gustäbela36cde42007-03-13 15:47:07 +0000300 tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000301
302 tar.extract("ustar/regtype", TEMPDIR)
Neal Norwitzf3396542005-10-28 05:52:22 +0000303 try:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000304 tar.extract("ustar/lnktype", TEMPDIR)
305 except EnvironmentError, e:
306 if e.errno == errno.ENOENT:
307 self.fail("hardlink not extracted properly")
Neal Norwitzf3396542005-10-28 05:52:22 +0000308
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000309 data = open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb").read()
310 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000311
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000312 try:
313 tar.extract("ustar/symtype", TEMPDIR)
314 except EnvironmentError, e:
315 if e.errno == errno.ENOENT:
316 self.fail("symlink not extracted properly")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000317
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000318 data = open(os.path.join(TEMPDIR, "ustar/symtype"), "rb").read()
319 self.assertEqual(md5sum(data), md5_regtype)
320
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000321 def test_extractall(self):
322 # Test if extractall() correctly restores directory permissions
323 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000324 tar = tarfile.open(tarname, encoding="iso8859-1")
325 directories = [t for t in tar if t.isdir()]
326 tar.extractall(TEMPDIR, directories)
327 for tarinfo in directories:
328 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000329 if sys.platform != "win32":
330 # Win32 has no support for fine grained permissions.
331 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000332 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
333 tar.close()
334
Lars Gustäbel12adc652009-11-23 15:46:19 +0000335 def test_init_close_fobj(self):
336 # Issue #7341: Close the internal file object in the TarFile
337 # constructor in case of an error. For the test we rely on
338 # the fact that opening an empty file raises a ReadError.
339 empty = os.path.join(TEMPDIR, "empty")
340 open(empty, "wb").write("")
341
342 try:
343 tar = object.__new__(tarfile.TarFile)
344 try:
345 tar.__init__(empty)
346 except tarfile.ReadError:
347 self.assertTrue(tar.fileobj.closed)
348 else:
349 self.fail("ReadError not raised")
350 finally:
351 os.remove(empty)
352
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000353
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000354class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000355
356 mode="r|"
357
358 def test_fileobj_regular_file(self):
359 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
360 fobj = self.tar.extractfile(tarinfo)
361 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000362 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000363 "regular file extraction failed")
364
365 def test_provoke_stream_error(self):
366 tarinfos = self.tar.getmembers()
367 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000368 self.assertRaises(tarfile.StreamError, f.read)
369
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000370 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000371 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000372 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000373
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000374 while True:
375 t1 = tar1.next()
376 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000377 if t1 is None:
378 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000379 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000380
381 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000382 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000383 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000384
385 v1 = tar1.extractfile(t1)
386 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000387 if v1 is None:
388 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000389 self.assertTrue(v2 is not None, "stream.extractfile() failed")
390 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000391
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000392 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000393
Georg Brandla32e0a02006-10-24 16:54:16 +0000394
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000395class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000396
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000397 def _testfunc_file(self, name, mode):
398 try:
399 tarfile.open(name, mode)
400 except tarfile.ReadError:
401 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000402
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000403 def _testfunc_fileobj(self, name, mode):
404 try:
405 tarfile.open(name, mode, fileobj=open(name, "rb"))
406 except tarfile.ReadError:
407 self.fail()
408
409 def _test_modes(self, testfunc):
410 testfunc(tarname, "r")
411 testfunc(tarname, "r:")
412 testfunc(tarname, "r:*")
413 testfunc(tarname, "r|")
414 testfunc(tarname, "r|*")
415
416 if gzip:
417 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
418 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
419 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
420 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
421
422 testfunc(gzipname, "r")
423 testfunc(gzipname, "r:*")
424 testfunc(gzipname, "r:gz")
425 testfunc(gzipname, "r|*")
426 testfunc(gzipname, "r|gz")
427
428 if bz2:
429 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
430 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
431 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
432 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
433
434 testfunc(bz2name, "r")
435 testfunc(bz2name, "r:*")
436 testfunc(bz2name, "r:bz2")
437 testfunc(bz2name, "r|*")
438 testfunc(bz2name, "r|bz2")
439
440 def test_detect_file(self):
441 self._test_modes(self._testfunc_file)
442
443 def test_detect_fileobj(self):
444 self._test_modes(self._testfunc_fileobj)
445
Lars Gustäbel9a388632011-12-06 13:07:09 +0100446 def test_detect_stream_bz2(self):
447 # Originally, tarfile's stream detection looked for the string
448 # "BZh91" at the start of the file. This is incorrect because
449 # the '9' represents the blocksize (900kB). If the file was
450 # compressed using another blocksize autodetection fails.
451 if not bz2:
452 return
453
454 with open(tarname, "rb") as fobj:
455 data = fobj.read()
456
457 # Compress with blocksize 100kB, the file starts with "BZh11".
458 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
459 fobj.write(data)
460
461 self._testfunc_file(tmpname, "r|*")
462
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000463
464class MemberReadTest(ReadTest):
465
466 def _test_member(self, tarinfo, chksum=None, **kwargs):
467 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000468 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000469 "wrong md5sum for %s" % tarinfo.name)
470
471 kwargs["mtime"] = 07606136617
472 kwargs["uid"] = 1000
473 kwargs["gid"] = 100
474 if "old-v7" not in tarinfo.name:
475 # V7 tar can't handle alphabetic owners.
476 kwargs["uname"] = "tarfile"
477 kwargs["gname"] = "tarfile"
478 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000479 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000480 "wrong value in %s field of %s" % (k, tarinfo.name))
481
482 def test_find_regtype(self):
483 tarinfo = self.tar.getmember("ustar/regtype")
484 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
485
486 def test_find_conttype(self):
487 tarinfo = self.tar.getmember("ustar/conttype")
488 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
489
490 def test_find_dirtype(self):
491 tarinfo = self.tar.getmember("ustar/dirtype")
492 self._test_member(tarinfo, size=0)
493
494 def test_find_dirtype_with_size(self):
495 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
496 self._test_member(tarinfo, size=255)
497
498 def test_find_lnktype(self):
499 tarinfo = self.tar.getmember("ustar/lnktype")
500 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
501
502 def test_find_symtype(self):
503 tarinfo = self.tar.getmember("ustar/symtype")
504 self._test_member(tarinfo, size=0, linkname="regtype")
505
506 def test_find_blktype(self):
507 tarinfo = self.tar.getmember("ustar/blktype")
508 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
509
510 def test_find_chrtype(self):
511 tarinfo = self.tar.getmember("ustar/chrtype")
512 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
513
514 def test_find_fifotype(self):
515 tarinfo = self.tar.getmember("ustar/fifotype")
516 self._test_member(tarinfo, size=0)
517
518 def test_find_sparse(self):
519 tarinfo = self.tar.getmember("ustar/sparse")
520 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
521
522 def test_find_umlauts(self):
523 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
524 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
525
526 def test_find_ustar_longname(self):
527 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000528 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000529
530 def test_find_regtype_oldv7(self):
531 tarinfo = self.tar.getmember("misc/regtype-old-v7")
532 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
533
534 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000535 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000536 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
537 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
538
539
540class LongnameTest(ReadTest):
541
542 def test_read_longname(self):
543 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000544 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000545 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000546 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000547 except KeyError:
548 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000549 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000550
551 def test_read_longlink(self):
552 longname = self.subdir + "/" + "123/" * 125 + "longname"
553 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
554 try:
555 tarinfo = self.tar.getmember(longlink)
556 except KeyError:
557 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000558 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000559
560 def test_truncated_longname(self):
561 longname = self.subdir + "/" + "123/" * 125 + "longname"
562 tarinfo = self.tar.getmember(longname)
563 offset = tarinfo.offset
564 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000565 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000566 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
567
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000568 def test_header_offset(self):
569 # Test if the start offset of the TarInfo object includes
570 # the preceding extended header.
571 longname = self.subdir + "/" + "123/" * 125 + "longname"
572 offset = self.tar.getmember(longname).offset
573 fobj = open(tarname)
574 fobj.seek(offset)
575 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
576 self.assertEqual(tarinfo.type, self.longnametype)
577
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000578
579class GNUReadTest(LongnameTest):
580
581 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000582 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000583
584 def test_sparse_file(self):
585 tarinfo1 = self.tar.getmember("ustar/sparse")
586 fobj1 = self.tar.extractfile(tarinfo1)
587 tarinfo2 = self.tar.getmember("gnu/sparse")
588 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000589 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000590 "sparse file extraction failed")
591
592
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000593class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000594
595 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000596 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000597
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000598 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000599 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000600
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000601 tarinfo = tar.getmember("pax/regtype1")
602 self.assertEqual(tarinfo.uname, "foo")
603 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000604 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000605
606 tarinfo = tar.getmember("pax/regtype2")
607 self.assertEqual(tarinfo.uname, "")
608 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000609 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000610
611 tarinfo = tar.getmember("pax/regtype3")
612 self.assertEqual(tarinfo.uname, "tarfile")
613 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000614 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
615
616 def test_pax_number_fields(self):
617 # All following number fields are read from the pax header.
618 tar = tarfile.open(tarname, encoding="iso8859-1")
619 tarinfo = tar.getmember("pax/regtype4")
620 self.assertEqual(tarinfo.size, 7011)
621 self.assertEqual(tarinfo.uid, 123)
622 self.assertEqual(tarinfo.gid, 123)
623 self.assertEqual(tarinfo.mtime, 1041808783.0)
624 self.assertEqual(type(tarinfo.mtime), float)
625 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
626 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000627
628
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000629class WriteTestBase(unittest.TestCase):
630 # Put all write tests in here that are supposed to be tested
631 # in all possible mode combinations.
632
633 def test_fileobj_no_close(self):
634 fobj = StringIO.StringIO()
635 tar = tarfile.open(fileobj=fobj, mode=self.mode)
636 tar.addfile(tarfile.TarInfo("foo"))
637 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000638 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000639
640
641class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000642
643 mode = "w:"
644
645 def test_100_char_name(self):
646 # The name field in a tar header stores strings of at most 100 chars.
647 # If a string is shorter than 100 chars it has to be padded with '\0',
648 # which implies that a string of exactly 100 chars is stored without
649 # a trailing '\0'.
650 name = "0123456789" * 10
651 tar = tarfile.open(tmpname, self.mode)
652 t = tarfile.TarInfo(name)
653 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000654 tar.close()
655
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000656 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000657 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000658 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000659 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000660
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000661 def test_tar_size(self):
662 # Test for bug #1013882.
663 tar = tarfile.open(tmpname, self.mode)
664 path = os.path.join(TEMPDIR, "file")
665 fobj = open(path, "wb")
666 fobj.write("aaa")
667 fobj.close()
668 tar.add(path)
669 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000670 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000671 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000672
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000673 # The test_*_size tests test for bug #1167128.
674 def test_file_size(self):
675 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000676
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000677 path = os.path.join(TEMPDIR, "file")
678 fobj = open(path, "wb")
679 fobj.close()
680 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000681 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000682
683 fobj = open(path, "wb")
684 fobj.write("aaa")
685 fobj.close()
686 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000687 self.assertEqual(tarinfo.size, 3)
688
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000689 tar.close()
690
691 def test_directory_size(self):
692 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000693 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000694 try:
695 tar = tarfile.open(tmpname, self.mode)
696 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000697 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000698 finally:
699 os.rmdir(path)
700
701 def test_link_size(self):
702 if hasattr(os, "link"):
703 link = os.path.join(TEMPDIR, "link")
704 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000705 fobj = open(target, "wb")
706 fobj.write("aaa")
707 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000708 os.link(target, link)
709 try:
710 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000711 # Record the link target in the inodes list.
712 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000713 tarinfo = tar.gettarinfo(link)
714 self.assertEqual(tarinfo.size, 0)
715 finally:
716 os.remove(target)
717 os.remove(link)
718
719 def test_symlink_size(self):
720 if hasattr(os, "symlink"):
721 path = os.path.join(TEMPDIR, "symlink")
722 os.symlink("link_target", path)
723 try:
724 tar = tarfile.open(tmpname, self.mode)
725 tarinfo = tar.gettarinfo(path)
726 self.assertEqual(tarinfo.size, 0)
727 finally:
728 os.remove(path)
729
730 def test_add_self(self):
731 # Test for #1257255.
732 dstname = os.path.abspath(tmpname)
733
734 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000735 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000736
737 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000738 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000739
740 cwd = os.getcwd()
741 os.chdir(TEMPDIR)
742 tar.add(dstname)
743 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000744 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000745
Lars Gustäbel104490e2007-06-18 11:42:11 +0000746 def test_exclude(self):
747 tempdir = os.path.join(TEMPDIR, "exclude")
748 os.mkdir(tempdir)
749 try:
750 for name in ("foo", "bar", "baz"):
751 name = os.path.join(tempdir, name)
752 open(name, "wb").close()
753
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000754 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000755
756 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000757 with test_support.check_warnings(("use the filter argument",
758 DeprecationWarning)):
759 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000760 tar.close()
761
762 tar = tarfile.open(tmpname, "r")
763 self.assertEqual(len(tar.getmembers()), 1)
764 self.assertEqual(tar.getnames()[0], "empty_dir")
765 finally:
766 shutil.rmtree(tempdir)
767
Lars Gustäbel21121e62009-09-12 10:28:15 +0000768 def test_filter(self):
769 tempdir = os.path.join(TEMPDIR, "filter")
770 os.mkdir(tempdir)
771 try:
772 for name in ("foo", "bar", "baz"):
773 name = os.path.join(tempdir, name)
774 open(name, "wb").close()
775
776 def filter(tarinfo):
777 if os.path.basename(tarinfo.name) == "bar":
778 return
779 tarinfo.uid = 123
780 tarinfo.uname = "foo"
781 return tarinfo
782
783 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
784 tar.add(tempdir, arcname="empty_dir", filter=filter)
785 tar.close()
786
787 tar = tarfile.open(tmpname, "r")
788 for tarinfo in tar:
789 self.assertEqual(tarinfo.uid, 123)
790 self.assertEqual(tarinfo.uname, "foo")
791 self.assertEqual(len(tar.getmembers()), 3)
792 tar.close()
793 finally:
794 shutil.rmtree(tempdir)
795
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000796 # Guarantee that stored pathnames are not modified. Don't
797 # remove ./ or ../ or double slashes. Still make absolute
798 # pathnames relative.
799 # For details see bug #6054.
800 def _test_pathname(self, path, cmp_path=None, dir=False):
801 # Create a tarfile with an empty member named path
802 # and compare the stored name with the original.
803 foo = os.path.join(TEMPDIR, "foo")
804 if not dir:
805 open(foo, "w").close()
806 else:
807 os.mkdir(foo)
808
809 tar = tarfile.open(tmpname, self.mode)
810 tar.add(foo, arcname=path)
811 tar.close()
812
813 tar = tarfile.open(tmpname, "r")
814 t = tar.next()
815 tar.close()
816
817 if not dir:
818 os.remove(foo)
819 else:
820 os.rmdir(foo)
821
822 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
823
824 def test_pathnames(self):
825 self._test_pathname("foo")
826 self._test_pathname(os.path.join("foo", ".", "bar"))
827 self._test_pathname(os.path.join("foo", "..", "bar"))
828 self._test_pathname(os.path.join(".", "foo"))
829 self._test_pathname(os.path.join(".", "foo", "."))
830 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
831 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
832 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
833 self._test_pathname(os.path.join("..", "foo"))
834 self._test_pathname(os.path.join("..", "foo", ".."))
835 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
836 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
837
838 self._test_pathname("foo" + os.sep + os.sep + "bar")
839 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
840
841 def test_abs_pathnames(self):
842 if sys.platform == "win32":
843 self._test_pathname("C:\\foo", "foo")
844 else:
845 self._test_pathname("/foo", "foo")
846 self._test_pathname("///foo", "foo")
847
848 def test_cwd(self):
849 # Test adding the current working directory.
850 cwd = os.getcwd()
851 os.chdir(TEMPDIR)
852 try:
853 open("foo", "w").close()
854
855 tar = tarfile.open(tmpname, self.mode)
856 tar.add(".")
857 tar.close()
858
859 tar = tarfile.open(tmpname, "r")
860 for t in tar:
861 self.assert_(t.name == "." or t.name.startswith("./"))
862 tar.close()
863 finally:
864 os.chdir(cwd)
865
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800866 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800867 def test_extractall_symlinks(self):
868 # Test if extractall works properly when tarfile contains symlinks
869 tempdir = os.path.join(TEMPDIR, "testsymlinks")
870 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
871 os.mkdir(tempdir)
872 try:
873 source_file = os.path.join(tempdir,'source')
874 target_file = os.path.join(tempdir,'symlink')
875 with open(source_file,'w') as f:
876 f.write('something\n')
877 os.symlink(source_file, target_file)
878 tar = tarfile.open(temparchive,'w')
879 tar.add(source_file, arcname=os.path.basename(source_file))
880 tar.add(target_file, arcname=os.path.basename(target_file))
881 tar.close()
882 # Let's extract it to the location which contains the symlink
883 tar = tarfile.open(temparchive,'r')
884 # this should not raise OSError: [Errno 17] File exists
885 try:
886 tar.extractall(path=tempdir)
887 except OSError:
888 self.fail("extractall failed with symlinked files")
889 finally:
890 tar.close()
891 finally:
892 os.unlink(temparchive)
893 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000894
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +0800895 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
896 def test_extractall_broken_symlinks(self):
897 # Test if extractall works properly when tarfile contains broken
898 # symlinks
899 tempdir = os.path.join(TEMPDIR, "testsymlinks")
900 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
901 os.mkdir(tempdir)
902 try:
903 source_file = os.path.join(tempdir,'source')
904 target_file = os.path.join(tempdir,'symlink')
905 with open(source_file,'w') as f:
906 f.write('something\n')
907 os.symlink(source_file, target_file)
908 tar = tarfile.open(temparchive,'w')
909 tar.add(target_file, arcname=os.path.basename(target_file))
910 tar.close()
911 # remove the real file
912 os.unlink(source_file)
913 # Let's extract it to the location which contains the symlink
914 tar = tarfile.open(temparchive,'r')
915 # this should not raise OSError: [Errno 17] File exists
916 try:
917 tar.extractall(path=tempdir)
918 except OSError:
919 self.fail("extractall failed with broken symlinked files")
920 finally:
921 tar.close()
922 finally:
923 os.unlink(temparchive)
924 shutil.rmtree(tempdir)
925
926 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
927 def test_extractall_hardlinks(self):
928 # Test if extractall works properly when tarfile contains symlinks
929 tempdir = os.path.join(TEMPDIR, "testsymlinks")
930 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
931 os.mkdir(tempdir)
932 try:
933 source_file = os.path.join(tempdir,'source')
934 target_file = os.path.join(tempdir,'symlink')
935 with open(source_file,'w') as f:
936 f.write('something\n')
937 os.link(source_file, target_file)
938 tar = tarfile.open(temparchive,'w')
939 tar.add(source_file, arcname=os.path.basename(source_file))
940 tar.add(target_file, arcname=os.path.basename(target_file))
941 tar.close()
942 # Let's extract it to the location which contains the symlink
943 tar = tarfile.open(temparchive,'r')
944 # this should not raise OSError: [Errno 17] File exists
945 try:
946 tar.extractall(path=tempdir)
947 except OSError:
948 self.fail("extractall failed with linked files")
949 finally:
950 tar.close()
951 finally:
952 os.unlink(temparchive)
953 shutil.rmtree(tempdir)
954
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000955class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000956
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000957 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +0000958
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000959 def test_stream_padding(self):
960 # Test for bug #1543303.
961 tar = tarfile.open(tmpname, self.mode)
962 tar.close()
963
964 if self.mode.endswith("gz"):
965 fobj = gzip.GzipFile(tmpname)
966 data = fobj.read()
967 fobj.close()
968 elif self.mode.endswith("bz2"):
969 dec = bz2.BZ2Decompressor()
970 data = open(tmpname, "rb").read()
971 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000972 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000973 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +0000974 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000975 fobj = open(tmpname, "rb")
976 data = fobj.read()
977 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +0000978
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000979 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +0000980 "incorrect zero padding")
981
Lars Gustäbel5c4c4612010-04-29 15:23:38 +0000982 def test_file_mode(self):
983 # Test for issue #8464: Create files with correct
984 # permissions.
985 if sys.platform == "win32" or not hasattr(os, "umask"):
986 return
987
988 if os.path.exists(tmpname):
989 os.remove(tmpname)
990
991 original_umask = os.umask(0022)
992 try:
993 tar = tarfile.open(tmpname, self.mode)
994 tar.close()
995 mode = os.stat(tmpname).st_mode & 0777
996 self.assertEqual(mode, 0644, "wrong file permissions")
997 finally:
998 os.umask(original_umask)
999
Lars Gustäbel7d4d0742011-12-21 19:27:50 +01001000 def test_issue13639(self):
1001 try:
1002 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1003 pass
1004 except UnicodeDecodeError:
1005 self.fail("_Stream failed to write unicode filename")
1006
Neal Norwitz8a519392006-08-21 17:59:46 +00001007
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001008class GNUWriteTest(unittest.TestCase):
1009 # This testcase checks for correct creation of GNU Longname
1010 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001011
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001012 def _length(self, s):
1013 blocks, remainder = divmod(len(s) + 1, 512)
1014 if remainder:
1015 blocks += 1
1016 return blocks * 512
1017
1018 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001019 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001020 count = 512
1021
1022 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001023 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001024 count += 512
1025 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001026 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001027 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001028 count += 512
1029 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001030 return count
1031
1032 def _test(self, name, link=None):
1033 tarinfo = tarfile.TarInfo(name)
1034 if link:
1035 tarinfo.linkname = link
1036 tarinfo.type = tarfile.LNKTYPE
1037
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001038 tar = tarfile.open(tmpname, "w")
1039 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001040 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001041
1042 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001043 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001044 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001045
Georg Brandl87fa5592006-12-06 22:21:18 +00001046 tar.close()
1047
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001048 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001049 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001050 self.assertIsNotNone(member,
1051 "unable to read longname member")
1052 self.assertEqual(tarinfo.name, member.name,
1053 "unable to read longname member")
1054 self.assertEqual(tarinfo.linkname, member.linkname,
1055 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001056
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001057 def test_longname_1023(self):
1058 self._test(("longnam/" * 127) + "longnam")
1059
1060 def test_longname_1024(self):
1061 self._test(("longnam/" * 127) + "longname")
1062
1063 def test_longname_1025(self):
1064 self._test(("longnam/" * 127) + "longname_")
1065
1066 def test_longlink_1023(self):
1067 self._test("name", ("longlnk/" * 127) + "longlnk")
1068
1069 def test_longlink_1024(self):
1070 self._test("name", ("longlnk/" * 127) + "longlink")
1071
1072 def test_longlink_1025(self):
1073 self._test("name", ("longlnk/" * 127) + "longlink_")
1074
1075 def test_longnamelink_1023(self):
1076 self._test(("longnam/" * 127) + "longnam",
1077 ("longlnk/" * 127) + "longlnk")
1078
1079 def test_longnamelink_1024(self):
1080 self._test(("longnam/" * 127) + "longname",
1081 ("longlnk/" * 127) + "longlink")
1082
1083 def test_longnamelink_1025(self):
1084 self._test(("longnam/" * 127) + "longname_",
1085 ("longlnk/" * 127) + "longlink_")
1086
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001087
1088class HardlinkTest(unittest.TestCase):
1089 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001090
1091 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001092 self.foo = os.path.join(TEMPDIR, "foo")
1093 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001094
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001095 fobj = open(self.foo, "wb")
1096 fobj.write("foo")
1097 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001098
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001099 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001100
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001101 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001102 self.tar.add(self.foo)
1103
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001104 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001105 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001106 os.remove(self.foo)
1107 os.remove(self.bar)
1108
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001109 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001110 # The same name will be added as a REGTYPE every
1111 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001112 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001113 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001114 "add file as regular failed")
1115
1116 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001117 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001118 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001119 "add file as hardlink failed")
1120
1121 def test_dereference_hardlink(self):
1122 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001123 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001124 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001125 "dereferencing hardlink failed")
1126
Neal Norwitza4f651a2004-07-20 22:07:44 +00001127
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001128class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001129
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001130 def _test(self, name, link=None):
1131 # See GNUWriteTest.
1132 tarinfo = tarfile.TarInfo(name)
1133 if link:
1134 tarinfo.linkname = link
1135 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001136
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001137 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1138 tar.addfile(tarinfo)
1139 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001140
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001141 tar = tarfile.open(tmpname)
1142 if link:
1143 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001144 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001145 else:
1146 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001147 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001148
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001149 def test_pax_global_header(self):
1150 pax_headers = {
1151 u"foo": u"bar",
1152 u"uid": u"0",
1153 u"mtime": u"1.23",
1154 u"test": u"äöü",
1155 u"äöü": u"test"}
1156
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001157 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001158 pax_headers=pax_headers)
1159 tar.addfile(tarfile.TarInfo("test"))
1160 tar.close()
1161
1162 # Test if the global header was written correctly.
1163 tar = tarfile.open(tmpname, encoding="iso8859-1")
1164 self.assertEqual(tar.pax_headers, pax_headers)
1165 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1166
1167 # Test if all the fields are unicode.
1168 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001169 self.assertTrue(type(key) is unicode)
1170 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001171 if key in tarfile.PAX_NUMBER_FIELDS:
1172 try:
1173 tarfile.PAX_NUMBER_FIELDS[key](val)
1174 except (TypeError, ValueError):
1175 self.fail("unable to convert pax header field")
1176
1177 def test_pax_extended_header(self):
1178 # The fields from the pax header have priority over the
1179 # TarInfo.
1180 pax_headers = {u"path": u"foo", u"uid": u"123"}
1181
1182 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1183 t = tarfile.TarInfo()
1184 t.name = u"äöü" # non-ASCII
1185 t.uid = 8**8 # too large
1186 t.pax_headers = pax_headers
1187 tar.addfile(t)
1188 tar.close()
1189
1190 tar = tarfile.open(tmpname, encoding="iso8859-1")
1191 t = tar.getmembers()[0]
1192 self.assertEqual(t.pax_headers, pax_headers)
1193 self.assertEqual(t.name, "foo")
1194 self.assertEqual(t.uid, 123)
1195
1196
1197class UstarUnicodeTest(unittest.TestCase):
1198 # All *UnicodeTests FIXME
1199
1200 format = tarfile.USTAR_FORMAT
1201
1202 def test_iso8859_1_filename(self):
1203 self._test_unicode_filename("iso8859-1")
1204
1205 def test_utf7_filename(self):
1206 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001207
1208 def test_utf8_filename(self):
1209 self._test_unicode_filename("utf8")
1210
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001211 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001212 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1213 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001214 tar.addfile(tarfile.TarInfo(name))
1215 tar.close()
1216
1217 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001218 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001219 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001220 tar.close()
1221
1222 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001223 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1224 tarinfo = tarfile.TarInfo()
1225
1226 tarinfo.name = "äöü"
1227 if self.format == tarfile.PAX_FORMAT:
1228 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1229 else:
1230 tar.addfile(tarinfo)
1231
1232 tarinfo.name = u"äöü"
1233 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1234
1235 tarinfo.name = "foo"
1236 tarinfo.uname = u"äöü"
1237 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1238
1239 def test_unicode_argument(self):
1240 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1241 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001242 self.assertTrue(type(t.name) is str)
1243 self.assertTrue(type(t.linkname) is str)
1244 self.assertTrue(type(t.uname) is str)
1245 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001246 tar.close()
1247
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001248 def test_uname_unicode(self):
1249 for name in (u"äöü", "äöü"):
1250 t = tarfile.TarInfo("foo")
1251 t.uname = name
1252 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001253
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001254 fobj = StringIO.StringIO()
1255 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1256 tar.addfile(t)
1257 tar.close()
1258 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001259
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001260 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1261 t = tar.getmember("foo")
1262 self.assertEqual(t.uname, "äöü")
1263 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001264
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001265
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001266class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001267
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001268 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001269
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001270
1271class PaxUnicodeTest(UstarUnicodeTest):
1272
1273 format = tarfile.PAX_FORMAT
1274
1275 def _create_unicode_name(self, name):
1276 tar = tarfile.open(tmpname, "w", format=self.format)
1277 t = tarfile.TarInfo()
1278 t.pax_headers["path"] = name
1279 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001280 tar.close()
1281
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001282 def test_error_handlers(self):
1283 # Test if the unicode error handlers work correctly for characters
1284 # that cannot be expressed in a given encoding.
1285 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001286
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001287 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1288 ("replace", "???"), ("ignore", "")):
1289 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1290 errors=handler)
1291 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001292
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001293 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1294 encoding="ascii", errors="strict")
1295
1296 def test_error_handler_utf8(self):
1297 # Create a pathname that has one component representable using
1298 # iso8859-1 and the other only in iso8859-15.
1299 self._create_unicode_name(u"äöü/¤")
1300
1301 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1302 errors="utf-8")
1303 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001304
Georg Brandlded1c4d2006-12-20 11:55:16 +00001305
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001306class AppendTest(unittest.TestCase):
1307 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001308
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001309 def setUp(self):
1310 self.tarname = tmpname
1311 if os.path.exists(self.tarname):
1312 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001313
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001314 def _add_testfile(self, fileobj=None):
1315 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1316 tar.addfile(tarfile.TarInfo("bar"))
1317 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001318
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001319 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001320 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001321 t = src.getmember("ustar/regtype")
1322 t.name = "foo"
1323 f = src.extractfile(t)
1324 tar = tarfile.open(self.tarname, mode)
1325 tar.addfile(t, f)
1326 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001327
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001328 def _test(self, names=["bar"], fileobj=None):
1329 tar = tarfile.open(self.tarname, fileobj=fileobj)
1330 self.assertEqual(tar.getnames(), names)
1331
1332 def test_non_existing(self):
1333 self._add_testfile()
1334 self._test()
1335
1336 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001337 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001338 self._add_testfile()
1339 self._test()
1340
1341 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001342 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001343 self._add_testfile(fobj)
1344 fobj.seek(0)
1345 self._test(fileobj=fobj)
1346
1347 def test_fileobj(self):
1348 self._create_testtar()
1349 data = open(self.tarname).read()
1350 fobj = StringIO.StringIO(data)
1351 self._add_testfile(fobj)
1352 fobj.seek(0)
1353 self._test(names=["foo", "bar"], fileobj=fobj)
1354
1355 def test_existing(self):
1356 self._create_testtar()
1357 self._add_testfile()
1358 self._test(names=["foo", "bar"])
1359
1360 def test_append_gz(self):
1361 if gzip is None:
1362 return
1363 self._create_testtar("w:gz")
1364 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1365
1366 def test_append_bz2(self):
1367 if bz2 is None:
1368 return
1369 self._create_testtar("w:bz2")
1370 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1371
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001372 # Append mode is supposed to fail if the tarfile to append to
1373 # does not end with a zero block.
1374 def _test_error(self, data):
1375 open(self.tarname, "wb").write(data)
1376 self.assertRaises(tarfile.ReadError, self._add_testfile)
1377
1378 def test_null(self):
1379 self._test_error("")
1380
1381 def test_incomplete(self):
1382 self._test_error("\0" * 13)
1383
1384 def test_premature_eof(self):
1385 data = tarfile.TarInfo("foo").tobuf()
1386 self._test_error(data)
1387
1388 def test_trailing_garbage(self):
1389 data = tarfile.TarInfo("foo").tobuf()
1390 self._test_error(data + "\0" * 13)
1391
1392 def test_invalid(self):
1393 self._test_error("a" * 512)
1394
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001395
1396class LimitsTest(unittest.TestCase):
1397
1398 def test_ustar_limits(self):
1399 # 100 char name
1400 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001401 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001402
1403 # 101 char name that cannot be stored
1404 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001405 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001406
1407 # 256 char name with a slash at pos 156
1408 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001409 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001410
1411 # 256 char name that cannot be stored
1412 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001413 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001414
1415 # 512 char name
1416 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
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 # 512 char linkname
1420 tarinfo = tarfile.TarInfo("longlink")
1421 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001422 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001423
1424 # uid > 8 digits
1425 tarinfo = tarfile.TarInfo("name")
1426 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001427 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001428
1429 def test_gnu_limits(self):
1430 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001431 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001432
1433 tarinfo = tarfile.TarInfo("longlink")
1434 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001435 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001436
1437 # uid >= 256 ** 7
1438 tarinfo = tarfile.TarInfo("name")
1439 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001440 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001441
1442 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001443 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001444 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001445
1446 tarinfo = tarfile.TarInfo("longlink")
1447 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001448 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001449
1450 tarinfo = tarfile.TarInfo("name")
1451 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001452 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001453
1454
Lars Gustäbel64581042010-03-03 11:55:48 +00001455class ContextManagerTest(unittest.TestCase):
1456
1457 def test_basic(self):
1458 with tarfile.open(tarname) as tar:
1459 self.assertFalse(tar.closed, "closed inside runtime context")
1460 self.assertTrue(tar.closed, "context manager failed")
1461
1462 def test_closed(self):
1463 # The __enter__() method is supposed to raise IOError
1464 # if the TarFile object is already closed.
1465 tar = tarfile.open(tarname)
1466 tar.close()
1467 with self.assertRaises(IOError):
1468 with tar:
1469 pass
1470
1471 def test_exception(self):
1472 # Test if the IOError exception is passed through properly.
1473 with self.assertRaises(Exception) as exc:
1474 with tarfile.open(tarname) as tar:
1475 raise IOError
1476 self.assertIsInstance(exc.exception, IOError,
1477 "wrong exception raised in context manager")
1478 self.assertTrue(tar.closed, "context manager failed")
1479
1480 def test_no_eof(self):
1481 # __exit__() must not write end-of-archive blocks if an
1482 # exception was raised.
1483 try:
1484 with tarfile.open(tmpname, "w") as tar:
1485 raise Exception
1486 except:
1487 pass
1488 self.assertEqual(os.path.getsize(tmpname), 0,
1489 "context manager wrote an end-of-archive block")
1490 self.assertTrue(tar.closed, "context manager failed")
1491
1492 def test_eof(self):
1493 # __exit__() must write end-of-archive blocks, i.e. call
1494 # TarFile.close() if there was no error.
1495 with tarfile.open(tmpname, "w"):
1496 pass
1497 self.assertNotEqual(os.path.getsize(tmpname), 0,
1498 "context manager wrote no end-of-archive block")
1499
1500 def test_fileobj(self):
1501 # Test that __exit__() did not close the external file
1502 # object.
1503 fobj = open(tmpname, "wb")
1504 try:
1505 with tarfile.open(fileobj=fobj, mode="w") as tar:
1506 raise Exception
1507 except:
1508 pass
1509 self.assertFalse(fobj.closed, "external file object was closed")
1510 self.assertTrue(tar.closed, "context manager failed")
1511 fobj.close()
1512
1513
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001514class LinkEmulationTest(ReadTest):
1515
1516 # Test for issue #8741 regression. On platforms that do not support
1517 # symbolic or hard links tarfile tries to extract these types of members as
1518 # the regular files they point to.
1519 def _test_link_extraction(self, name):
1520 self.tar.extract(name, TEMPDIR)
1521 data = open(os.path.join(TEMPDIR, name), "rb").read()
1522 self.assertEqual(md5sum(data), md5_regtype)
1523
1524 def test_hardlink_extraction1(self):
1525 self._test_link_extraction("ustar/lnktype")
1526
1527 def test_hardlink_extraction2(self):
1528 self._test_link_extraction("./ustar/linktest2/lnktype")
1529
1530 def test_symlink_extraction1(self):
1531 self._test_link_extraction("ustar/symtype")
1532
1533 def test_symlink_extraction2(self):
1534 self._test_link_extraction("./ustar/linktest2/symtype")
1535
1536
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001537class GzipMiscReadTest(MiscReadTest):
1538 tarname = gzipname
1539 mode = "r:gz"
1540class GzipUstarReadTest(UstarReadTest):
1541 tarname = gzipname
1542 mode = "r:gz"
1543class GzipStreamReadTest(StreamReadTest):
1544 tarname = gzipname
1545 mode = "r|gz"
1546class GzipWriteTest(WriteTest):
1547 mode = "w:gz"
1548class GzipStreamWriteTest(StreamWriteTest):
1549 mode = "w|gz"
1550
1551
1552class Bz2MiscReadTest(MiscReadTest):
1553 tarname = bz2name
1554 mode = "r:bz2"
1555class Bz2UstarReadTest(UstarReadTest):
1556 tarname = bz2name
1557 mode = "r:bz2"
1558class Bz2StreamReadTest(StreamReadTest):
1559 tarname = bz2name
1560 mode = "r|bz2"
1561class Bz2WriteTest(WriteTest):
1562 mode = "w:bz2"
1563class Bz2StreamWriteTest(StreamWriteTest):
1564 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001565
Lars Gustäbel2020a592009-03-22 20:09:33 +00001566class Bz2PartialReadTest(unittest.TestCase):
1567 # Issue5068: The _BZ2Proxy.read() method loops forever
1568 # on an empty or partial bzipped file.
1569
1570 def _test_partial_input(self, mode):
1571 class MyStringIO(StringIO.StringIO):
1572 hit_eof = False
1573 def read(self, n):
1574 if self.hit_eof:
1575 raise AssertionError("infinite loop detected in tarfile.open()")
1576 self.hit_eof = self.pos == self.len
1577 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001578 def seek(self, *args):
1579 self.hit_eof = False
1580 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001581
1582 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1583 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001584 try:
1585 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1586 except tarfile.ReadError:
1587 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001588
1589 def test_partial_input(self):
1590 self._test_partial_input("r")
1591
1592 def test_partial_input_bz2(self):
1593 self._test_partial_input("r:bz2")
1594
1595
Neal Norwitz996acf12003-02-17 14:51:41 +00001596def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001597 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001598
Walter Dörwald21d3a322003-05-01 17:45:56 +00001599 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001600 UstarReadTest,
1601 MiscReadTest,
1602 StreamReadTest,
1603 DetectReadTest,
1604 MemberReadTest,
1605 GNUReadTest,
1606 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001607 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001608 StreamWriteTest,
1609 GNUWriteTest,
1610 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001611 UstarUnicodeTest,
1612 GNUUnicodeTest,
1613 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001614 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001615 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001616 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001617 ]
1618
Neal Norwitza4f651a2004-07-20 22:07:44 +00001619 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001620 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001621 else:
1622 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001623
1624 fobj = open(tarname, "rb")
1625 data = fobj.read()
1626 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001627
Walter Dörwald21d3a322003-05-01 17:45:56 +00001628 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001629 # Create testtar.tar.gz and add gzip-specific tests.
1630 tar = gzip.open(gzipname, "wb")
1631 tar.write(data)
1632 tar.close()
1633
1634 tests += [
1635 GzipMiscReadTest,
1636 GzipUstarReadTest,
1637 GzipStreamReadTest,
1638 GzipWriteTest,
1639 GzipStreamWriteTest,
1640 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001641
1642 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001643 # Create testtar.tar.bz2 and add bz2-specific tests.
1644 tar = bz2.BZ2File(bz2name, "wb")
1645 tar.write(data)
1646 tar.close()
1647
1648 tests += [
1649 Bz2MiscReadTest,
1650 Bz2UstarReadTest,
1651 Bz2StreamReadTest,
1652 Bz2WriteTest,
1653 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001654 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001655 ]
1656
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001657 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001658 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001659 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001660 if os.path.exists(TEMPDIR):
1661 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001662
Neal Norwitz996acf12003-02-17 14:51:41 +00001663if __name__ == "__main__":
1664 test_main()