blob: af59e277f3e40ac3cd2870e7096bd573a7cbd351 [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).
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200300 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
301 tar.extract("ustar/regtype", TEMPDIR)
302 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000303
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000304 tar.extract("ustar/lnktype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200305 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
306 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
307 data = f.read()
308 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000309
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000310 tar.extract("ustar/symtype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200311 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
312 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
313 data = f.read()
314 self.assertEqual(md5sum(data), md5_regtype)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000315
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000316 def test_extractall(self):
317 # Test if extractall() correctly restores directory permissions
318 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000319 tar = tarfile.open(tarname, encoding="iso8859-1")
320 directories = [t for t in tar if t.isdir()]
321 tar.extractall(TEMPDIR, directories)
322 for tarinfo in directories:
323 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel3b027422008-12-12 13:58:03 +0000324 if sys.platform != "win32":
325 # Win32 has no support for fine grained permissions.
326 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000327 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
328 tar.close()
329
Lars Gustäbel12adc652009-11-23 15:46:19 +0000330 def test_init_close_fobj(self):
331 # Issue #7341: Close the internal file object in the TarFile
332 # constructor in case of an error. For the test we rely on
333 # the fact that opening an empty file raises a ReadError.
334 empty = os.path.join(TEMPDIR, "empty")
335 open(empty, "wb").write("")
336
337 try:
338 tar = object.__new__(tarfile.TarFile)
339 try:
340 tar.__init__(empty)
341 except tarfile.ReadError:
342 self.assertTrue(tar.fileobj.closed)
343 else:
344 self.fail("ReadError not raised")
345 finally:
346 os.remove(empty)
347
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000348
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000349class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000350
351 mode="r|"
352
353 def test_fileobj_regular_file(self):
354 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
355 fobj = self.tar.extractfile(tarinfo)
356 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000357 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000358 "regular file extraction failed")
359
360 def test_provoke_stream_error(self):
361 tarinfos = self.tar.getmembers()
362 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000363 self.assertRaises(tarfile.StreamError, f.read)
364
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000365 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000366 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000367 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000368
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000369 while True:
370 t1 = tar1.next()
371 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000372 if t1 is None:
373 break
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000374 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000375
376 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000377 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000378 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000379
380 v1 = tar1.extractfile(t1)
381 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000382 if v1 is None:
383 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000384 self.assertTrue(v2 is not None, "stream.extractfile() failed")
385 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000386
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000387 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000388
Georg Brandla32e0a02006-10-24 16:54:16 +0000389
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000390class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000391
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000392 def _testfunc_file(self, name, mode):
393 try:
394 tarfile.open(name, mode)
395 except tarfile.ReadError:
396 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000397
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000398 def _testfunc_fileobj(self, name, mode):
399 try:
400 tarfile.open(name, mode, fileobj=open(name, "rb"))
401 except tarfile.ReadError:
402 self.fail()
403
404 def _test_modes(self, testfunc):
405 testfunc(tarname, "r")
406 testfunc(tarname, "r:")
407 testfunc(tarname, "r:*")
408 testfunc(tarname, "r|")
409 testfunc(tarname, "r|*")
410
411 if gzip:
412 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
413 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
414 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
415 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
416
417 testfunc(gzipname, "r")
418 testfunc(gzipname, "r:*")
419 testfunc(gzipname, "r:gz")
420 testfunc(gzipname, "r|*")
421 testfunc(gzipname, "r|gz")
422
423 if bz2:
424 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
425 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
426 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
427 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
428
429 testfunc(bz2name, "r")
430 testfunc(bz2name, "r:*")
431 testfunc(bz2name, "r:bz2")
432 testfunc(bz2name, "r|*")
433 testfunc(bz2name, "r|bz2")
434
435 def test_detect_file(self):
436 self._test_modes(self._testfunc_file)
437
438 def test_detect_fileobj(self):
439 self._test_modes(self._testfunc_fileobj)
440
Lars Gustäbel9a388632011-12-06 13:07:09 +0100441 def test_detect_stream_bz2(self):
442 # Originally, tarfile's stream detection looked for the string
443 # "BZh91" at the start of the file. This is incorrect because
444 # the '9' represents the blocksize (900kB). If the file was
445 # compressed using another blocksize autodetection fails.
446 if not bz2:
447 return
448
449 with open(tarname, "rb") as fobj:
450 data = fobj.read()
451
452 # Compress with blocksize 100kB, the file starts with "BZh11".
453 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
454 fobj.write(data)
455
456 self._testfunc_file(tmpname, "r|*")
457
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000458
459class MemberReadTest(ReadTest):
460
461 def _test_member(self, tarinfo, chksum=None, **kwargs):
462 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000463 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000464 "wrong md5sum for %s" % tarinfo.name)
465
466 kwargs["mtime"] = 07606136617
467 kwargs["uid"] = 1000
468 kwargs["gid"] = 100
469 if "old-v7" not in tarinfo.name:
470 # V7 tar can't handle alphabetic owners.
471 kwargs["uname"] = "tarfile"
472 kwargs["gname"] = "tarfile"
473 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000474 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000475 "wrong value in %s field of %s" % (k, tarinfo.name))
476
477 def test_find_regtype(self):
478 tarinfo = self.tar.getmember("ustar/regtype")
479 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
480
481 def test_find_conttype(self):
482 tarinfo = self.tar.getmember("ustar/conttype")
483 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
484
485 def test_find_dirtype(self):
486 tarinfo = self.tar.getmember("ustar/dirtype")
487 self._test_member(tarinfo, size=0)
488
489 def test_find_dirtype_with_size(self):
490 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
491 self._test_member(tarinfo, size=255)
492
493 def test_find_lnktype(self):
494 tarinfo = self.tar.getmember("ustar/lnktype")
495 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
496
497 def test_find_symtype(self):
498 tarinfo = self.tar.getmember("ustar/symtype")
499 self._test_member(tarinfo, size=0, linkname="regtype")
500
501 def test_find_blktype(self):
502 tarinfo = self.tar.getmember("ustar/blktype")
503 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
504
505 def test_find_chrtype(self):
506 tarinfo = self.tar.getmember("ustar/chrtype")
507 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
508
509 def test_find_fifotype(self):
510 tarinfo = self.tar.getmember("ustar/fifotype")
511 self._test_member(tarinfo, size=0)
512
513 def test_find_sparse(self):
514 tarinfo = self.tar.getmember("ustar/sparse")
515 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
516
517 def test_find_umlauts(self):
518 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
519 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
520
521 def test_find_ustar_longname(self):
522 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000523 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000524
525 def test_find_regtype_oldv7(self):
526 tarinfo = self.tar.getmember("misc/regtype-old-v7")
527 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
528
529 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000530 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000531 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
532 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
533
534
535class LongnameTest(ReadTest):
536
537 def test_read_longname(self):
538 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000539 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000540 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000541 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000542 except KeyError:
543 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000544 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000545
546 def test_read_longlink(self):
547 longname = self.subdir + "/" + "123/" * 125 + "longname"
548 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
549 try:
550 tarinfo = self.tar.getmember(longlink)
551 except KeyError:
552 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000553 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000554
555 def test_truncated_longname(self):
556 longname = self.subdir + "/" + "123/" * 125 + "longname"
557 tarinfo = self.tar.getmember(longname)
558 offset = tarinfo.offset
559 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000560 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000561 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
562
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000563 def test_header_offset(self):
564 # Test if the start offset of the TarInfo object includes
565 # the preceding extended header.
566 longname = self.subdir + "/" + "123/" * 125 + "longname"
567 offset = self.tar.getmember(longname).offset
568 fobj = open(tarname)
569 fobj.seek(offset)
570 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
571 self.assertEqual(tarinfo.type, self.longnametype)
572
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000573
574class GNUReadTest(LongnameTest):
575
576 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000577 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000578
579 def test_sparse_file(self):
580 tarinfo1 = self.tar.getmember("ustar/sparse")
581 fobj1 = self.tar.extractfile(tarinfo1)
582 tarinfo2 = self.tar.getmember("gnu/sparse")
583 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000584 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000585 "sparse file extraction failed")
586
587
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000588class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000589
590 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000591 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000592
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000593 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000594 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000595
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000596 tarinfo = tar.getmember("pax/regtype1")
597 self.assertEqual(tarinfo.uname, "foo")
598 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000599 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000600
601 tarinfo = tar.getmember("pax/regtype2")
602 self.assertEqual(tarinfo.uname, "")
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/regtype3")
607 self.assertEqual(tarinfo.uname, "tarfile")
608 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000609 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
610
611 def test_pax_number_fields(self):
612 # All following number fields are read from the pax header.
613 tar = tarfile.open(tarname, encoding="iso8859-1")
614 tarinfo = tar.getmember("pax/regtype4")
615 self.assertEqual(tarinfo.size, 7011)
616 self.assertEqual(tarinfo.uid, 123)
617 self.assertEqual(tarinfo.gid, 123)
618 self.assertEqual(tarinfo.mtime, 1041808783.0)
619 self.assertEqual(type(tarinfo.mtime), float)
620 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
621 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000622
623
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000624class WriteTestBase(unittest.TestCase):
625 # Put all write tests in here that are supposed to be tested
626 # in all possible mode combinations.
627
628 def test_fileobj_no_close(self):
629 fobj = StringIO.StringIO()
630 tar = tarfile.open(fileobj=fobj, mode=self.mode)
631 tar.addfile(tarfile.TarInfo("foo"))
632 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000633 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000634
635
636class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000637
638 mode = "w:"
639
640 def test_100_char_name(self):
641 # The name field in a tar header stores strings of at most 100 chars.
642 # If a string is shorter than 100 chars it has to be padded with '\0',
643 # which implies that a string of exactly 100 chars is stored without
644 # a trailing '\0'.
645 name = "0123456789" * 10
646 tar = tarfile.open(tmpname, self.mode)
647 t = tarfile.TarInfo(name)
648 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000649 tar.close()
650
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000651 tar = tarfile.open(tmpname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000652 self.assertTrue(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000653 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000654 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000655
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000656 def test_tar_size(self):
657 # Test for bug #1013882.
658 tar = tarfile.open(tmpname, self.mode)
659 path = os.path.join(TEMPDIR, "file")
660 fobj = open(path, "wb")
661 fobj.write("aaa")
662 fobj.close()
663 tar.add(path)
664 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000665 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000666 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000667
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000668 # The test_*_size tests test for bug #1167128.
669 def test_file_size(self):
670 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000671
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000672 path = os.path.join(TEMPDIR, "file")
673 fobj = open(path, "wb")
674 fobj.close()
675 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000676 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000677
678 fobj = open(path, "wb")
679 fobj.write("aaa")
680 fobj.close()
681 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000682 self.assertEqual(tarinfo.size, 3)
683
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000684 tar.close()
685
686 def test_directory_size(self):
687 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000688 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000689 try:
690 tar = tarfile.open(tmpname, self.mode)
691 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000692 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000693 finally:
694 os.rmdir(path)
695
696 def test_link_size(self):
697 if hasattr(os, "link"):
698 link = os.path.join(TEMPDIR, "link")
699 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000700 fobj = open(target, "wb")
701 fobj.write("aaa")
702 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000703 os.link(target, link)
704 try:
705 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel2ee9c6f2010-06-03 09:56:22 +0000706 # Record the link target in the inodes list.
707 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000708 tarinfo = tar.gettarinfo(link)
709 self.assertEqual(tarinfo.size, 0)
710 finally:
711 os.remove(target)
712 os.remove(link)
713
714 def test_symlink_size(self):
715 if hasattr(os, "symlink"):
716 path = os.path.join(TEMPDIR, "symlink")
717 os.symlink("link_target", path)
718 try:
719 tar = tarfile.open(tmpname, self.mode)
720 tarinfo = tar.gettarinfo(path)
721 self.assertEqual(tarinfo.size, 0)
722 finally:
723 os.remove(path)
724
725 def test_add_self(self):
726 # Test for #1257255.
727 dstname = os.path.abspath(tmpname)
728
729 tar = tarfile.open(tmpname, self.mode)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000730 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000731
732 tar.add(dstname)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000733 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000734
735 cwd = os.getcwd()
736 os.chdir(TEMPDIR)
737 tar.add(dstname)
738 os.chdir(cwd)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000739 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000740
Lars Gustäbel104490e2007-06-18 11:42:11 +0000741 def test_exclude(self):
742 tempdir = os.path.join(TEMPDIR, "exclude")
743 os.mkdir(tempdir)
744 try:
745 for name in ("foo", "bar", "baz"):
746 name = os.path.join(tempdir, name)
747 open(name, "wb").close()
748
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000749 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000750
751 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000752 with test_support.check_warnings(("use the filter argument",
753 DeprecationWarning)):
754 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Lars Gustäbel104490e2007-06-18 11:42:11 +0000755 tar.close()
756
757 tar = tarfile.open(tmpname, "r")
758 self.assertEqual(len(tar.getmembers()), 1)
759 self.assertEqual(tar.getnames()[0], "empty_dir")
760 finally:
761 shutil.rmtree(tempdir)
762
Lars Gustäbel21121e62009-09-12 10:28:15 +0000763 def test_filter(self):
764 tempdir = os.path.join(TEMPDIR, "filter")
765 os.mkdir(tempdir)
766 try:
767 for name in ("foo", "bar", "baz"):
768 name = os.path.join(tempdir, name)
769 open(name, "wb").close()
770
771 def filter(tarinfo):
772 if os.path.basename(tarinfo.name) == "bar":
773 return
774 tarinfo.uid = 123
775 tarinfo.uname = "foo"
776 return tarinfo
777
778 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
779 tar.add(tempdir, arcname="empty_dir", filter=filter)
780 tar.close()
781
782 tar = tarfile.open(tmpname, "r")
783 for tarinfo in tar:
784 self.assertEqual(tarinfo.uid, 123)
785 self.assertEqual(tarinfo.uname, "foo")
786 self.assertEqual(len(tar.getmembers()), 3)
787 tar.close()
788 finally:
789 shutil.rmtree(tempdir)
790
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000791 # Guarantee that stored pathnames are not modified. Don't
792 # remove ./ or ../ or double slashes. Still make absolute
793 # pathnames relative.
794 # For details see bug #6054.
795 def _test_pathname(self, path, cmp_path=None, dir=False):
796 # Create a tarfile with an empty member named path
797 # and compare the stored name with the original.
798 foo = os.path.join(TEMPDIR, "foo")
799 if not dir:
800 open(foo, "w").close()
801 else:
802 os.mkdir(foo)
803
804 tar = tarfile.open(tmpname, self.mode)
805 tar.add(foo, arcname=path)
806 tar.close()
807
808 tar = tarfile.open(tmpname, "r")
809 t = tar.next()
810 tar.close()
811
812 if not dir:
813 os.remove(foo)
814 else:
815 os.rmdir(foo)
816
817 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
818
819 def test_pathnames(self):
820 self._test_pathname("foo")
821 self._test_pathname(os.path.join("foo", ".", "bar"))
822 self._test_pathname(os.path.join("foo", "..", "bar"))
823 self._test_pathname(os.path.join(".", "foo"))
824 self._test_pathname(os.path.join(".", "foo", "."))
825 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
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
833 self._test_pathname("foo" + os.sep + os.sep + "bar")
834 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
835
836 def test_abs_pathnames(self):
837 if sys.platform == "win32":
838 self._test_pathname("C:\\foo", "foo")
839 else:
840 self._test_pathname("/foo", "foo")
841 self._test_pathname("///foo", "foo")
842
843 def test_cwd(self):
844 # Test adding the current working directory.
845 cwd = os.getcwd()
846 os.chdir(TEMPDIR)
847 try:
848 open("foo", "w").close()
849
850 tar = tarfile.open(tmpname, self.mode)
851 tar.add(".")
852 tar.close()
853
854 tar = tarfile.open(tmpname, "r")
855 for t in tar:
Serhiy Storchaka88761452012-12-28 00:32:19 +0200856 self.assertTrue(t.name == "." or t.name.startswith("./"))
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000857 tar.close()
858 finally:
859 os.chdir(cwd)
860
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +0800861 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +0800862 def test_extractall_symlinks(self):
863 # Test if extractall works properly when tarfile contains symlinks
864 tempdir = os.path.join(TEMPDIR, "testsymlinks")
865 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
866 os.mkdir(tempdir)
867 try:
868 source_file = os.path.join(tempdir,'source')
869 target_file = os.path.join(tempdir,'symlink')
870 with open(source_file,'w') as f:
871 f.write('something\n')
872 os.symlink(source_file, target_file)
873 tar = tarfile.open(temparchive,'w')
874 tar.add(source_file, arcname=os.path.basename(source_file))
875 tar.add(target_file, arcname=os.path.basename(target_file))
876 tar.close()
877 # Let's extract it to the location which contains the symlink
878 tar = tarfile.open(temparchive,'r')
879 # this should not raise OSError: [Errno 17] File exists
880 try:
881 tar.extractall(path=tempdir)
882 except OSError:
883 self.fail("extractall failed with symlinked files")
884 finally:
885 tar.close()
886 finally:
887 os.unlink(temparchive)
888 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000889
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +0800890 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
891 def test_extractall_broken_symlinks(self):
892 # Test if extractall works properly when tarfile contains broken
893 # symlinks
894 tempdir = os.path.join(TEMPDIR, "testsymlinks")
895 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
896 os.mkdir(tempdir)
897 try:
898 source_file = os.path.join(tempdir,'source')
899 target_file = os.path.join(tempdir,'symlink')
900 with open(source_file,'w') as f:
901 f.write('something\n')
902 os.symlink(source_file, target_file)
903 tar = tarfile.open(temparchive,'w')
904 tar.add(target_file, arcname=os.path.basename(target_file))
905 tar.close()
906 # remove the real file
907 os.unlink(source_file)
908 # Let's extract it to the location which contains the symlink
909 tar = tarfile.open(temparchive,'r')
910 # this should not raise OSError: [Errno 17] File exists
911 try:
912 tar.extractall(path=tempdir)
913 except OSError:
914 self.fail("extractall failed with broken symlinked files")
915 finally:
916 tar.close()
917 finally:
918 os.unlink(temparchive)
919 shutil.rmtree(tempdir)
920
921 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
922 def test_extractall_hardlinks(self):
923 # Test if extractall works properly when tarfile contains symlinks
924 tempdir = os.path.join(TEMPDIR, "testsymlinks")
925 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
926 os.mkdir(tempdir)
927 try:
928 source_file = os.path.join(tempdir,'source')
929 target_file = os.path.join(tempdir,'symlink')
930 with open(source_file,'w') as f:
931 f.write('something\n')
932 os.link(source_file, target_file)
933 tar = tarfile.open(temparchive,'w')
934 tar.add(source_file, arcname=os.path.basename(source_file))
935 tar.add(target_file, arcname=os.path.basename(target_file))
936 tar.close()
937 # Let's extract it to the location which contains the symlink
938 tar = tarfile.open(temparchive,'r')
939 # this should not raise OSError: [Errno 17] File exists
940 try:
941 tar.extractall(path=tempdir)
942 except OSError:
943 self.fail("extractall failed with linked files")
944 finally:
945 tar.close()
946 finally:
947 os.unlink(temparchive)
948 shutil.rmtree(tempdir)
949
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000950class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000951
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000952 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +0000953
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000954 def test_stream_padding(self):
955 # Test for bug #1543303.
956 tar = tarfile.open(tmpname, self.mode)
957 tar.close()
958
959 if self.mode.endswith("gz"):
960 fobj = gzip.GzipFile(tmpname)
961 data = fobj.read()
962 fobj.close()
963 elif self.mode.endswith("bz2"):
964 dec = bz2.BZ2Decompressor()
965 data = open(tmpname, "rb").read()
966 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000967 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000968 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +0000969 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000970 fobj = open(tmpname, "rb")
971 data = fobj.read()
972 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +0000973
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000974 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +0000975 "incorrect zero padding")
976
Lars Gustäbel5c4c4612010-04-29 15:23:38 +0000977 def test_file_mode(self):
978 # Test for issue #8464: Create files with correct
979 # permissions.
980 if sys.platform == "win32" or not hasattr(os, "umask"):
981 return
982
983 if os.path.exists(tmpname):
984 os.remove(tmpname)
985
986 original_umask = os.umask(0022)
987 try:
988 tar = tarfile.open(tmpname, self.mode)
989 tar.close()
990 mode = os.stat(tmpname).st_mode & 0777
991 self.assertEqual(mode, 0644, "wrong file permissions")
992 finally:
993 os.umask(original_umask)
994
Lars Gustäbel7d4d0742011-12-21 19:27:50 +0100995 def test_issue13639(self):
996 try:
997 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
998 pass
999 except UnicodeDecodeError:
1000 self.fail("_Stream failed to write unicode filename")
1001
Neal Norwitz8a519392006-08-21 17:59:46 +00001002
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001003class GNUWriteTest(unittest.TestCase):
1004 # This testcase checks for correct creation of GNU Longname
1005 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001006
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001007 def _length(self, s):
1008 blocks, remainder = divmod(len(s) + 1, 512)
1009 if remainder:
1010 blocks += 1
1011 return blocks * 512
1012
1013 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001014 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001015 count = 512
1016
1017 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001018 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001019 count += 512
1020 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001021 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001022 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001023 count += 512
1024 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001025 return count
1026
1027 def _test(self, name, link=None):
1028 tarinfo = tarfile.TarInfo(name)
1029 if link:
1030 tarinfo.linkname = link
1031 tarinfo.type = tarfile.LNKTYPE
1032
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001033 tar = tarfile.open(tmpname, "w")
1034 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +00001035 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001036
1037 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +00001038 v2 = tar.offset
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001039 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001040
Georg Brandl87fa5592006-12-06 22:21:18 +00001041 tar.close()
1042
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001043 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +00001044 member = tar.next()
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001045 self.assertIsNotNone(member,
1046 "unable to read longname member")
1047 self.assertEqual(tarinfo.name, member.name,
1048 "unable to read longname member")
1049 self.assertEqual(tarinfo.linkname, member.linkname,
1050 "unable to read longname member")
Georg Brandl87fa5592006-12-06 22:21:18 +00001051
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001052 def test_longname_1023(self):
1053 self._test(("longnam/" * 127) + "longnam")
1054
1055 def test_longname_1024(self):
1056 self._test(("longnam/" * 127) + "longname")
1057
1058 def test_longname_1025(self):
1059 self._test(("longnam/" * 127) + "longname_")
1060
1061 def test_longlink_1023(self):
1062 self._test("name", ("longlnk/" * 127) + "longlnk")
1063
1064 def test_longlink_1024(self):
1065 self._test("name", ("longlnk/" * 127) + "longlink")
1066
1067 def test_longlink_1025(self):
1068 self._test("name", ("longlnk/" * 127) + "longlink_")
1069
1070 def test_longnamelink_1023(self):
1071 self._test(("longnam/" * 127) + "longnam",
1072 ("longlnk/" * 127) + "longlnk")
1073
1074 def test_longnamelink_1024(self):
1075 self._test(("longnam/" * 127) + "longname",
1076 ("longlnk/" * 127) + "longlink")
1077
1078 def test_longnamelink_1025(self):
1079 self._test(("longnam/" * 127) + "longname_",
1080 ("longlnk/" * 127) + "longlink_")
1081
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001082
1083class HardlinkTest(unittest.TestCase):
1084 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001085
1086 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001087 self.foo = os.path.join(TEMPDIR, "foo")
1088 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001089
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001090 fobj = open(self.foo, "wb")
1091 fobj.write("foo")
1092 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +00001093
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001094 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001095
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001096 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001097 self.tar.add(self.foo)
1098
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001099 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001100 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001101 os.remove(self.foo)
1102 os.remove(self.bar)
1103
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001104 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001105 # The same name will be added as a REGTYPE every
1106 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001107 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001108 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001109 "add file as regular failed")
1110
1111 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001112 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001113 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001114 "add file as hardlink failed")
1115
1116 def test_dereference_hardlink(self):
1117 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001118 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001119 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001120 "dereferencing hardlink failed")
1121
Neal Norwitza4f651a2004-07-20 22:07:44 +00001122
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001123class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001124
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001125 def _test(self, name, link=None):
1126 # See GNUWriteTest.
1127 tarinfo = tarfile.TarInfo(name)
1128 if link:
1129 tarinfo.linkname = link
1130 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001131
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001132 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
1133 tar.addfile(tarinfo)
1134 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001135
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001136 tar = tarfile.open(tmpname)
1137 if link:
1138 l = tar.getmembers()[0].linkname
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001139 self.assertTrue(link == l, "PAX longlink creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001140 else:
1141 n = tar.getmembers()[0].name
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001142 self.assertTrue(name == n, "PAX longname creation failed")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001143
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001144 def test_pax_global_header(self):
1145 pax_headers = {
1146 u"foo": u"bar",
1147 u"uid": u"0",
1148 u"mtime": u"1.23",
1149 u"test": u"äöü",
1150 u"äöü": u"test"}
1151
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001152 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001153 pax_headers=pax_headers)
1154 tar.addfile(tarfile.TarInfo("test"))
1155 tar.close()
1156
1157 # Test if the global header was written correctly.
1158 tar = tarfile.open(tmpname, encoding="iso8859-1")
1159 self.assertEqual(tar.pax_headers, pax_headers)
1160 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1161
1162 # Test if all the fields are unicode.
1163 for key, val in tar.pax_headers.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001164 self.assertTrue(type(key) is unicode)
1165 self.assertTrue(type(val) is unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001166 if key in tarfile.PAX_NUMBER_FIELDS:
1167 try:
1168 tarfile.PAX_NUMBER_FIELDS[key](val)
1169 except (TypeError, ValueError):
1170 self.fail("unable to convert pax header field")
1171
1172 def test_pax_extended_header(self):
1173 # The fields from the pax header have priority over the
1174 # TarInfo.
1175 pax_headers = {u"path": u"foo", u"uid": u"123"}
1176
1177 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1178 t = tarfile.TarInfo()
1179 t.name = u"äöü" # non-ASCII
1180 t.uid = 8**8 # too large
1181 t.pax_headers = pax_headers
1182 tar.addfile(t)
1183 tar.close()
1184
1185 tar = tarfile.open(tmpname, encoding="iso8859-1")
1186 t = tar.getmembers()[0]
1187 self.assertEqual(t.pax_headers, pax_headers)
1188 self.assertEqual(t.name, "foo")
1189 self.assertEqual(t.uid, 123)
1190
1191
1192class UstarUnicodeTest(unittest.TestCase):
1193 # All *UnicodeTests FIXME
1194
1195 format = tarfile.USTAR_FORMAT
1196
1197 def test_iso8859_1_filename(self):
1198 self._test_unicode_filename("iso8859-1")
1199
1200 def test_utf7_filename(self):
1201 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001202
1203 def test_utf8_filename(self):
1204 self._test_unicode_filename("utf8")
1205
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001206 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001207 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
1208 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001209 tar.addfile(tarfile.TarInfo(name))
1210 tar.close()
1211
1212 tar = tarfile.open(tmpname, encoding=encoding)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001213 self.assertTrue(type(tar.getnames()[0]) is not unicode)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001214 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001215 tar.close()
1216
1217 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001218 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1219 tarinfo = tarfile.TarInfo()
1220
1221 tarinfo.name = "äöü"
1222 if self.format == tarfile.PAX_FORMAT:
1223 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1224 else:
1225 tar.addfile(tarinfo)
1226
1227 tarinfo.name = u"äöü"
1228 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1229
1230 tarinfo.name = "foo"
1231 tarinfo.uname = u"äöü"
1232 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1233
1234 def test_unicode_argument(self):
1235 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1236 for t in tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001237 self.assertTrue(type(t.name) is str)
1238 self.assertTrue(type(t.linkname) is str)
1239 self.assertTrue(type(t.uname) is str)
1240 self.assertTrue(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001241 tar.close()
1242
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001243 def test_uname_unicode(self):
1244 for name in (u"äöü", "äöü"):
1245 t = tarfile.TarInfo("foo")
1246 t.uname = name
1247 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001248
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001249 fobj = StringIO.StringIO()
1250 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
1251 tar.addfile(t)
1252 tar.close()
1253 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001254
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001255 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1256 t = tar.getmember("foo")
1257 self.assertEqual(t.uname, "äöü")
1258 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001259
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001260
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001261class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001262
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001263 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001264
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001265
1266class PaxUnicodeTest(UstarUnicodeTest):
1267
1268 format = tarfile.PAX_FORMAT
1269
1270 def _create_unicode_name(self, name):
1271 tar = tarfile.open(tmpname, "w", format=self.format)
1272 t = tarfile.TarInfo()
1273 t.pax_headers["path"] = name
1274 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001275 tar.close()
1276
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001277 def test_error_handlers(self):
1278 # Test if the unicode error handlers work correctly for characters
1279 # that cannot be expressed in a given encoding.
1280 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001281
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001282 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1283 ("replace", "???"), ("ignore", "")):
1284 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1285 errors=handler)
1286 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001287
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001288 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1289 encoding="ascii", errors="strict")
1290
1291 def test_error_handler_utf8(self):
1292 # Create a pathname that has one component representable using
1293 # iso8859-1 and the other only in iso8859-15.
1294 self._create_unicode_name(u"äöü/¤")
1295
1296 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1297 errors="utf-8")
1298 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001299
Georg Brandlded1c4d2006-12-20 11:55:16 +00001300
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001301class AppendTest(unittest.TestCase):
1302 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001303
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001304 def setUp(self):
1305 self.tarname = tmpname
1306 if os.path.exists(self.tarname):
1307 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001308
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001309 def _add_testfile(self, fileobj=None):
1310 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1311 tar.addfile(tarfile.TarInfo("bar"))
1312 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001313
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001314 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001315 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001316 t = src.getmember("ustar/regtype")
1317 t.name = "foo"
1318 f = src.extractfile(t)
1319 tar = tarfile.open(self.tarname, mode)
1320 tar.addfile(t, f)
1321 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001322
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001323 def _test(self, names=["bar"], fileobj=None):
1324 tar = tarfile.open(self.tarname, fileobj=fileobj)
1325 self.assertEqual(tar.getnames(), names)
1326
1327 def test_non_existing(self):
1328 self._add_testfile()
1329 self._test()
1330
1331 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001332 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001333 self._add_testfile()
1334 self._test()
1335
1336 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001337 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001338 self._add_testfile(fobj)
1339 fobj.seek(0)
1340 self._test(fileobj=fobj)
1341
1342 def test_fileobj(self):
1343 self._create_testtar()
1344 data = open(self.tarname).read()
1345 fobj = StringIO.StringIO(data)
1346 self._add_testfile(fobj)
1347 fobj.seek(0)
1348 self._test(names=["foo", "bar"], fileobj=fobj)
1349
1350 def test_existing(self):
1351 self._create_testtar()
1352 self._add_testfile()
1353 self._test(names=["foo", "bar"])
1354
1355 def test_append_gz(self):
1356 if gzip is None:
1357 return
1358 self._create_testtar("w:gz")
1359 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1360
1361 def test_append_bz2(self):
1362 if bz2 is None:
1363 return
1364 self._create_testtar("w:bz2")
1365 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1366
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001367 # Append mode is supposed to fail if the tarfile to append to
1368 # does not end with a zero block.
1369 def _test_error(self, data):
1370 open(self.tarname, "wb").write(data)
1371 self.assertRaises(tarfile.ReadError, self._add_testfile)
1372
1373 def test_null(self):
1374 self._test_error("")
1375
1376 def test_incomplete(self):
1377 self._test_error("\0" * 13)
1378
1379 def test_premature_eof(self):
1380 data = tarfile.TarInfo("foo").tobuf()
1381 self._test_error(data)
1382
1383 def test_trailing_garbage(self):
1384 data = tarfile.TarInfo("foo").tobuf()
1385 self._test_error(data + "\0" * 13)
1386
1387 def test_invalid(self):
1388 self._test_error("a" * 512)
1389
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001390
1391class LimitsTest(unittest.TestCase):
1392
1393 def test_ustar_limits(self):
1394 # 100 char name
1395 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001396 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001397
1398 # 101 char name that cannot be stored
1399 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001400 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001401
1402 # 256 char name with a slash at pos 156
1403 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001404 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001405
1406 # 256 char name that cannot be stored
1407 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001408 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001409
1410 # 512 char name
1411 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001412 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001413
1414 # 512 char linkname
1415 tarinfo = tarfile.TarInfo("longlink")
1416 tarinfo.linkname = "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 # uid > 8 digits
1420 tarinfo = tarfile.TarInfo("name")
1421 tarinfo.uid = 010000000
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 def test_gnu_limits(self):
1425 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001426 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001427
1428 tarinfo = tarfile.TarInfo("longlink")
1429 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001430 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001431
1432 # uid >= 256 ** 7
1433 tarinfo = tarfile.TarInfo("name")
1434 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001435 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001436
1437 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001438 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001439 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001440
1441 tarinfo = tarfile.TarInfo("longlink")
1442 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001443 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001444
1445 tarinfo = tarfile.TarInfo("name")
1446 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001447 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001448
1449
Lars Gustäbel64581042010-03-03 11:55:48 +00001450class ContextManagerTest(unittest.TestCase):
1451
1452 def test_basic(self):
1453 with tarfile.open(tarname) as tar:
1454 self.assertFalse(tar.closed, "closed inside runtime context")
1455 self.assertTrue(tar.closed, "context manager failed")
1456
1457 def test_closed(self):
1458 # The __enter__() method is supposed to raise IOError
1459 # if the TarFile object is already closed.
1460 tar = tarfile.open(tarname)
1461 tar.close()
1462 with self.assertRaises(IOError):
1463 with tar:
1464 pass
1465
1466 def test_exception(self):
1467 # Test if the IOError exception is passed through properly.
1468 with self.assertRaises(Exception) as exc:
1469 with tarfile.open(tarname) as tar:
1470 raise IOError
1471 self.assertIsInstance(exc.exception, IOError,
1472 "wrong exception raised in context manager")
1473 self.assertTrue(tar.closed, "context manager failed")
1474
1475 def test_no_eof(self):
1476 # __exit__() must not write end-of-archive blocks if an
1477 # exception was raised.
1478 try:
1479 with tarfile.open(tmpname, "w") as tar:
1480 raise Exception
1481 except:
1482 pass
1483 self.assertEqual(os.path.getsize(tmpname), 0,
1484 "context manager wrote an end-of-archive block")
1485 self.assertTrue(tar.closed, "context manager failed")
1486
1487 def test_eof(self):
1488 # __exit__() must write end-of-archive blocks, i.e. call
1489 # TarFile.close() if there was no error.
1490 with tarfile.open(tmpname, "w"):
1491 pass
1492 self.assertNotEqual(os.path.getsize(tmpname), 0,
1493 "context manager wrote no end-of-archive block")
1494
1495 def test_fileobj(self):
1496 # Test that __exit__() did not close the external file
1497 # object.
1498 fobj = open(tmpname, "wb")
1499 try:
1500 with tarfile.open(fileobj=fobj, mode="w") as tar:
1501 raise Exception
1502 except:
1503 pass
1504 self.assertFalse(fobj.closed, "external file object was closed")
1505 self.assertTrue(tar.closed, "context manager failed")
1506 fobj.close()
1507
1508
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001509class LinkEmulationTest(ReadTest):
1510
1511 # Test for issue #8741 regression. On platforms that do not support
1512 # symbolic or hard links tarfile tries to extract these types of members as
1513 # the regular files they point to.
1514 def _test_link_extraction(self, name):
1515 self.tar.extract(name, TEMPDIR)
1516 data = open(os.path.join(TEMPDIR, name), "rb").read()
1517 self.assertEqual(md5sum(data), md5_regtype)
1518
1519 def test_hardlink_extraction1(self):
1520 self._test_link_extraction("ustar/lnktype")
1521
1522 def test_hardlink_extraction2(self):
1523 self._test_link_extraction("./ustar/linktest2/lnktype")
1524
1525 def test_symlink_extraction1(self):
1526 self._test_link_extraction("ustar/symtype")
1527
1528 def test_symlink_extraction2(self):
1529 self._test_link_extraction("./ustar/linktest2/symtype")
1530
1531
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001532class GzipMiscReadTest(MiscReadTest):
1533 tarname = gzipname
1534 mode = "r:gz"
1535class GzipUstarReadTest(UstarReadTest):
1536 tarname = gzipname
1537 mode = "r:gz"
1538class GzipStreamReadTest(StreamReadTest):
1539 tarname = gzipname
1540 mode = "r|gz"
1541class GzipWriteTest(WriteTest):
1542 mode = "w:gz"
1543class GzipStreamWriteTest(StreamWriteTest):
1544 mode = "w|gz"
1545
1546
1547class Bz2MiscReadTest(MiscReadTest):
1548 tarname = bz2name
1549 mode = "r:bz2"
1550class Bz2UstarReadTest(UstarReadTest):
1551 tarname = bz2name
1552 mode = "r:bz2"
1553class Bz2StreamReadTest(StreamReadTest):
1554 tarname = bz2name
1555 mode = "r|bz2"
1556class Bz2WriteTest(WriteTest):
1557 mode = "w:bz2"
1558class Bz2StreamWriteTest(StreamWriteTest):
1559 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001560
Lars Gustäbel2020a592009-03-22 20:09:33 +00001561class Bz2PartialReadTest(unittest.TestCase):
1562 # Issue5068: The _BZ2Proxy.read() method loops forever
1563 # on an empty or partial bzipped file.
1564
1565 def _test_partial_input(self, mode):
1566 class MyStringIO(StringIO.StringIO):
1567 hit_eof = False
1568 def read(self, n):
1569 if self.hit_eof:
1570 raise AssertionError("infinite loop detected in tarfile.open()")
1571 self.hit_eof = self.pos == self.len
1572 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001573 def seek(self, *args):
1574 self.hit_eof = False
1575 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001576
1577 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1578 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001579 try:
1580 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1581 except tarfile.ReadError:
1582 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001583
1584 def test_partial_input(self):
1585 self._test_partial_input("r")
1586
1587 def test_partial_input_bz2(self):
1588 self._test_partial_input("r:bz2")
1589
1590
Neal Norwitz996acf12003-02-17 14:51:41 +00001591def test_main():
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001592 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001593
Walter Dörwald21d3a322003-05-01 17:45:56 +00001594 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001595 UstarReadTest,
1596 MiscReadTest,
1597 StreamReadTest,
1598 DetectReadTest,
1599 MemberReadTest,
1600 GNUReadTest,
1601 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001602 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001603 StreamWriteTest,
1604 GNUWriteTest,
1605 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001606 UstarUnicodeTest,
1607 GNUUnicodeTest,
1608 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001609 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001610 LimitsTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001611 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001612 ]
1613
Neal Norwitza4f651a2004-07-20 22:07:44 +00001614 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001615 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001616 else:
1617 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001618
1619 fobj = open(tarname, "rb")
1620 data = fobj.read()
1621 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001622
Walter Dörwald21d3a322003-05-01 17:45:56 +00001623 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001624 # Create testtar.tar.gz and add gzip-specific tests.
1625 tar = gzip.open(gzipname, "wb")
1626 tar.write(data)
1627 tar.close()
1628
1629 tests += [
1630 GzipMiscReadTest,
1631 GzipUstarReadTest,
1632 GzipStreamReadTest,
1633 GzipWriteTest,
1634 GzipStreamWriteTest,
1635 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001636
1637 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001638 # Create testtar.tar.bz2 and add bz2-specific tests.
1639 tar = bz2.BZ2File(bz2name, "wb")
1640 tar.write(data)
1641 tar.close()
1642
1643 tests += [
1644 Bz2MiscReadTest,
1645 Bz2UstarReadTest,
1646 Bz2StreamReadTest,
1647 Bz2WriteTest,
1648 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001649 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001650 ]
1651
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001652 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001653 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001654 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001655 if os.path.exists(TEMPDIR):
1656 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001657
Neal Norwitz996acf12003-02-17 14:51:41 +00001658if __name__ == "__main__":
1659 test_main()