blob: 3e054ac5ee10d0cc68d4b9b9e8d9ae85fee5cbb4 [file] [log] [blame]
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001# -*- coding: iso-8859-15 -*-
Lars Gustäbelc64e4022007-03-13 10:47:19 +00002
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00003import sys
4import os
5import shutil
Georg Brandl38c6a222006-05-10 16:26:03 +00006import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00007from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00008import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00009
10import unittest
11import tarfile
12
13from test import test_support
14
15# Check for our compression modules.
16try:
17 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000018 gzip.GzipFile
19except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000020 gzip = None
21try:
22 import bz2
23except ImportError:
24 bz2 = None
25
Lars Gustäbelc64e4022007-03-13 10:47:19 +000026def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000027 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000028
Antoine Pitrou310c9fe2009-11-11 20:55:07 +000029TEMPDIR = os.path.abspath(test_support.TESTFN)
30tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000031gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
32bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
33tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000034
Lars Gustäbelc64e4022007-03-13 10:47:19 +000035md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
36md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000037
38
Lars Gustäbelc64e4022007-03-13 10:47:19 +000039class ReadTest(unittest.TestCase):
40
41 tarname = tarname
42 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000043
44 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000045 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000046
47 def tearDown(self):
48 self.tar.close()
49
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000050
Lars Gustäbelc64e4022007-03-13 10:47:19 +000051class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000052
Lars Gustäbelc64e4022007-03-13 10:47:19 +000053 def test_fileobj_regular_file(self):
54 tarinfo = self.tar.getmember("ustar/regtype")
55 fobj = self.tar.extractfile(tarinfo)
56 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000057 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000058 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000059
Lars Gustäbelc64e4022007-03-13 10:47:19 +000060 def test_fileobj_readlines(self):
61 self.tar.extract("ustar/regtype", TEMPDIR)
62 tarinfo = self.tar.getmember("ustar/regtype")
63 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
64 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000065
Lars Gustäbelc64e4022007-03-13 10:47:19 +000066 lines1 = fobj1.readlines()
67 lines2 = fobj2.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000068 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000069 "fileobj.readlines() failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000070 self.assertTrue(len(lines2) == 114,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000071 "fileobj.readlines() failed")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +000072 self.assertTrue(lines2[83] ==
Lars Gustäbelc64e4022007-03-13 10:47:19 +000073 "I will gladly admit that Python is not the fastest running scripting language.\n",
74 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000075
Lars Gustäbelc64e4022007-03-13 10:47:19 +000076 def test_fileobj_iter(self):
77 self.tar.extract("ustar/regtype", TEMPDIR)
78 tarinfo = self.tar.getmember("ustar/regtype")
79 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
80 fobj2 = self.tar.extractfile(tarinfo)
81 lines1 = fobj1.readlines()
82 lines2 = [line for line in fobj2]
Benjamin Peterson5c8da862009-06-30 22:57:08 +000083 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000084 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000085
Lars Gustäbelc64e4022007-03-13 10:47:19 +000086 def test_fileobj_seek(self):
87 self.tar.extract("ustar/regtype", TEMPDIR)
88 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
89 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000090 fobj.close()
91
Lars Gustäbelc64e4022007-03-13 10:47:19 +000092 tarinfo = self.tar.getmember("ustar/regtype")
93 fobj = self.tar.extractfile(tarinfo)
94
95 text = fobj.read()
96 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000097 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000098 "seek() to file's start failed")
99 fobj.seek(2048, 0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000100 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000101 "seek() to absolute position failed")
102 fobj.seek(-1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000103 self.assertTrue(1024 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000104 "seek() to negative relative position failed")
105 fobj.seek(1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000106 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000107 "seek() to positive relative position failed")
108 s = fobj.read(10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000109 self.assertTrue(s == data[2048:2058],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000110 "read() after seek failed")
111 fobj.seek(0, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000112 self.assertTrue(tarinfo.size == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000113 "seek() to file's end failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000114 self.assertTrue(fobj.read() == "",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000115 "read() at file's end did not return empty string")
116 fobj.seek(-tarinfo.size, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000117 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000118 "relative seek() to file's start failed")
119 fobj.seek(512)
120 s1 = fobj.readlines()
121 fobj.seek(512)
122 s2 = fobj.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000123 self.assertTrue(s1 == s2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000124 "readlines() after seek failed")
125 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000126 self.assertTrue(len(fobj.readline()) == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000127 "tell() after readline() failed")
128 fobj.seek(512)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000129 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000130 "tell() after seek() and readline() failed")
131 fobj.seek(0)
132 line = fobj.readline()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000133 self.assertTrue(fobj.read() == data[len(line):],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000134 "read() after readline() failed")
135 fobj.close()
136
Lars Gustäbel4da7d412010-06-03 12:34:14 +0000137 # Test if symbolic and hard links are resolved by extractfile(). The
138 # test link members each point to a regular member whose data is
139 # supposed to be exported.
140 def _test_fileobj_link(self, lnktype, regtype):
141 a = self.tar.extractfile(lnktype)
142 b = self.tar.extractfile(regtype)
143 self.assertEqual(a.name, b.name)
144
145 def test_fileobj_link1(self):
146 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
147
148 def test_fileobj_link2(self):
149 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
150
151 def test_fileobj_symlink1(self):
152 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
153
154 def test_fileobj_symlink2(self):
155 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
156
Lars Gustäbel231d4742012-04-24 22:42:08 +0200157 def test_issue14160(self):
158 self._test_fileobj_link("symtype2", "ustar/regtype")
159
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000160
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000161class CommonReadTest(ReadTest):
162
163 def test_empty_tarfile(self):
164 # Test for issue6123: Allow opening empty archives.
165 # This test checks if tarfile.open() is able to open an empty tar
166 # archive successfully. Note that an empty tar archive is not the
167 # same as an empty file!
168 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
169 try:
170 tar = tarfile.open(tmpname, self.mode)
171 tar.getnames()
172 except tarfile.ReadError:
173 self.fail("tarfile.open() failed on empty archive")
174 self.assertListEqual(tar.getmembers(), [])
175
176 def test_null_tarfile(self):
177 # Test for issue6123: Allow opening empty archives.
178 # This test guarantees that tarfile.open() does not treat an empty
179 # file as an empty tar archive.
180 open(tmpname, "wb").close()
181 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
182 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
183
Serhiy Storchakad804f532014-01-13 19:08:51 +0200184 def test_non_existent_tarfile(self):
185 # Test for issue11513: prevent non-existent gzipped tarfiles raising
186 # multiple exceptions.
187 exctype = OSError if '|' in self.mode else IOError
188 with self.assertRaisesRegexp(exctype, "xxx") as ex:
189 tarfile.open("xxx", self.mode)
190 self.assertEqual(ex.exception.errno, errno.ENOENT)
191
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000192 def test_ignore_zeros(self):
193 # Test TarFile's ignore_zeros option.
194 if self.mode.endswith(":gz"):
195 _open = gzip.GzipFile
196 elif self.mode.endswith(":bz2"):
197 _open = bz2.BZ2File
198 else:
199 _open = open
200
201 for char in ('\0', 'a'):
202 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
203 # are ignored correctly.
204 fobj = _open(tmpname, "wb")
205 fobj.write(char * 1024)
206 fobj.write(tarfile.TarInfo("foo").tobuf())
207 fobj.close()
208
209 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
210 self.assertListEqual(tar.getnames(), ["foo"],
211 "ignore_zeros=True should have skipped the %r-blocks" % char)
212 tar.close()
213
214
215class MiscReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000216
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000217 def test_no_name_argument(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000218 fobj = open(self.tarname, "rb")
219 tar = tarfile.open(fileobj=fobj, mode=self.mode)
220 self.assertEqual(tar.name, os.path.abspath(fobj.name))
221
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000222 def test_no_name_attribute(self):
223 data = open(self.tarname, "rb").read()
224 fobj = StringIO.StringIO(data)
225 self.assertRaises(AttributeError, getattr, fobj, "name")
226 tar = tarfile.open(fileobj=fobj, mode=self.mode)
227 self.assertEqual(tar.name, None)
228
229 def test_empty_name_attribute(self):
230 data = open(self.tarname, "rb").read()
231 fobj = StringIO.StringIO(data)
232 fobj.name = ""
233 tar = tarfile.open(fileobj=fobj, mode=self.mode)
234 self.assertEqual(tar.name, None)
235
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000236 def test_fileobj_with_offset(self):
237 # Skip the first member and store values from the second member
238 # of the testtar.
239 tar = tarfile.open(self.tarname, mode=self.mode)
240 tar.next()
241 t = tar.next()
242 name = t.name
243 offset = t.offset
244 data = tar.extractfile(t).read()
245 tar.close()
246
247 # Open the testtar and seek to the offset of the second member.
248 if self.mode.endswith(":gz"):
249 _open = gzip.GzipFile
250 elif self.mode.endswith(":bz2"):
251 _open = bz2.BZ2File
252 else:
253 _open = open
254 fobj = _open(self.tarname, "rb")
255 fobj.seek(offset)
256
257 # Test if the tarfile starts with the second member.
258 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
259 t = tar.next()
260 self.assertEqual(t.name, name)
261 # Read to the end of fileobj and test if seeking back to the
262 # beginning works.
263 tar.getmembers()
264 self.assertEqual(tar.extractfile(t).read(), data,
265 "seek back did not work")
266 tar.close()
267
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000268 def test_fail_comp(self):
269 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
270 if self.mode == "r:":
Zachary Ware1f702212013-12-10 14:09:20 -0600271 self.skipTest('needs a gz or bz2 mode')
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000272 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
273 fobj = open(tarname, "rb")
274 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
275
276 def test_v7_dirtype(self):
277 # Test old style dirtype member (bug #1336623):
278 # Old V7 tars create directory members using an AREGTYPE
279 # header with a "/" appended to the filename field.
280 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000281 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000282 "v7 dirtype failed")
283
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000284 def test_xstar_type(self):
285 # The xstar format stores extra atime and ctime fields inside the
286 # space reserved for the prefix field. The prefix field must be
287 # ignored in this case, otherwise it will mess up the name.
288 try:
289 self.tar.getmember("misc/regtype-xstar")
290 except KeyError:
291 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
292
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000293 def test_check_members(self):
294 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000295 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000296 "wrong mtime for %s" % tarinfo.name)
297 if not tarinfo.name.startswith("ustar/"):
298 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000299 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000300 "wrong uname for %s" % tarinfo.name)
301
302 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000303 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000304 "could not find all members")
305
306 def test_extract_hardlink(self):
307 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200308 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
309 tar.extract("ustar/regtype", TEMPDIR)
310 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000311
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000312 tar.extract("ustar/lnktype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200313 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
314 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
315 data = f.read()
316 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000317
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000318 tar.extract("ustar/symtype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200319 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
320 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
321 data = f.read()
322 self.assertEqual(md5sum(data), md5_regtype)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000323
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000324 def test_extractall(self):
325 # Test if extractall() correctly restores directory permissions
326 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000327 tar = tarfile.open(tarname, encoding="iso8859-1")
328 directories = [t for t in tar if t.isdir()]
329 tar.extractall(TEMPDIR, directories)
330 for tarinfo in directories:
331 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000332 if sys.platform != "win32":
333 # Win32 has no support for fine grained permissions.
334 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000335 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
336 tar.close()
337
Lars Gustäbel12adc652009-11-23 15:46:19 +0000338 def test_init_close_fobj(self):
339 # Issue #7341: Close the internal file object in the TarFile
340 # constructor in case of an error. For the test we rely on
341 # the fact that opening an empty file raises a ReadError.
342 empty = os.path.join(TEMPDIR, "empty")
343 open(empty, "wb").write("")
344
345 try:
346 tar = object.__new__(tarfile.TarFile)
347 try:
348 tar.__init__(empty)
349 except tarfile.ReadError:
350 self.assertTrue(tar.fileobj.closed)
351 else:
352 self.fail("ReadError not raised")
353 finally:
354 os.remove(empty)
355
Serhiy Storchakace34ba62013-05-09 14:22:05 +0300356 def test_parallel_iteration(self):
357 # Issue #16601: Restarting iteration over tarfile continued
358 # from where it left off.
359 with tarfile.open(self.tarname) as tar:
360 for m1, m2 in zip(tar, tar):
361 self.assertEqual(m1.offset, m2.offset)
362 self.assertEqual(m1.name, m2.name)
363
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000364
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000365class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000366
367 mode="r|"
368
369 def test_fileobj_regular_file(self):
370 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
371 fobj = self.tar.extractfile(tarinfo)
372 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000373 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000374 "regular file extraction failed")
375
376 def test_provoke_stream_error(self):
377 tarinfos = self.tar.getmembers()
378 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000379 self.assertRaises(tarfile.StreamError, f.read)
380
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000381 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000382 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000383 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000384
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000385 while True:
386 t1 = tar1.next()
387 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000388 if t1 is None:
389 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000390 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000391
392 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000393 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000394 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000395
396 v1 = tar1.extractfile(t1)
397 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000398 if v1 is None:
399 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000400 self.assertTrue(v2 is not None, "stream.extractfile() failed")
401 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000402
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000403 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000404
Georg Brandla32e0a02006-10-24 16:54:16 +0000405
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000406class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000407
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000408 def _testfunc_file(self, name, mode):
409 try:
410 tarfile.open(name, mode)
411 except tarfile.ReadError:
412 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000413
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000414 def _testfunc_fileobj(self, name, mode):
415 try:
416 tarfile.open(name, mode, fileobj=open(name, "rb"))
417 except tarfile.ReadError:
418 self.fail()
419
420 def _test_modes(self, testfunc):
421 testfunc(tarname, "r")
422 testfunc(tarname, "r:")
423 testfunc(tarname, "r:*")
424 testfunc(tarname, "r|")
425 testfunc(tarname, "r|*")
426
427 if gzip:
428 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
429 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
430 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
431 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
432
433 testfunc(gzipname, "r")
434 testfunc(gzipname, "r:*")
435 testfunc(gzipname, "r:gz")
436 testfunc(gzipname, "r|*")
437 testfunc(gzipname, "r|gz")
438
439 if bz2:
440 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
441 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
442 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
443 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
444
445 testfunc(bz2name, "r")
446 testfunc(bz2name, "r:*")
447 testfunc(bz2name, "r:bz2")
448 testfunc(bz2name, "r|*")
449 testfunc(bz2name, "r|bz2")
450
451 def test_detect_file(self):
452 self._test_modes(self._testfunc_file)
453
454 def test_detect_fileobj(self):
455 self._test_modes(self._testfunc_fileobj)
456
Zachary Ware1f702212013-12-10 14:09:20 -0600457 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbel9a388632011-12-06 13:07:09 +0100458 def test_detect_stream_bz2(self):
459 # Originally, tarfile's stream detection looked for the string
460 # "BZh91" at the start of the file. This is incorrect because
461 # the '9' represents the blocksize (900kB). If the file was
462 # compressed using another blocksize autodetection fails.
Lars Gustäbel9a388632011-12-06 13:07:09 +0100463 with open(tarname, "rb") as fobj:
464 data = fobj.read()
465
466 # Compress with blocksize 100kB, the file starts with "BZh11".
467 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
468 fobj.write(data)
469
470 self._testfunc_file(tmpname, "r|*")
471
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000472
473class MemberReadTest(ReadTest):
474
475 def _test_member(self, tarinfo, chksum=None, **kwargs):
476 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000477 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000478 "wrong md5sum for %s" % tarinfo.name)
479
480 kwargs["mtime"] = 07606136617
481 kwargs["uid"] = 1000
482 kwargs["gid"] = 100
483 if "old-v7" not in tarinfo.name:
484 # V7 tar can't handle alphabetic owners.
485 kwargs["uname"] = "tarfile"
486 kwargs["gname"] = "tarfile"
487 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000488 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000489 "wrong value in %s field of %s" % (k, tarinfo.name))
490
491 def test_find_regtype(self):
492 tarinfo = self.tar.getmember("ustar/regtype")
493 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
494
495 def test_find_conttype(self):
496 tarinfo = self.tar.getmember("ustar/conttype")
497 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
498
499 def test_find_dirtype(self):
500 tarinfo = self.tar.getmember("ustar/dirtype")
501 self._test_member(tarinfo, size=0)
502
503 def test_find_dirtype_with_size(self):
504 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
505 self._test_member(tarinfo, size=255)
506
507 def test_find_lnktype(self):
508 tarinfo = self.tar.getmember("ustar/lnktype")
509 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
510
511 def test_find_symtype(self):
512 tarinfo = self.tar.getmember("ustar/symtype")
513 self._test_member(tarinfo, size=0, linkname="regtype")
514
515 def test_find_blktype(self):
516 tarinfo = self.tar.getmember("ustar/blktype")
517 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
518
519 def test_find_chrtype(self):
520 tarinfo = self.tar.getmember("ustar/chrtype")
521 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
522
523 def test_find_fifotype(self):
524 tarinfo = self.tar.getmember("ustar/fifotype")
525 self._test_member(tarinfo, size=0)
526
527 def test_find_sparse(self):
528 tarinfo = self.tar.getmember("ustar/sparse")
529 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
530
531 def test_find_umlauts(self):
532 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
533 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
534
535 def test_find_ustar_longname(self):
536 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000537 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000538
539 def test_find_regtype_oldv7(self):
540 tarinfo = self.tar.getmember("misc/regtype-old-v7")
541 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
542
543 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000544 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000545 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
546 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
547
548
549class LongnameTest(ReadTest):
550
551 def test_read_longname(self):
552 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000553 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000554 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000555 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000556 except KeyError:
557 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000558 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000559
560 def test_read_longlink(self):
561 longname = self.subdir + "/" + "123/" * 125 + "longname"
562 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
563 try:
564 tarinfo = self.tar.getmember(longlink)
565 except KeyError:
566 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000567 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000568
569 def test_truncated_longname(self):
570 longname = self.subdir + "/" + "123/" * 125 + "longname"
571 tarinfo = self.tar.getmember(longname)
572 offset = tarinfo.offset
573 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000574 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000575 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
576
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000577 def test_header_offset(self):
578 # Test if the start offset of the TarInfo object includes
579 # the preceding extended header.
580 longname = self.subdir + "/" + "123/" * 125 + "longname"
581 offset = self.tar.getmember(longname).offset
582 fobj = open(tarname)
583 fobj.seek(offset)
584 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
585 self.assertEqual(tarinfo.type, self.longnametype)
586
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000587
588class GNUReadTest(LongnameTest):
589
590 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000591 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000592
593 def test_sparse_file(self):
594 tarinfo1 = self.tar.getmember("ustar/sparse")
595 fobj1 = self.tar.extractfile(tarinfo1)
596 tarinfo2 = self.tar.getmember("gnu/sparse")
597 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000598 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000599 "sparse file extraction failed")
600
601
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000602class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000603
604 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000605 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000606
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000607 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000608 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000609
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000610 tarinfo = tar.getmember("pax/regtype1")
611 self.assertEqual(tarinfo.uname, "foo")
612 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000613 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000614
615 tarinfo = tar.getmember("pax/regtype2")
616 self.assertEqual(tarinfo.uname, "")
617 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000618 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000619
620 tarinfo = tar.getmember("pax/regtype3")
621 self.assertEqual(tarinfo.uname, "tarfile")
622 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000623 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
624
625 def test_pax_number_fields(self):
626 # All following number fields are read from the pax header.
627 tar = tarfile.open(tarname, encoding="iso8859-1")
628 tarinfo = tar.getmember("pax/regtype4")
629 self.assertEqual(tarinfo.size, 7011)
630 self.assertEqual(tarinfo.uid, 123)
631 self.assertEqual(tarinfo.gid, 123)
632 self.assertEqual(tarinfo.mtime, 1041808783.0)
633 self.assertEqual(type(tarinfo.mtime), float)
634 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
635 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000636
637
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000638class WriteTestBase(unittest.TestCase):
639 # Put all write tests in here that are supposed to be tested
640 # in all possible mode combinations.
641
642 def test_fileobj_no_close(self):
643 fobj = StringIO.StringIO()
644 tar = tarfile.open(fileobj=fobj, mode=self.mode)
645 tar.addfile(tarfile.TarInfo("foo"))
646 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000647 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000648
649
650class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000651
652 mode = "w:"
653
654 def test_100_char_name(self):
655 # The name field in a tar header stores strings of at most 100 chars.
656 # If a string is shorter than 100 chars it has to be padded with '\0',
657 # which implies that a string of exactly 100 chars is stored without
658 # a trailing '\0'.
659 name = "0123456789" * 10
660 tar = tarfile.open(tmpname, self.mode)
661 t = tarfile.TarInfo(name)
662 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000663 tar.close()
664
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000665 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000666 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000667 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000668 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000669
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000670 def test_tar_size(self):
671 # Test for bug #1013882.
672 tar = tarfile.open(tmpname, self.mode)
673 path = os.path.join(TEMPDIR, "file")
674 fobj = open(path, "wb")
675 fobj.write("aaa")
676 fobj.close()
677 tar.add(path)
678 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000679 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000680 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000681
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000682 # The test_*_size tests test for bug #1167128.
683 def test_file_size(self):
684 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000685
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000686 path = os.path.join(TEMPDIR, "file")
687 fobj = open(path, "wb")
688 fobj.close()
689 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000690 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000691
692 fobj = open(path, "wb")
693 fobj.write("aaa")
694 fobj.close()
695 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000696 self.assertEqual(tarinfo.size, 3)
697
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000698 tar.close()
699
700 def test_directory_size(self):
701 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000702 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000703 try:
704 tar = tarfile.open(tmpname, self.mode)
705 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000706 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000707 finally:
708 os.rmdir(path)
709
710 def test_link_size(self):
711 if hasattr(os, "link"):
712 link = os.path.join(TEMPDIR, "link")
713 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000714 fobj = open(target, "wb")
715 fobj.write("aaa")
716 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000717 os.link(target, link)
718 try:
719 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000720 # Record the link target in the inodes list.
721 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000722 tarinfo = tar.gettarinfo(link)
723 self.assertEqual(tarinfo.size, 0)
724 finally:
725 os.remove(target)
726 os.remove(link)
727
728 def test_symlink_size(self):
729 if hasattr(os, "symlink"):
730 path = os.path.join(TEMPDIR, "symlink")
731 os.symlink("link_target", path)
732 try:
733 tar = tarfile.open(tmpname, self.mode)
734 tarinfo = tar.gettarinfo(path)
735 self.assertEqual(tarinfo.size, 0)
736 finally:
737 os.remove(path)
738
739 def test_add_self(self):
740 # Test for #1257255.
741 dstname = os.path.abspath(tmpname)
742
743 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000744 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000745
746 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000747 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000748
749 cwd = os.getcwd()
750 os.chdir(TEMPDIR)
751 tar.add(dstname)
752 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000753 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000754
Lars Gustäbel104490e2007-06-18 11:42:11 +0000755 def test_exclude(self):
756 tempdir = os.path.join(TEMPDIR, "exclude")
757 os.mkdir(tempdir)
758 try:
759 for name in ("foo", "bar", "baz"):
760 name = os.path.join(tempdir, name)
761 open(name, "wb").close()
762
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000763 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000764
765 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000766 with test_support.check_warnings(("use the filter argument",
767 DeprecationWarning)):
768 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000769 tar.close()
770
771 tar = tarfile.open(tmpname, "r")
772 self.assertEqual(len(tar.getmembers()), 1)
773 self.assertEqual(tar.getnames()[0], "empty_dir")
774 finally:
775 shutil.rmtree(tempdir)
776
Lars Gustäbel21121e62009-09-12 10:28:15 +0000777 def test_filter(self):
778 tempdir = os.path.join(TEMPDIR, "filter")
779 os.mkdir(tempdir)
780 try:
781 for name in ("foo", "bar", "baz"):
782 name = os.path.join(tempdir, name)
783 open(name, "wb").close()
784
785 def filter(tarinfo):
786 if os.path.basename(tarinfo.name) == "bar":
787 return
788 tarinfo.uid = 123
789 tarinfo.uname = "foo"
790 return tarinfo
791
792 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
793 tar.add(tempdir, arcname="empty_dir", filter=filter)
794 tar.close()
795
796 tar = tarfile.open(tmpname, "r")
797 for tarinfo in tar:
798 self.assertEqual(tarinfo.uid, 123)
799 self.assertEqual(tarinfo.uname, "foo")
800 self.assertEqual(len(tar.getmembers()), 3)
801 tar.close()
802 finally:
803 shutil.rmtree(tempdir)
804
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000805 # Guarantee that stored pathnames are not modified. Don't
806 # remove ./ or ../ or double slashes. Still make absolute
807 # pathnames relative.
808 # For details see bug #6054.
809 def _test_pathname(self, path, cmp_path=None, dir=False):
810 # Create a tarfile with an empty member named path
811 # and compare the stored name with the original.
812 foo = os.path.join(TEMPDIR, "foo")
813 if not dir:
814 open(foo, "w").close()
815 else:
816 os.mkdir(foo)
817
818 tar = tarfile.open(tmpname, self.mode)
819 tar.add(foo, arcname=path)
820 tar.close()
821
822 tar = tarfile.open(tmpname, "r")
823 t = tar.next()
824 tar.close()
825
826 if not dir:
827 os.remove(foo)
828 else:
829 os.rmdir(foo)
830
831 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
832
833 def test_pathnames(self):
834 self._test_pathname("foo")
835 self._test_pathname(os.path.join("foo", ".", "bar"))
836 self._test_pathname(os.path.join("foo", "..", "bar"))
837 self._test_pathname(os.path.join(".", "foo"))
838 self._test_pathname(os.path.join(".", "foo", "."))
839 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
840 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
841 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
842 self._test_pathname(os.path.join("..", "foo"))
843 self._test_pathname(os.path.join("..", "foo", ".."))
844 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
845 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
846
847 self._test_pathname("foo" + os.sep + os.sep + "bar")
848 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
849
850 def test_abs_pathnames(self):
851 if sys.platform == "win32":
852 self._test_pathname("C:\\foo", "foo")
853 else:
854 self._test_pathname("/foo", "foo")
855 self._test_pathname("///foo", "foo")
856
857 def test_cwd(self):
858 # Test adding the current working directory.
859 cwd = os.getcwd()
860 os.chdir(TEMPDIR)
861 try:
862 open("foo", "w").close()
863
864 tar = tarfile.open(tmpname, self.mode)
865 tar.add(".")
866 tar.close()
867
868 tar = tarfile.open(tmpname, "r")
869 for t in tar:
Serhiy Storchaka88761452012-12-28 00:32:19 +0200870 self.assertTrue(t.name == "." or t.name.startswith("./"))
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000871 tar.close()
872 finally:
873 os.chdir(cwd)
874
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800875 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800876 def test_extractall_symlinks(self):
877 # Test if extractall works properly when tarfile contains symlinks
878 tempdir = os.path.join(TEMPDIR, "testsymlinks")
879 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
880 os.mkdir(tempdir)
881 try:
882 source_file = os.path.join(tempdir,'source')
883 target_file = os.path.join(tempdir,'symlink')
884 with open(source_file,'w') as f:
885 f.write('something\n')
886 os.symlink(source_file, target_file)
887 tar = tarfile.open(temparchive,'w')
888 tar.add(source_file, arcname=os.path.basename(source_file))
889 tar.add(target_file, arcname=os.path.basename(target_file))
890 tar.close()
891 # Let's extract it to the location which contains the symlink
892 tar = tarfile.open(temparchive,'r')
893 # this should not raise OSError: [Errno 17] File exists
894 try:
895 tar.extractall(path=tempdir)
896 except OSError:
897 self.fail("extractall failed with symlinked files")
898 finally:
899 tar.close()
900 finally:
901 os.unlink(temparchive)
902 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000903
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +0800904 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
905 def test_extractall_broken_symlinks(self):
906 # Test if extractall works properly when tarfile contains broken
907 # symlinks
908 tempdir = os.path.join(TEMPDIR, "testsymlinks")
909 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
910 os.mkdir(tempdir)
911 try:
912 source_file = os.path.join(tempdir,'source')
913 target_file = os.path.join(tempdir,'symlink')
914 with open(source_file,'w') as f:
915 f.write('something\n')
916 os.symlink(source_file, target_file)
917 tar = tarfile.open(temparchive,'w')
918 tar.add(target_file, arcname=os.path.basename(target_file))
919 tar.close()
920 # remove the real file
921 os.unlink(source_file)
922 # Let's extract it to the location which contains the symlink
923 tar = tarfile.open(temparchive,'r')
924 # this should not raise OSError: [Errno 17] File exists
925 try:
926 tar.extractall(path=tempdir)
927 except OSError:
928 self.fail("extractall failed with broken symlinked files")
929 finally:
930 tar.close()
931 finally:
932 os.unlink(temparchive)
933 shutil.rmtree(tempdir)
934
935 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
936 def test_extractall_hardlinks(self):
937 # Test if extractall works properly when tarfile contains symlinks
938 tempdir = os.path.join(TEMPDIR, "testsymlinks")
939 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
940 os.mkdir(tempdir)
941 try:
942 source_file = os.path.join(tempdir,'source')
943 target_file = os.path.join(tempdir,'symlink')
944 with open(source_file,'w') as f:
945 f.write('something\n')
946 os.link(source_file, target_file)
947 tar = tarfile.open(temparchive,'w')
948 tar.add(source_file, arcname=os.path.basename(source_file))
949 tar.add(target_file, arcname=os.path.basename(target_file))
950 tar.close()
951 # Let's extract it to the location which contains the symlink
952 tar = tarfile.open(temparchive,'r')
953 # this should not raise OSError: [Errno 17] File exists
954 try:
955 tar.extractall(path=tempdir)
956 except OSError:
957 self.fail("extractall failed with linked files")
958 finally:
959 tar.close()
960 finally:
961 os.unlink(temparchive)
962 shutil.rmtree(tempdir)
963
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000964class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000965
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000966 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +0000967
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000968 def test_stream_padding(self):
969 # Test for bug #1543303.
970 tar = tarfile.open(tmpname, self.mode)
971 tar.close()
972
973 if self.mode.endswith("gz"):
974 fobj = gzip.GzipFile(tmpname)
975 data = fobj.read()
976 fobj.close()
977 elif self.mode.endswith("bz2"):
978 dec = bz2.BZ2Decompressor()
979 data = open(tmpname, "rb").read()
980 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000981 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000982 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +0000983 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000984 fobj = open(tmpname, "rb")
985 data = fobj.read()
986 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +0000987
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000988 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +0000989 "incorrect zero padding")
990
Zachary Ware1f702212013-12-10 14:09:20 -0600991 @unittest.skipIf(sys.platform == 'win32', 'not appropriate for Windows')
992 @unittest.skipUnless(hasattr(os, 'umask'), 'requires os.umask')
Lars Gustäbel5c4c4612010-04-29 15:23:38 +0000993 def test_file_mode(self):
994 # Test for issue #8464: Create files with correct
995 # permissions.
Lars Gustäbel5c4c4612010-04-29 15:23:38 +0000996 if os.path.exists(tmpname):
997 os.remove(tmpname)
998
999 original_umask = os.umask(0022)
1000 try:
1001 tar = tarfile.open(tmpname, self.mode)
1002 tar.close()
1003 mode = os.stat(tmpname).st_mode & 0777
1004 self.assertEqual(mode, 0644, "wrong file permissions")
1005 finally:
1006 os.umask(original_umask)
1007
Lars Gustäbel7d4d0742011-12-21 19:27:50 +01001008 def test_issue13639(self):
1009 try:
1010 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1011 pass
1012 except UnicodeDecodeError:
1013 self.fail("_Stream failed to write unicode filename")
1014
Neal Norwitz8a519392006-08-21 17:59:46 +00001015
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001016class GNUWriteTest(unittest.TestCase):
1017 # This testcase checks for correct creation of GNU Longname
1018 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001019
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001020 def _length(self, s):
1021 blocks, remainder = divmod(len(s) + 1, 512)
1022 if remainder:
1023 blocks += 1
1024 return blocks * 512
1025
1026 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001027 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001028 count = 512
1029
1030 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001031 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001032 count += 512
1033 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001034 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001035 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001036 count += 512
1037 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001038 return count
1039
1040 def _test(self, name, link=None):
1041 tarinfo = tarfile.TarInfo(name)
1042 if link:
1043 tarinfo.linkname = link
1044 tarinfo.type = tarfile.LNKTYPE
1045
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001046 tar = tarfile.open(tmpname, "w")
1047 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001048 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001049
1050 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001051 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001052 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001053
Georg Brandl87fa5592006-12-06 22:21:18 +00001054 tar.close()
1055
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001056 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001057 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001058 self.assertIsNotNone(member,
1059 "unable to read longname member")
1060 self.assertEqual(tarinfo.name, member.name,
1061 "unable to read longname member")
1062 self.assertEqual(tarinfo.linkname, member.linkname,
1063 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001064
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001065 def test_longname_1023(self):
1066 self._test(("longnam/" * 127) + "longnam")
1067
1068 def test_longname_1024(self):
1069 self._test(("longnam/" * 127) + "longname")
1070
1071 def test_longname_1025(self):
1072 self._test(("longnam/" * 127) + "longname_")
1073
1074 def test_longlink_1023(self):
1075 self._test("name", ("longlnk/" * 127) + "longlnk")
1076
1077 def test_longlink_1024(self):
1078 self._test("name", ("longlnk/" * 127) + "longlink")
1079
1080 def test_longlink_1025(self):
1081 self._test("name", ("longlnk/" * 127) + "longlink_")
1082
1083 def test_longnamelink_1023(self):
1084 self._test(("longnam/" * 127) + "longnam",
1085 ("longlnk/" * 127) + "longlnk")
1086
1087 def test_longnamelink_1024(self):
1088 self._test(("longnam/" * 127) + "longname",
1089 ("longlnk/" * 127) + "longlink")
1090
1091 def test_longnamelink_1025(self):
1092 self._test(("longnam/" * 127) + "longname_",
1093 ("longlnk/" * 127) + "longlink_")
1094
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001095
1096class HardlinkTest(unittest.TestCase):
1097 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001098
1099 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001100 self.foo = os.path.join(TEMPDIR, "foo")
1101 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001102
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001103 fobj = open(self.foo, "wb")
1104 fobj.write("foo")
1105 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001106
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001107 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001108
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001109 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001110 self.tar.add(self.foo)
1111
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001112 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001113 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001114 os.remove(self.foo)
1115 os.remove(self.bar)
1116
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001117 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001118 # The same name will be added as a REGTYPE every
1119 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001120 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001121 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001122 "add file as regular failed")
1123
1124 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001125 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001126 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001127 "add file as hardlink failed")
1128
1129 def test_dereference_hardlink(self):
1130 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001131 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001132 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001133 "dereferencing hardlink failed")
1134
Neal Norwitza4f651a2004-07-20 22:07:44 +00001135
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001136class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001137
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001138 def _test(self, name, link=None):
1139 # See GNUWriteTest.
1140 tarinfo = tarfile.TarInfo(name)
1141 if link:
1142 tarinfo.linkname = link
1143 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001144
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001145 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1146 tar.addfile(tarinfo)
1147 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001148
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001149 tar = tarfile.open(tmpname)
1150 if link:
1151 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001152 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001153 else:
1154 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001155 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001156
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001157 def test_pax_global_header(self):
1158 pax_headers = {
1159 u"foo": u"bar",
1160 u"uid": u"0",
1161 u"mtime": u"1.23",
1162 u"test": u"äöü",
1163 u"äöü": u"test"}
1164
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001165 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001166 pax_headers=pax_headers)
1167 tar.addfile(tarfile.TarInfo("test"))
1168 tar.close()
1169
1170 # Test if the global header was written correctly.
1171 tar = tarfile.open(tmpname, encoding="iso8859-1")
1172 self.assertEqual(tar.pax_headers, pax_headers)
1173 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1174
1175 # Test if all the fields are unicode.
1176 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001177 self.assertTrue(type(key) is unicode)
1178 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001179 if key in tarfile.PAX_NUMBER_FIELDS:
1180 try:
1181 tarfile.PAX_NUMBER_FIELDS[key](val)
1182 except (TypeError, ValueError):
1183 self.fail("unable to convert pax header field")
1184
1185 def test_pax_extended_header(self):
1186 # The fields from the pax header have priority over the
1187 # TarInfo.
1188 pax_headers = {u"path": u"foo", u"uid": u"123"}
1189
1190 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1191 t = tarfile.TarInfo()
1192 t.name = u"äöü" # non-ASCII
1193 t.uid = 8**8 # too large
1194 t.pax_headers = pax_headers
1195 tar.addfile(t)
1196 tar.close()
1197
1198 tar = tarfile.open(tmpname, encoding="iso8859-1")
1199 t = tar.getmembers()[0]
1200 self.assertEqual(t.pax_headers, pax_headers)
1201 self.assertEqual(t.name, "foo")
1202 self.assertEqual(t.uid, 123)
1203
1204
1205class UstarUnicodeTest(unittest.TestCase):
1206 # All *UnicodeTests FIXME
1207
1208 format = tarfile.USTAR_FORMAT
1209
1210 def test_iso8859_1_filename(self):
1211 self._test_unicode_filename("iso8859-1")
1212
1213 def test_utf7_filename(self):
1214 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001215
1216 def test_utf8_filename(self):
1217 self._test_unicode_filename("utf8")
1218
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001219 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001220 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1221 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001222 tar.addfile(tarfile.TarInfo(name))
1223 tar.close()
1224
1225 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001226 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001227 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001228 tar.close()
1229
1230 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001231 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1232 tarinfo = tarfile.TarInfo()
1233
1234 tarinfo.name = "äöü"
1235 if self.format == tarfile.PAX_FORMAT:
1236 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1237 else:
1238 tar.addfile(tarinfo)
1239
1240 tarinfo.name = u"äöü"
1241 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1242
1243 tarinfo.name = "foo"
1244 tarinfo.uname = u"äöü"
1245 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1246
1247 def test_unicode_argument(self):
1248 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1249 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001250 self.assertTrue(type(t.name) is str)
1251 self.assertTrue(type(t.linkname) is str)
1252 self.assertTrue(type(t.uname) is str)
1253 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001254 tar.close()
1255
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001256 def test_uname_unicode(self):
1257 for name in (u"äöü", "äöü"):
1258 t = tarfile.TarInfo("foo")
1259 t.uname = name
1260 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001261
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001262 fobj = StringIO.StringIO()
1263 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1264 tar.addfile(t)
1265 tar.close()
1266 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001267
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001268 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1269 t = tar.getmember("foo")
1270 self.assertEqual(t.uname, "äöü")
1271 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001272
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001273
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001274class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001275
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001276 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001277
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001278
1279class PaxUnicodeTest(UstarUnicodeTest):
1280
1281 format = tarfile.PAX_FORMAT
1282
1283 def _create_unicode_name(self, name):
1284 tar = tarfile.open(tmpname, "w", format=self.format)
1285 t = tarfile.TarInfo()
1286 t.pax_headers["path"] = name
1287 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001288 tar.close()
1289
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001290 def test_error_handlers(self):
1291 # Test if the unicode error handlers work correctly for characters
1292 # that cannot be expressed in a given encoding.
1293 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001294
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001295 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1296 ("replace", "???"), ("ignore", "")):
1297 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1298 errors=handler)
1299 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001300
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001301 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1302 encoding="ascii", errors="strict")
1303
1304 def test_error_handler_utf8(self):
1305 # Create a pathname that has one component representable using
1306 # iso8859-1 and the other only in iso8859-15.
1307 self._create_unicode_name(u"äöü/¤")
1308
1309 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1310 errors="utf-8")
1311 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001312
Georg Brandlded1c4d2006-12-20 11:55:16 +00001313
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001314class AppendTest(unittest.TestCase):
1315 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001316
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001317 def setUp(self):
1318 self.tarname = tmpname
1319 if os.path.exists(self.tarname):
1320 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001321
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001322 def _add_testfile(self, fileobj=None):
1323 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1324 tar.addfile(tarfile.TarInfo("bar"))
1325 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001326
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001327 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001328 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001329 t = src.getmember("ustar/regtype")
1330 t.name = "foo"
1331 f = src.extractfile(t)
1332 tar = tarfile.open(self.tarname, mode)
1333 tar.addfile(t, f)
1334 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001335
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001336 def _test(self, names=["bar"], fileobj=None):
1337 tar = tarfile.open(self.tarname, fileobj=fileobj)
1338 self.assertEqual(tar.getnames(), names)
1339
1340 def test_non_existing(self):
1341 self._add_testfile()
1342 self._test()
1343
1344 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001345 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001346 self._add_testfile()
1347 self._test()
1348
1349 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001350 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001351 self._add_testfile(fobj)
1352 fobj.seek(0)
1353 self._test(fileobj=fobj)
1354
1355 def test_fileobj(self):
1356 self._create_testtar()
1357 data = open(self.tarname).read()
1358 fobj = StringIO.StringIO(data)
1359 self._add_testfile(fobj)
1360 fobj.seek(0)
1361 self._test(names=["foo", "bar"], fileobj=fobj)
1362
1363 def test_existing(self):
1364 self._create_testtar()
1365 self._add_testfile()
1366 self._test(names=["foo", "bar"])
1367
Zachary Ware1f702212013-12-10 14:09:20 -06001368 @unittest.skipUnless(gzip, 'requires gzip')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001369 def test_append_gz(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001370 self._create_testtar("w:gz")
1371 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1372
Zachary Ware1f702212013-12-10 14:09:20 -06001373 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001374 def test_append_bz2(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001375 self._create_testtar("w:bz2")
1376 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1377
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001378 # Append mode is supposed to fail if the tarfile to append to
1379 # does not end with a zero block.
1380 def _test_error(self, data):
1381 open(self.tarname, "wb").write(data)
1382 self.assertRaises(tarfile.ReadError, self._add_testfile)
1383
1384 def test_null(self):
1385 self._test_error("")
1386
1387 def test_incomplete(self):
1388 self._test_error("\0" * 13)
1389
1390 def test_premature_eof(self):
1391 data = tarfile.TarInfo("foo").tobuf()
1392 self._test_error(data)
1393
1394 def test_trailing_garbage(self):
1395 data = tarfile.TarInfo("foo").tobuf()
1396 self._test_error(data + "\0" * 13)
1397
1398 def test_invalid(self):
1399 self._test_error("a" * 512)
1400
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001401
1402class LimitsTest(unittest.TestCase):
1403
1404 def test_ustar_limits(self):
1405 # 100 char name
1406 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001407 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001408
1409 # 101 char name that cannot be stored
1410 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001411 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001412
1413 # 256 char name with a slash at pos 156
1414 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001415 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001416
1417 # 256 char name that cannot be stored
1418 tarinfo = tarfile.TarInfo("1234567/" * 31 + "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 # 512 char name
1422 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001423 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001424
1425 # 512 char linkname
1426 tarinfo = tarfile.TarInfo("longlink")
1427 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001428 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001429
1430 # uid > 8 digits
1431 tarinfo = tarfile.TarInfo("name")
1432 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001433 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001434
1435 def test_gnu_limits(self):
1436 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001437 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001438
1439 tarinfo = tarfile.TarInfo("longlink")
1440 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001441 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001442
1443 # uid >= 256 ** 7
1444 tarinfo = tarfile.TarInfo("name")
1445 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001446 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001447
1448 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001449 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001450 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001451
1452 tarinfo = tarfile.TarInfo("longlink")
1453 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001454 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001455
1456 tarinfo = tarfile.TarInfo("name")
1457 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001458 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001459
1460
Lars Gustäbel64581042010-03-03 11:55:48 +00001461class ContextManagerTest(unittest.TestCase):
1462
1463 def test_basic(self):
1464 with tarfile.open(tarname) as tar:
1465 self.assertFalse(tar.closed, "closed inside runtime context")
1466 self.assertTrue(tar.closed, "context manager failed")
1467
1468 def test_closed(self):
1469 # The __enter__() method is supposed to raise IOError
1470 # if the TarFile object is already closed.
1471 tar = tarfile.open(tarname)
1472 tar.close()
1473 with self.assertRaises(IOError):
1474 with tar:
1475 pass
1476
1477 def test_exception(self):
1478 # Test if the IOError exception is passed through properly.
1479 with self.assertRaises(Exception) as exc:
1480 with tarfile.open(tarname) as tar:
1481 raise IOError
1482 self.assertIsInstance(exc.exception, IOError,
1483 "wrong exception raised in context manager")
1484 self.assertTrue(tar.closed, "context manager failed")
1485
1486 def test_no_eof(self):
1487 # __exit__() must not write end-of-archive blocks if an
1488 # exception was raised.
1489 try:
1490 with tarfile.open(tmpname, "w") as tar:
1491 raise Exception
1492 except:
1493 pass
1494 self.assertEqual(os.path.getsize(tmpname), 0,
1495 "context manager wrote an end-of-archive block")
1496 self.assertTrue(tar.closed, "context manager failed")
1497
1498 def test_eof(self):
1499 # __exit__() must write end-of-archive blocks, i.e. call
1500 # TarFile.close() if there was no error.
1501 with tarfile.open(tmpname, "w"):
1502 pass
1503 self.assertNotEqual(os.path.getsize(tmpname), 0,
1504 "context manager wrote no end-of-archive block")
1505
1506 def test_fileobj(self):
1507 # Test that __exit__() did not close the external file
1508 # object.
1509 fobj = open(tmpname, "wb")
1510 try:
1511 with tarfile.open(fileobj=fobj, mode="w") as tar:
1512 raise Exception
1513 except:
1514 pass
1515 self.assertFalse(fobj.closed, "external file object was closed")
1516 self.assertTrue(tar.closed, "context manager failed")
1517 fobj.close()
1518
1519
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001520class LinkEmulationTest(ReadTest):
1521
1522 # Test for issue #8741 regression. On platforms that do not support
1523 # symbolic or hard links tarfile tries to extract these types of members as
1524 # the regular files they point to.
1525 def _test_link_extraction(self, name):
1526 self.tar.extract(name, TEMPDIR)
1527 data = open(os.path.join(TEMPDIR, name), "rb").read()
1528 self.assertEqual(md5sum(data), md5_regtype)
1529
1530 def test_hardlink_extraction1(self):
1531 self._test_link_extraction("ustar/lnktype")
1532
1533 def test_hardlink_extraction2(self):
1534 self._test_link_extraction("./ustar/linktest2/lnktype")
1535
1536 def test_symlink_extraction1(self):
1537 self._test_link_extraction("ustar/symtype")
1538
1539 def test_symlink_extraction2(self):
1540 self._test_link_extraction("./ustar/linktest2/symtype")
1541
1542
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001543class GzipMiscReadTest(MiscReadTest):
1544 tarname = gzipname
1545 mode = "r:gz"
1546class GzipUstarReadTest(UstarReadTest):
1547 tarname = gzipname
1548 mode = "r:gz"
1549class GzipStreamReadTest(StreamReadTest):
1550 tarname = gzipname
1551 mode = "r|gz"
1552class GzipWriteTest(WriteTest):
1553 mode = "w:gz"
1554class GzipStreamWriteTest(StreamWriteTest):
1555 mode = "w|gz"
1556
1557
1558class Bz2MiscReadTest(MiscReadTest):
1559 tarname = bz2name
1560 mode = "r:bz2"
1561class Bz2UstarReadTest(UstarReadTest):
1562 tarname = bz2name
1563 mode = "r:bz2"
1564class Bz2StreamReadTest(StreamReadTest):
1565 tarname = bz2name
1566 mode = "r|bz2"
1567class Bz2WriteTest(WriteTest):
1568 mode = "w:bz2"
1569class Bz2StreamWriteTest(StreamWriteTest):
1570 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001571
Lars Gustäbel2020a592009-03-22 20:09:33 +00001572class Bz2PartialReadTest(unittest.TestCase):
1573 # Issue5068: The _BZ2Proxy.read() method loops forever
1574 # on an empty or partial bzipped file.
1575
1576 def _test_partial_input(self, mode):
1577 class MyStringIO(StringIO.StringIO):
1578 hit_eof = False
1579 def read(self, n):
1580 if self.hit_eof:
1581 raise AssertionError("infinite loop detected in tarfile.open()")
1582 self.hit_eof = self.pos == self.len
1583 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001584 def seek(self, *args):
1585 self.hit_eof = False
1586 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001587
1588 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1589 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001590 try:
1591 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1592 except tarfile.ReadError:
1593 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001594
1595 def test_partial_input(self):
1596 self._test_partial_input("r")
1597
1598 def test_partial_input_bz2(self):
1599 self._test_partial_input("r:bz2")
1600
1601
Neal Norwitz996acf12003-02-17 14:51:41 +00001602def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001603 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001604
Walter Dörwald21d3a322003-05-01 17:45:56 +00001605 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001606 UstarReadTest,
1607 MiscReadTest,
1608 StreamReadTest,
1609 DetectReadTest,
1610 MemberReadTest,
1611 GNUReadTest,
1612 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001613 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001614 StreamWriteTest,
1615 GNUWriteTest,
1616 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001617 UstarUnicodeTest,
1618 GNUUnicodeTest,
1619 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001620 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001621 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001622 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001623 ]
1624
Neal Norwitza4f651a2004-07-20 22:07:44 +00001625 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001626 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001627 else:
1628 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001629
1630 fobj = open(tarname, "rb")
1631 data = fobj.read()
1632 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001633
Walter Dörwald21d3a322003-05-01 17:45:56 +00001634 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001635 # Create testtar.tar.gz and add gzip-specific tests.
1636 tar = gzip.open(gzipname, "wb")
1637 tar.write(data)
1638 tar.close()
1639
1640 tests += [
1641 GzipMiscReadTest,
1642 GzipUstarReadTest,
1643 GzipStreamReadTest,
1644 GzipWriteTest,
1645 GzipStreamWriteTest,
1646 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001647
1648 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001649 # Create testtar.tar.bz2 and add bz2-specific tests.
1650 tar = bz2.BZ2File(bz2name, "wb")
1651 tar.write(data)
1652 tar.close()
1653
1654 tests += [
1655 Bz2MiscReadTest,
1656 Bz2UstarReadTest,
1657 Bz2StreamReadTest,
1658 Bz2WriteTest,
1659 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001660 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001661 ]
1662
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001663 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001664 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001665 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001666 if os.path.exists(TEMPDIR):
1667 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001668
Neal Norwitz996acf12003-02-17 14:51:41 +00001669if __name__ == "__main__":
1670 test_main()