blob: 30d9e07e35d2dfc6d6d8b9b883636a2f28b5f0ad [file] [log] [blame]
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001# Copyright (C) 2003 Python Software Foundation
2
3import unittest
4import shutil
5import tempfile
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +00006import sys
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +00007import stat
Brett Cannon1c3fa182004-06-19 21:11:35 +00008import os
9import os.path
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
11from test.support import TESTFN
Tarek Ziadé396fad72010-02-23 05:30:31 +000012from os.path import splitdrive
13from distutils.spawn import find_executable, spawn
14from shutil import (_make_tarball, _make_zipfile, make_archive,
15 register_archive_format, unregister_archive_format,
Tarek Ziadé6ac91722010-04-28 17:51:36 +000016 get_archive_formats, Error, unpack_archive,
17 register_unpack_format, RegistryError,
18 unregister_unpack_format, get_unpack_formats)
Tarek Ziadé396fad72010-02-23 05:30:31 +000019import tarfile
20import warnings
21
22from test import support
23from test.support import TESTFN, check_warnings, captured_stdout
24
Tarek Ziadéffa155a2010-04-29 13:34:35 +000025try:
26 import bz2
27 BZ2_SUPPORTED = True
28except ImportError:
29 BZ2_SUPPORTED = False
30
Antoine Pitrou7fff0962009-05-01 21:09:44 +000031TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000032
Tarek Ziadé396fad72010-02-23 05:30:31 +000033try:
34 import grp
35 import pwd
36 UID_GID_SUPPORT = True
37except ImportError:
38 UID_GID_SUPPORT = False
39
40try:
41 import zlib
42except ImportError:
43 zlib = None
44
45try:
46 import zipfile
47 ZIP_SUPPORT = True
48except ImportError:
49 ZIP_SUPPORT = find_executable('zip')
50
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000051class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000052
53 def setUp(self):
54 super(TestShutil, self).setUp()
55 self.tempdirs = []
56
57 def tearDown(self):
58 super(TestShutil, self).tearDown()
59 while self.tempdirs:
60 d = self.tempdirs.pop()
61 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
62
63 def write_file(self, path, content='xxx'):
64 """Writes a file in the given path.
65
66
67 path can be a string or a sequence.
68 """
69 if isinstance(path, (list, tuple)):
70 path = os.path.join(*path)
71 f = open(path, 'w')
72 try:
73 f.write(content)
74 finally:
75 f.close()
76
77 def mkdtemp(self):
78 """Create a temporary directory that will be cleaned up.
79
80 Returns the path of the directory.
81 """
82 d = tempfile.mkdtemp()
83 self.tempdirs.append(d)
84 return d
Tarek Ziadé5340db32010-04-19 22:30:51 +000085
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000086 def test_rmtree_errors(self):
87 # filename is guaranteed not to exist
88 filename = tempfile.mktemp()
89 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000090
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000091 # See bug #1071513 for why we don't run this on cygwin
92 # and bug #1076467 for why we don't run this as root.
93 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000094 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000095 def test_on_error(self):
96 self.errorState = 0
97 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000098 self.childpath = os.path.join(TESTFN, 'a')
99 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000100 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000101 old_dir_mode = os.stat(TESTFN).st_mode
102 old_child_mode = os.stat(self.childpath).st_mode
103 # Make unwritable.
104 os.chmod(self.childpath, stat.S_IREAD)
105 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000106
107 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000108 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000109 self.assertEqual(self.errorState, 2,
110 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000111
Tim Peters4590c002004-11-01 02:40:52 +0000112 # Make writable again.
113 os.chmod(TESTFN, old_dir_mode)
114 os.chmod(self.childpath, old_child_mode)
115
116 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000117 shutil.rmtree(TESTFN)
118
119 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000120 # test_rmtree_errors deliberately runs rmtree
121 # on a directory that is chmod 400, which will fail.
122 # This function is run when shutil.rmtree fails.
123 # 99.9% of the time it initially fails to remove
124 # a file in the directory, so the first time through
125 # func is os.remove.
126 # However, some Linux machines running ZFS on
127 # FUSE experienced a failure earlier in the process
128 # at os.listdir. The first failure may legally
129 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000130 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000131 if func is os.remove:
132 self.assertEqual(arg, self.childpath)
133 else:
134 self.assertIs(func, os.listdir,
135 "func must be either os.remove or os.listdir")
136 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000137 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000138 self.errorState = 1
139 else:
140 self.assertEqual(func, os.rmdir)
141 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000142 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000143 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000144
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000145 def test_rmtree_dont_delete_file(self):
146 # When called on a file instead of a directory, don't delete it.
147 handle, path = tempfile.mkstemp()
148 os.fdopen(handle).close()
149 self.assertRaises(OSError, shutil.rmtree, path)
150 os.remove(path)
151
Tarek Ziadé5340db32010-04-19 22:30:51 +0000152 def _write_data(self, path, data):
153 f = open(path, "w")
154 f.write(data)
155 f.close()
156
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158
159 def read_data(path):
160 f = open(path)
161 data = f.read()
162 f.close()
163 return data
164
165 src_dir = tempfile.mkdtemp()
166 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000167 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000168 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000169 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000170
171 try:
172 shutil.copytree(src_dir, dst_dir)
173 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
174 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
175 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
176 'test.txt')))
177 actual = read_data(os.path.join(dst_dir, 'test.txt'))
178 self.assertEqual(actual, '123')
179 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
180 self.assertEqual(actual, '456')
181 finally:
182 for path in (
183 os.path.join(src_dir, 'test.txt'),
184 os.path.join(dst_dir, 'test.txt'),
185 os.path.join(src_dir, 'test_dir', 'test.txt'),
186 os.path.join(dst_dir, 'test_dir', 'test.txt'),
187 ):
188 if os.path.exists(path):
189 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000190 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000191 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000192 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000194 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000195
Georg Brandl2ee470f2008-07-16 12:55:28 +0000196 def test_copytree_with_exclude(self):
197
Georg Brandl2ee470f2008-07-16 12:55:28 +0000198 def read_data(path):
199 f = open(path)
200 data = f.read()
201 f.close()
202 return data
203
204 # creating data
205 join = os.path.join
206 exists = os.path.exists
207 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000208 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000209 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000210 self._write_data(join(src_dir, 'test.txt'), '123')
211 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000212 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000213 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000214 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000215 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000216 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
217 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000218 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
219 '456')
220 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
221 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000222
223
224 # testing glob-like patterns
225 try:
226 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
227 shutil.copytree(src_dir, dst_dir, ignore=patterns)
228 # checking the result: some elements should not be copied
229 self.assertTrue(exists(join(dst_dir, 'test.txt')))
230 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
231 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
232 finally:
233 if os.path.exists(dst_dir):
234 shutil.rmtree(dst_dir)
235 try:
236 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
237 shutil.copytree(src_dir, dst_dir, ignore=patterns)
238 # checking the result: some elements should not be copied
239 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
240 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
241 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
242 finally:
243 if os.path.exists(dst_dir):
244 shutil.rmtree(dst_dir)
245
246 # testing callable-style
247 try:
248 def _filter(src, names):
249 res = []
250 for name in names:
251 path = os.path.join(src, name)
252
253 if (os.path.isdir(path) and
254 path.split()[-1] == 'subdir'):
255 res.append(name)
256 elif os.path.splitext(path)[-1] in ('.py'):
257 res.append(name)
258 return res
259
260 shutil.copytree(src_dir, dst_dir, ignore=_filter)
261
262 # checking the result: some elements should not be copied
263 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
264 'test.py')))
265 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
266
267 finally:
268 if os.path.exists(dst_dir):
269 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000270 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000271 shutil.rmtree(src_dir)
272 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000273
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000274 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000275 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000276 # Temporarily disable test on Windows.
277 if os.name == 'nt':
278 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000279 # bug 851123.
280 os.mkdir(TESTFN)
281 src = os.path.join(TESTFN, 'cheese')
282 dst = os.path.join(TESTFN, 'shop')
283 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000284 with open(src, 'w') as f:
285 f.write('cheddar')
286 os.link(src, dst)
287 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
288 with open(src, 'r') as f:
289 self.assertEqual(f.read(), 'cheddar')
290 os.remove(dst)
291 finally:
292 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000293
Brian Curtin3b4499c2010-12-28 14:31:47 +0000294 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000295 def test_dont_copy_file_onto_symlink_to_itself(self):
296 # bug 851123.
297 os.mkdir(TESTFN)
298 src = os.path.join(TESTFN, 'cheese')
299 dst = os.path.join(TESTFN, 'shop')
300 try:
301 with open(src, 'w') as f:
302 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000303 # Using `src` here would mean we end up with a symlink pointing
304 # to TESTFN/TESTFN/cheese, while it should point at
305 # TESTFN/cheese.
306 os.symlink('cheese', dst)
307 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000308 with open(src, 'r') as f:
309 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000310 os.remove(dst)
311 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000312 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000313
Brian Curtin3b4499c2010-12-28 14:31:47 +0000314 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000315 def test_rmtree_on_symlink(self):
316 # bug 1669.
317 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000318 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000319 src = os.path.join(TESTFN, 'cheese')
320 dst = os.path.join(TESTFN, 'shop')
321 os.mkdir(src)
322 os.symlink(src, dst)
323 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000324 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000325 shutil.rmtree(TESTFN, ignore_errors=True)
326
327 if hasattr(os, "mkfifo"):
328 # Issue #3002: copyfile and copytree block indefinitely on named pipes
329 def test_copyfile_named_pipe(self):
330 os.mkfifo(TESTFN)
331 try:
332 self.assertRaises(shutil.SpecialFileError,
333 shutil.copyfile, TESTFN, TESTFN2)
334 self.assertRaises(shutil.SpecialFileError,
335 shutil.copyfile, __file__, TESTFN)
336 finally:
337 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000338
Brian Curtin3b4499c2010-12-28 14:31:47 +0000339 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000340 def test_copytree_named_pipe(self):
341 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000342 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000343 subdir = os.path.join(TESTFN, "subdir")
344 os.mkdir(subdir)
345 pipe = os.path.join(subdir, "mypipe")
346 os.mkfifo(pipe)
347 try:
348 shutil.copytree(TESTFN, TESTFN2)
349 except shutil.Error as e:
350 errors = e.args[0]
351 self.assertEqual(len(errors), 1)
352 src, dst, error_msg = errors[0]
353 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
354 else:
355 self.fail("shutil.Error should have been raised")
356 finally:
357 shutil.rmtree(TESTFN, ignore_errors=True)
358 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000359
Tarek Ziadé5340db32010-04-19 22:30:51 +0000360 def test_copytree_special_func(self):
361
362 src_dir = self.mkdtemp()
363 dst_dir = os.path.join(self.mkdtemp(), 'destination')
364 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
365 os.mkdir(os.path.join(src_dir, 'test_dir'))
366 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
367
368 copied = []
369 def _copy(src, dst):
370 copied.append((src, dst))
371
372 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000373 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000374
Brian Curtin3b4499c2010-12-28 14:31:47 +0000375 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000376 def test_copytree_dangling_symlinks(self):
377
378 # a dangling symlink raises an error at the end
379 src_dir = self.mkdtemp()
380 dst_dir = os.path.join(self.mkdtemp(), 'destination')
381 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
382 os.mkdir(os.path.join(src_dir, 'test_dir'))
383 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
384 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
385
386 # a dangling symlink is ignored with the proper flag
387 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
388 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
389 self.assertNotIn('test.txt', os.listdir(dst_dir))
390
391 # a dangling symlink is copied if symlinks=True
392 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
393 shutil.copytree(src_dir, dst_dir, symlinks=True)
394 self.assertIn('test.txt', os.listdir(dst_dir))
395
Tarek Ziadé396fad72010-02-23 05:30:31 +0000396 @unittest.skipUnless(zlib, "requires zlib")
397 def test_make_tarball(self):
398 # creating something to tar
399 tmpdir = self.mkdtemp()
400 self.write_file([tmpdir, 'file1'], 'xxx')
401 self.write_file([tmpdir, 'file2'], 'xxx')
402 os.mkdir(os.path.join(tmpdir, 'sub'))
403 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
404
405 tmpdir2 = self.mkdtemp()
406 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
407 "source and target should be on same drive")
408
409 base_name = os.path.join(tmpdir2, 'archive')
410
411 # working with relative paths to avoid tar warnings
412 old_dir = os.getcwd()
413 os.chdir(tmpdir)
414 try:
415 _make_tarball(splitdrive(base_name)[1], '.')
416 finally:
417 os.chdir(old_dir)
418
419 # check if the compressed tarball was created
420 tarball = base_name + '.tar.gz'
421 self.assertTrue(os.path.exists(tarball))
422
423 # trying an uncompressed one
424 base_name = os.path.join(tmpdir2, 'archive')
425 old_dir = os.getcwd()
426 os.chdir(tmpdir)
427 try:
428 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
429 finally:
430 os.chdir(old_dir)
431 tarball = base_name + '.tar'
432 self.assertTrue(os.path.exists(tarball))
433
434 def _tarinfo(self, path):
435 tar = tarfile.open(path)
436 try:
437 names = tar.getnames()
438 names.sort()
439 return tuple(names)
440 finally:
441 tar.close()
442
443 def _create_files(self):
444 # creating something to tar
445 tmpdir = self.mkdtemp()
446 dist = os.path.join(tmpdir, 'dist')
447 os.mkdir(dist)
448 self.write_file([dist, 'file1'], 'xxx')
449 self.write_file([dist, 'file2'], 'xxx')
450 os.mkdir(os.path.join(dist, 'sub'))
451 self.write_file([dist, 'sub', 'file3'], 'xxx')
452 os.mkdir(os.path.join(dist, 'sub2'))
453 tmpdir2 = self.mkdtemp()
454 base_name = os.path.join(tmpdir2, 'archive')
455 return tmpdir, tmpdir2, base_name
456
457 @unittest.skipUnless(zlib, "Requires zlib")
458 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
459 'Need the tar command to run')
460 def test_tarfile_vs_tar(self):
461 tmpdir, tmpdir2, base_name = self._create_files()
462 old_dir = os.getcwd()
463 os.chdir(tmpdir)
464 try:
465 _make_tarball(base_name, 'dist')
466 finally:
467 os.chdir(old_dir)
468
469 # check if the compressed tarball was created
470 tarball = base_name + '.tar.gz'
471 self.assertTrue(os.path.exists(tarball))
472
473 # now create another tarball using `tar`
474 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
475 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
476 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
477 old_dir = os.getcwd()
478 os.chdir(tmpdir)
479 try:
480 with captured_stdout() as s:
481 spawn(tar_cmd)
482 spawn(gzip_cmd)
483 finally:
484 os.chdir(old_dir)
485
486 self.assertTrue(os.path.exists(tarball2))
487 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000488 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000489
490 # trying an uncompressed one
491 base_name = os.path.join(tmpdir2, 'archive')
492 old_dir = os.getcwd()
493 os.chdir(tmpdir)
494 try:
495 _make_tarball(base_name, 'dist', compress=None)
496 finally:
497 os.chdir(old_dir)
498 tarball = base_name + '.tar'
499 self.assertTrue(os.path.exists(tarball))
500
501 # now for a dry_run
502 base_name = os.path.join(tmpdir2, 'archive')
503 old_dir = os.getcwd()
504 os.chdir(tmpdir)
505 try:
506 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
507 finally:
508 os.chdir(old_dir)
509 tarball = base_name + '.tar'
510 self.assertTrue(os.path.exists(tarball))
511
Tarek Ziadé396fad72010-02-23 05:30:31 +0000512 @unittest.skipUnless(zlib, "Requires zlib")
513 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
514 def test_make_zipfile(self):
515 # creating something to tar
516 tmpdir = self.mkdtemp()
517 self.write_file([tmpdir, 'file1'], 'xxx')
518 self.write_file([tmpdir, 'file2'], 'xxx')
519
520 tmpdir2 = self.mkdtemp()
521 base_name = os.path.join(tmpdir2, 'archive')
522 _make_zipfile(base_name, tmpdir)
523
524 # check if the compressed tarball was created
525 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000526 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000527
528
529 def test_make_archive(self):
530 tmpdir = self.mkdtemp()
531 base_name = os.path.join(tmpdir, 'archive')
532 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
533
534 @unittest.skipUnless(zlib, "Requires zlib")
535 def test_make_archive_owner_group(self):
536 # testing make_archive with owner and group, with various combinations
537 # this works even if there's not gid/uid support
538 if UID_GID_SUPPORT:
539 group = grp.getgrgid(0)[0]
540 owner = pwd.getpwuid(0)[0]
541 else:
542 group = owner = 'root'
543
544 base_dir, root_dir, base_name = self._create_files()
545 base_name = os.path.join(self.mkdtemp() , 'archive')
546 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
547 group=group)
548 self.assertTrue(os.path.exists(res))
549
550 res = make_archive(base_name, 'zip', root_dir, base_dir)
551 self.assertTrue(os.path.exists(res))
552
553 res = make_archive(base_name, 'tar', root_dir, base_dir,
554 owner=owner, group=group)
555 self.assertTrue(os.path.exists(res))
556
557 res = make_archive(base_name, 'tar', root_dir, base_dir,
558 owner='kjhkjhkjg', group='oihohoh')
559 self.assertTrue(os.path.exists(res))
560
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000561
Tarek Ziadé396fad72010-02-23 05:30:31 +0000562 @unittest.skipUnless(zlib, "Requires zlib")
563 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
564 def test_tarfile_root_owner(self):
565 tmpdir, tmpdir2, base_name = self._create_files()
566 old_dir = os.getcwd()
567 os.chdir(tmpdir)
568 group = grp.getgrgid(0)[0]
569 owner = pwd.getpwuid(0)[0]
570 try:
571 archive_name = _make_tarball(base_name, 'dist', compress=None,
572 owner=owner, group=group)
573 finally:
574 os.chdir(old_dir)
575
576 # check if the compressed tarball was created
577 self.assertTrue(os.path.exists(archive_name))
578
579 # now checks the rights
580 archive = tarfile.open(archive_name)
581 try:
582 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000583 self.assertEqual(member.uid, 0)
584 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000585 finally:
586 archive.close()
587
588 def test_make_archive_cwd(self):
589 current_dir = os.getcwd()
590 def _breaks(*args, **kw):
591 raise RuntimeError()
592
593 register_archive_format('xxx', _breaks, [], 'xxx file')
594 try:
595 try:
596 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
597 except Exception:
598 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000599 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000600 finally:
601 unregister_archive_format('xxx')
602
603 def test_register_archive_format(self):
604
605 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
606 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
607 1)
608 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
609 [(1, 2), (1, 2, 3)])
610
611 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
612 formats = [name for name, params in get_archive_formats()]
613 self.assertIn('xxx', formats)
614
615 unregister_archive_format('xxx')
616 formats = [name for name, params in get_archive_formats()]
617 self.assertNotIn('xxx', formats)
618
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000619 def _compare_dirs(self, dir1, dir2):
620 # check that dir1 and dir2 are equivalent,
621 # return the diff
622 diff = []
623 for root, dirs, files in os.walk(dir1):
624 for file_ in files:
625 path = os.path.join(root, file_)
626 target_path = os.path.join(dir2, os.path.split(path)[-1])
627 if not os.path.exists(target_path):
628 diff.append(file_)
629 return diff
630
631 @unittest.skipUnless(zlib, "Requires zlib")
632 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000633 formats = ['tar', 'gztar', 'zip']
634 if BZ2_SUPPORTED:
635 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000636
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000637 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000638 tmpdir = self.mkdtemp()
639 base_dir, root_dir, base_name = self._create_files()
640 tmpdir2 = self.mkdtemp()
641 filename = make_archive(base_name, format, root_dir, base_dir)
642
643 # let's try to unpack it now
644 unpack_archive(filename, tmpdir2)
645 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000646 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000647
648 def test_unpack_registery(self):
649
650 formats = get_unpack_formats()
651
652 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000653 self.assertEqual(extra, 1)
654 self.assertEqual(filename, 'stuff.boo')
655 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000656
657 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
658 unpack_archive('stuff.boo', 'xx')
659
660 # trying to register a .boo unpacker again
661 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
662 ['.boo'], _boo)
663
664 # should work now
665 unregister_unpack_format('Boo')
666 register_unpack_format('Boo2', ['.boo'], _boo)
667 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
668 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
669
670 # let's leave a clean state
671 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000672 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000673
Christian Heimes9bd667a2008-01-20 15:14:11 +0000674
Christian Heimesada8c3b2008-03-18 18:26:33 +0000675class TestMove(unittest.TestCase):
676
677 def setUp(self):
678 filename = "foo"
679 self.src_dir = tempfile.mkdtemp()
680 self.dst_dir = tempfile.mkdtemp()
681 self.src_file = os.path.join(self.src_dir, filename)
682 self.dst_file = os.path.join(self.dst_dir, filename)
683 # Try to create a dir in the current directory, hoping that it is
684 # not located on the same filesystem as the system tmp dir.
685 try:
686 self.dir_other_fs = tempfile.mkdtemp(
687 dir=os.path.dirname(__file__))
688 self.file_other_fs = os.path.join(self.dir_other_fs,
689 filename)
690 except OSError:
691 self.dir_other_fs = None
692 with open(self.src_file, "wb") as f:
693 f.write(b"spam")
694
695 def tearDown(self):
696 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
697 try:
698 if d:
699 shutil.rmtree(d)
700 except:
701 pass
702
703 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000704 with open(src, "rb") as f:
705 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000706 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000707 with open(real_dst, "rb") as f:
708 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000709 self.assertFalse(os.path.exists(src))
710
711 def _check_move_dir(self, src, dst, real_dst):
712 contents = sorted(os.listdir(src))
713 shutil.move(src, dst)
714 self.assertEqual(contents, sorted(os.listdir(real_dst)))
715 self.assertFalse(os.path.exists(src))
716
717 def test_move_file(self):
718 # Move a file to another location on the same filesystem.
719 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
720
721 def test_move_file_to_dir(self):
722 # Move a file inside an existing dir on the same filesystem.
723 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
724
725 def test_move_file_other_fs(self):
726 # Move a file to an existing dir on another filesystem.
727 if not self.dir_other_fs:
728 # skip
729 return
730 self._check_move_file(self.src_file, self.file_other_fs,
731 self.file_other_fs)
732
733 def test_move_file_to_dir_other_fs(self):
734 # Move a file to another location on another filesystem.
735 if not self.dir_other_fs:
736 # skip
737 return
738 self._check_move_file(self.src_file, self.dir_other_fs,
739 self.file_other_fs)
740
741 def test_move_dir(self):
742 # Move a dir to another location on the same filesystem.
743 dst_dir = tempfile.mktemp()
744 try:
745 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
746 finally:
747 try:
748 shutil.rmtree(dst_dir)
749 except:
750 pass
751
752 def test_move_dir_other_fs(self):
753 # Move a dir to another location on another filesystem.
754 if not self.dir_other_fs:
755 # skip
756 return
757 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
758 try:
759 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
760 finally:
761 try:
762 shutil.rmtree(dst_dir)
763 except:
764 pass
765
766 def test_move_dir_to_dir(self):
767 # Move a dir inside an existing dir on the same filesystem.
768 self._check_move_dir(self.src_dir, self.dst_dir,
769 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
770
771 def test_move_dir_to_dir_other_fs(self):
772 # Move a dir inside an existing dir on another filesystem.
773 if not self.dir_other_fs:
774 # skip
775 return
776 self._check_move_dir(self.src_dir, self.dir_other_fs,
777 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
778
779 def test_existing_file_inside_dest_dir(self):
780 # A file with the same name inside the destination dir already exists.
781 with open(self.dst_file, "wb"):
782 pass
783 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
784
785 def test_dont_move_dir_in_itself(self):
786 # Moving a dir inside itself raises an Error.
787 dst = os.path.join(self.src_dir, "bar")
788 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
789
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000790 def test_destinsrc_false_negative(self):
791 os.mkdir(TESTFN)
792 try:
793 for src, dst in [('srcdir', 'srcdir/dest')]:
794 src = os.path.join(TESTFN, src)
795 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000796 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000797 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000798 'dst (%s) is not in src (%s)' % (dst, src))
799 finally:
800 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000801
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000802 def test_destinsrc_false_positive(self):
803 os.mkdir(TESTFN)
804 try:
805 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
806 src = os.path.join(TESTFN, src)
807 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000808 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000809 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000810 'dst (%s) is in src (%s)' % (dst, src))
811 finally:
812 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000813
Tarek Ziadé5340db32010-04-19 22:30:51 +0000814
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000815class TestCopyFile(unittest.TestCase):
816
817 _delete = False
818
819 class Faux(object):
820 _entered = False
821 _exited_with = None
822 _raised = False
823 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
824 self._raise_in_exit = raise_in_exit
825 self._suppress_at_exit = suppress_at_exit
826 def read(self, *args):
827 return ''
828 def __enter__(self):
829 self._entered = True
830 def __exit__(self, exc_type, exc_val, exc_tb):
831 self._exited_with = exc_type, exc_val, exc_tb
832 if self._raise_in_exit:
833 self._raised = True
834 raise IOError("Cannot close")
835 return self._suppress_at_exit
836
837 def tearDown(self):
838 if self._delete:
839 del shutil.open
840
841 def _set_shutil_open(self, func):
842 shutil.open = func
843 self._delete = True
844
845 def test_w_source_open_fails(self):
846 def _open(filename, mode='r'):
847 if filename == 'srcfile':
848 raise IOError('Cannot open "srcfile"')
849 assert 0 # shouldn't reach here.
850
851 self._set_shutil_open(_open)
852
853 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
854
855 def test_w_dest_open_fails(self):
856
857 srcfile = self.Faux()
858
859 def _open(filename, mode='r'):
860 if filename == 'srcfile':
861 return srcfile
862 if filename == 'destfile':
863 raise IOError('Cannot open "destfile"')
864 assert 0 # shouldn't reach here.
865
866 self._set_shutil_open(_open)
867
868 shutil.copyfile('srcfile', 'destfile')
869 self.assertTrue(srcfile._entered)
870 self.assertTrue(srcfile._exited_with[0] is IOError)
871 self.assertEqual(srcfile._exited_with[1].args,
872 ('Cannot open "destfile"',))
873
874 def test_w_dest_close_fails(self):
875
876 srcfile = self.Faux()
877 destfile = self.Faux(True)
878
879 def _open(filename, mode='r'):
880 if filename == 'srcfile':
881 return srcfile
882 if filename == 'destfile':
883 return destfile
884 assert 0 # shouldn't reach here.
885
886 self._set_shutil_open(_open)
887
888 shutil.copyfile('srcfile', 'destfile')
889 self.assertTrue(srcfile._entered)
890 self.assertTrue(destfile._entered)
891 self.assertTrue(destfile._raised)
892 self.assertTrue(srcfile._exited_with[0] is IOError)
893 self.assertEqual(srcfile._exited_with[1].args,
894 ('Cannot close',))
895
896 def test_w_source_close_fails(self):
897
898 srcfile = self.Faux(True)
899 destfile = self.Faux()
900
901 def _open(filename, mode='r'):
902 if filename == 'srcfile':
903 return srcfile
904 if filename == 'destfile':
905 return destfile
906 assert 0 # shouldn't reach here.
907
908 self._set_shutil_open(_open)
909
910 self.assertRaises(IOError,
911 shutil.copyfile, 'srcfile', 'destfile')
912 self.assertTrue(srcfile._entered)
913 self.assertTrue(destfile._entered)
914 self.assertFalse(destfile._raised)
915 self.assertTrue(srcfile._exited_with[0] is None)
916 self.assertTrue(srcfile._raised)
917
918
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000919def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000920 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000921
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000922if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000923 test_main()