blob: 5252d4dff3582a94f25297c9ee2f55cd0f9f23be [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
Nick Coghlan8ed3cf32011-03-16 14:05:35 -040010import functools
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
12from test.support import TESTFN
Tarek Ziadé396fad72010-02-23 05:30:31 +000013from os.path import splitdrive
14from distutils.spawn import find_executable, spawn
15from shutil import (_make_tarball, _make_zipfile, make_archive,
16 register_archive_format, unregister_archive_format,
Tarek Ziadé6ac91722010-04-28 17:51:36 +000017 get_archive_formats, Error, unpack_archive,
18 register_unpack_format, RegistryError,
19 unregister_unpack_format, get_unpack_formats)
Tarek Ziadé396fad72010-02-23 05:30:31 +000020import tarfile
21import warnings
22
23from test import support
24from test.support import TESTFN, check_warnings, captured_stdout
25
Tarek Ziadéffa155a2010-04-29 13:34:35 +000026try:
27 import bz2
28 BZ2_SUPPORTED = True
29except ImportError:
30 BZ2_SUPPORTED = False
31
Antoine Pitrou7fff0962009-05-01 21:09:44 +000032TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000033
Tarek Ziadé396fad72010-02-23 05:30:31 +000034try:
35 import grp
36 import pwd
37 UID_GID_SUPPORT = True
38except ImportError:
39 UID_GID_SUPPORT = False
40
41try:
42 import zlib
43except ImportError:
44 zlib = None
45
46try:
47 import zipfile
48 ZIP_SUPPORT = True
49except ImportError:
50 ZIP_SUPPORT = find_executable('zip')
51
Nick Coghlan8ed3cf32011-03-16 14:05:35 -040052def _fake_rename(*args, **kwargs):
53 # Pretend the destination path is on a different filesystem.
54 raise OSError()
55
56def mock_rename(func):
57 @functools.wraps(func)
58 def wrap(*args, **kwargs):
59 try:
60 builtin_rename = os.rename
61 os.rename = _fake_rename
62 return func(*args, **kwargs)
63 finally:
64 os.rename = builtin_rename
65 return wrap
66
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000067class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000068
69 def setUp(self):
70 super(TestShutil, self).setUp()
71 self.tempdirs = []
72
73 def tearDown(self):
74 super(TestShutil, self).tearDown()
75 while self.tempdirs:
76 d = self.tempdirs.pop()
77 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
78
79 def write_file(self, path, content='xxx'):
80 """Writes a file in the given path.
81
82
83 path can be a string or a sequence.
84 """
85 if isinstance(path, (list, tuple)):
86 path = os.path.join(*path)
87 f = open(path, 'w')
88 try:
89 f.write(content)
90 finally:
91 f.close()
92
93 def mkdtemp(self):
94 """Create a temporary directory that will be cleaned up.
95
96 Returns the path of the directory.
97 """
98 d = tempfile.mkdtemp()
99 self.tempdirs.append(d)
100 return d
Tarek Ziadé5340db32010-04-19 22:30:51 +0000101
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000102 def test_rmtree_errors(self):
103 # filename is guaranteed not to exist
104 filename = tempfile.mktemp()
105 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000106
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000107 # See bug #1071513 for why we don't run this on cygwin
108 # and bug #1076467 for why we don't run this as root.
109 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +0000110 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000111 def test_on_error(self):
112 self.errorState = 0
113 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +0000114 self.childpath = os.path.join(TESTFN, 'a')
115 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000116 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000117 old_dir_mode = os.stat(TESTFN).st_mode
118 old_child_mode = os.stat(self.childpath).st_mode
119 # Make unwritable.
120 os.chmod(self.childpath, stat.S_IREAD)
121 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000122
123 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000124 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000125 self.assertEqual(self.errorState, 2,
126 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000127
Tim Peters4590c002004-11-01 02:40:52 +0000128 # Make writable again.
129 os.chmod(TESTFN, old_dir_mode)
130 os.chmod(self.childpath, old_child_mode)
131
132 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000133 shutil.rmtree(TESTFN)
134
135 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000136 # test_rmtree_errors deliberately runs rmtree
137 # on a directory that is chmod 400, which will fail.
138 # This function is run when shutil.rmtree fails.
139 # 99.9% of the time it initially fails to remove
140 # a file in the directory, so the first time through
141 # func is os.remove.
142 # However, some Linux machines running ZFS on
143 # FUSE experienced a failure earlier in the process
144 # at os.listdir. The first failure may legally
145 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000146 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000147 if func is os.remove:
148 self.assertEqual(arg, self.childpath)
149 else:
150 self.assertIs(func, os.listdir,
151 "func must be either os.remove or os.listdir")
152 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000153 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000154 self.errorState = 1
155 else:
156 self.assertEqual(func, os.rmdir)
157 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000158 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000159 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000160
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000161 def test_rmtree_dont_delete_file(self):
162 # When called on a file instead of a directory, don't delete it.
163 handle, path = tempfile.mkstemp()
164 os.fdopen(handle).close()
165 self.assertRaises(OSError, shutil.rmtree, path)
166 os.remove(path)
167
Tarek Ziadé5340db32010-04-19 22:30:51 +0000168 def _write_data(self, path, data):
169 f = open(path, "w")
170 f.write(data)
171 f.close()
172
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000173 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000174
175 def read_data(path):
176 f = open(path)
177 data = f.read()
178 f.close()
179 return data
180
181 src_dir = tempfile.mkdtemp()
182 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000183 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000184 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000185 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000186
187 try:
188 shutil.copytree(src_dir, dst_dir)
189 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
190 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
191 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
192 'test.txt')))
193 actual = read_data(os.path.join(dst_dir, 'test.txt'))
194 self.assertEqual(actual, '123')
195 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
196 self.assertEqual(actual, '456')
197 finally:
198 for path in (
199 os.path.join(src_dir, 'test.txt'),
200 os.path.join(dst_dir, 'test.txt'),
201 os.path.join(src_dir, 'test_dir', 'test.txt'),
202 os.path.join(dst_dir, 'test_dir', 'test.txt'),
203 ):
204 if os.path.exists(path):
205 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000206 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000207 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000208 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000209 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000210 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000211
Georg Brandl2ee470f2008-07-16 12:55:28 +0000212 def test_copytree_with_exclude(self):
213
Georg Brandl2ee470f2008-07-16 12:55:28 +0000214 def read_data(path):
215 f = open(path)
216 data = f.read()
217 f.close()
218 return data
219
220 # creating data
221 join = os.path.join
222 exists = os.path.exists
223 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000224 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000225 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000226 self._write_data(join(src_dir, 'test.txt'), '123')
227 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000228 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000229 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000230 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000231 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000232 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
233 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000234 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
235 '456')
236 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
237 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000238
239
240 # testing glob-like patterns
241 try:
242 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
243 shutil.copytree(src_dir, dst_dir, ignore=patterns)
244 # checking the result: some elements should not be copied
245 self.assertTrue(exists(join(dst_dir, 'test.txt')))
246 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
247 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
248 finally:
249 if os.path.exists(dst_dir):
250 shutil.rmtree(dst_dir)
251 try:
252 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
253 shutil.copytree(src_dir, dst_dir, ignore=patterns)
254 # checking the result: some elements should not be copied
255 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
256 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
257 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
258 finally:
259 if os.path.exists(dst_dir):
260 shutil.rmtree(dst_dir)
261
262 # testing callable-style
263 try:
264 def _filter(src, names):
265 res = []
266 for name in names:
267 path = os.path.join(src, name)
268
269 if (os.path.isdir(path) and
270 path.split()[-1] == 'subdir'):
271 res.append(name)
272 elif os.path.splitext(path)[-1] in ('.py'):
273 res.append(name)
274 return res
275
276 shutil.copytree(src_dir, dst_dir, ignore=_filter)
277
278 # checking the result: some elements should not be copied
279 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
280 'test.py')))
281 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
282
283 finally:
284 if os.path.exists(dst_dir):
285 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000286 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000287 shutil.rmtree(src_dir)
288 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000290 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000291 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000292 # Temporarily disable test on Windows.
293 if os.name == 'nt':
294 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000295 # bug 851123.
296 os.mkdir(TESTFN)
297 src = os.path.join(TESTFN, 'cheese')
298 dst = os.path.join(TESTFN, 'shop')
299 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000300 with open(src, 'w') as f:
301 f.write('cheddar')
302 os.link(src, dst)
303 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
304 with open(src, 'r') as f:
305 self.assertEqual(f.read(), 'cheddar')
306 os.remove(dst)
307 finally:
308 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000309
Brian Curtin3b4499c2010-12-28 14:31:47 +0000310 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000311 def test_dont_copy_file_onto_symlink_to_itself(self):
312 # bug 851123.
313 os.mkdir(TESTFN)
314 src = os.path.join(TESTFN, 'cheese')
315 dst = os.path.join(TESTFN, 'shop')
316 try:
317 with open(src, 'w') as f:
318 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000319 # Using `src` here would mean we end up with a symlink pointing
320 # to TESTFN/TESTFN/cheese, while it should point at
321 # TESTFN/cheese.
322 os.symlink('cheese', dst)
323 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000324 with open(src, 'r') as f:
325 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000326 os.remove(dst)
327 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000328 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000329
Brian Curtin3b4499c2010-12-28 14:31:47 +0000330 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000331 def test_rmtree_on_symlink(self):
332 # bug 1669.
333 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000334 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000335 src = os.path.join(TESTFN, 'cheese')
336 dst = os.path.join(TESTFN, 'shop')
337 os.mkdir(src)
338 os.symlink(src, dst)
339 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000340 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000341 shutil.rmtree(TESTFN, ignore_errors=True)
342
343 if hasattr(os, "mkfifo"):
344 # Issue #3002: copyfile and copytree block indefinitely on named pipes
345 def test_copyfile_named_pipe(self):
346 os.mkfifo(TESTFN)
347 try:
348 self.assertRaises(shutil.SpecialFileError,
349 shutil.copyfile, TESTFN, TESTFN2)
350 self.assertRaises(shutil.SpecialFileError,
351 shutil.copyfile, __file__, TESTFN)
352 finally:
353 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000354
Brian Curtin3b4499c2010-12-28 14:31:47 +0000355 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000356 def test_copytree_named_pipe(self):
357 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000358 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000359 subdir = os.path.join(TESTFN, "subdir")
360 os.mkdir(subdir)
361 pipe = os.path.join(subdir, "mypipe")
362 os.mkfifo(pipe)
363 try:
364 shutil.copytree(TESTFN, TESTFN2)
365 except shutil.Error as e:
366 errors = e.args[0]
367 self.assertEqual(len(errors), 1)
368 src, dst, error_msg = errors[0]
369 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
370 else:
371 self.fail("shutil.Error should have been raised")
372 finally:
373 shutil.rmtree(TESTFN, ignore_errors=True)
374 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000375
Tarek Ziadé5340db32010-04-19 22:30:51 +0000376 def test_copytree_special_func(self):
377
378 src_dir = self.mkdtemp()
379 dst_dir = os.path.join(self.mkdtemp(), 'destination')
380 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
381 os.mkdir(os.path.join(src_dir, 'test_dir'))
382 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
383
384 copied = []
385 def _copy(src, dst):
386 copied.append((src, dst))
387
388 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000389 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000390
Brian Curtin3b4499c2010-12-28 14:31:47 +0000391 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000392 def test_copytree_dangling_symlinks(self):
393
394 # a dangling symlink raises an error at the end
395 src_dir = self.mkdtemp()
396 dst_dir = os.path.join(self.mkdtemp(), 'destination')
397 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
398 os.mkdir(os.path.join(src_dir, 'test_dir'))
399 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
400 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
401
402 # a dangling symlink is ignored with the proper flag
403 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
404 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
405 self.assertNotIn('test.txt', os.listdir(dst_dir))
406
407 # a dangling symlink is copied if symlinks=True
408 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
409 shutil.copytree(src_dir, dst_dir, symlinks=True)
410 self.assertIn('test.txt', os.listdir(dst_dir))
411
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400412 def _copy_file(self, method):
413 fname = 'test.txt'
414 tmpdir = self.mkdtemp()
415 self.write_file([tmpdir, fname])
416 file1 = os.path.join(tmpdir, fname)
417 tmpdir2 = self.mkdtemp()
418 method(file1, tmpdir2)
419 file2 = os.path.join(tmpdir2, fname)
420 return (file1, file2)
421
422 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
423 def test_copy(self):
424 # Ensure that the copied file exists and has the same mode bits.
425 file1, file2 = self._copy_file(shutil.copy)
426 self.assertTrue(os.path.exists(file2))
427 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
428
429 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
430 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.utime')
431 def test_copy2(self):
432 # Ensure that the copied file exists and has the same mode and
433 # modification time bits.
434 file1, file2 = self._copy_file(shutil.copy2)
435 self.assertTrue(os.path.exists(file2))
436 file1_stat = os.stat(file1)
437 file2_stat = os.stat(file2)
438 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
439 for attr in 'st_atime', 'st_mtime':
440 # The modification times may be truncated in the new file.
441 self.assertLessEqual(getattr(file1_stat, attr),
442 getattr(file2_stat, attr) + 1)
443 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
444 self.assertEqual(getattr(file1_stat, 'st_flags'),
445 getattr(file2_stat, 'st_flags'))
446
Tarek Ziadé396fad72010-02-23 05:30:31 +0000447 @unittest.skipUnless(zlib, "requires zlib")
448 def test_make_tarball(self):
449 # creating something to tar
450 tmpdir = self.mkdtemp()
451 self.write_file([tmpdir, 'file1'], 'xxx')
452 self.write_file([tmpdir, 'file2'], 'xxx')
453 os.mkdir(os.path.join(tmpdir, 'sub'))
454 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
455
456 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400457 # force shutil to create the directory
458 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000459 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
460 "source and target should be on same drive")
461
462 base_name = os.path.join(tmpdir2, 'archive')
463
464 # working with relative paths to avoid tar warnings
465 old_dir = os.getcwd()
466 os.chdir(tmpdir)
467 try:
468 _make_tarball(splitdrive(base_name)[1], '.')
469 finally:
470 os.chdir(old_dir)
471
472 # check if the compressed tarball was created
473 tarball = base_name + '.tar.gz'
474 self.assertTrue(os.path.exists(tarball))
475
476 # trying an uncompressed one
477 base_name = os.path.join(tmpdir2, 'archive')
478 old_dir = os.getcwd()
479 os.chdir(tmpdir)
480 try:
481 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
482 finally:
483 os.chdir(old_dir)
484 tarball = base_name + '.tar'
485 self.assertTrue(os.path.exists(tarball))
486
487 def _tarinfo(self, path):
488 tar = tarfile.open(path)
489 try:
490 names = tar.getnames()
491 names.sort()
492 return tuple(names)
493 finally:
494 tar.close()
495
496 def _create_files(self):
497 # creating something to tar
498 tmpdir = self.mkdtemp()
499 dist = os.path.join(tmpdir, 'dist')
500 os.mkdir(dist)
501 self.write_file([dist, 'file1'], 'xxx')
502 self.write_file([dist, 'file2'], 'xxx')
503 os.mkdir(os.path.join(dist, 'sub'))
504 self.write_file([dist, 'sub', 'file3'], 'xxx')
505 os.mkdir(os.path.join(dist, 'sub2'))
506 tmpdir2 = self.mkdtemp()
507 base_name = os.path.join(tmpdir2, 'archive')
508 return tmpdir, tmpdir2, base_name
509
510 @unittest.skipUnless(zlib, "Requires zlib")
511 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
512 'Need the tar command to run')
513 def test_tarfile_vs_tar(self):
514 tmpdir, tmpdir2, base_name = self._create_files()
515 old_dir = os.getcwd()
516 os.chdir(tmpdir)
517 try:
518 _make_tarball(base_name, 'dist')
519 finally:
520 os.chdir(old_dir)
521
522 # check if the compressed tarball was created
523 tarball = base_name + '.tar.gz'
524 self.assertTrue(os.path.exists(tarball))
525
526 # now create another tarball using `tar`
527 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
528 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
529 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
530 old_dir = os.getcwd()
531 os.chdir(tmpdir)
532 try:
533 with captured_stdout() as s:
534 spawn(tar_cmd)
535 spawn(gzip_cmd)
536 finally:
537 os.chdir(old_dir)
538
539 self.assertTrue(os.path.exists(tarball2))
540 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000541 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000542
543 # trying an uncompressed one
544 base_name = os.path.join(tmpdir2, 'archive')
545 old_dir = os.getcwd()
546 os.chdir(tmpdir)
547 try:
548 _make_tarball(base_name, 'dist', compress=None)
549 finally:
550 os.chdir(old_dir)
551 tarball = base_name + '.tar'
552 self.assertTrue(os.path.exists(tarball))
553
554 # now for a dry_run
555 base_name = os.path.join(tmpdir2, 'archive')
556 old_dir = os.getcwd()
557 os.chdir(tmpdir)
558 try:
559 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
560 finally:
561 os.chdir(old_dir)
562 tarball = base_name + '.tar'
563 self.assertTrue(os.path.exists(tarball))
564
Tarek Ziadé396fad72010-02-23 05:30:31 +0000565 @unittest.skipUnless(zlib, "Requires zlib")
566 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
567 def test_make_zipfile(self):
568 # creating something to tar
569 tmpdir = self.mkdtemp()
570 self.write_file([tmpdir, 'file1'], 'xxx')
571 self.write_file([tmpdir, 'file2'], 'xxx')
572
573 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400574 # force shutil to create the directory
575 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000576 base_name = os.path.join(tmpdir2, 'archive')
577 _make_zipfile(base_name, tmpdir)
578
579 # check if the compressed tarball was created
580 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000581 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000582
583
584 def test_make_archive(self):
585 tmpdir = self.mkdtemp()
586 base_name = os.path.join(tmpdir, 'archive')
587 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
588
589 @unittest.skipUnless(zlib, "Requires zlib")
590 def test_make_archive_owner_group(self):
591 # testing make_archive with owner and group, with various combinations
592 # this works even if there's not gid/uid support
593 if UID_GID_SUPPORT:
594 group = grp.getgrgid(0)[0]
595 owner = pwd.getpwuid(0)[0]
596 else:
597 group = owner = 'root'
598
599 base_dir, root_dir, base_name = self._create_files()
600 base_name = os.path.join(self.mkdtemp() , 'archive')
601 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
602 group=group)
603 self.assertTrue(os.path.exists(res))
604
605 res = make_archive(base_name, 'zip', root_dir, base_dir)
606 self.assertTrue(os.path.exists(res))
607
608 res = make_archive(base_name, 'tar', root_dir, base_dir,
609 owner=owner, group=group)
610 self.assertTrue(os.path.exists(res))
611
612 res = make_archive(base_name, 'tar', root_dir, base_dir,
613 owner='kjhkjhkjg', group='oihohoh')
614 self.assertTrue(os.path.exists(res))
615
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000616
Tarek Ziadé396fad72010-02-23 05:30:31 +0000617 @unittest.skipUnless(zlib, "Requires zlib")
618 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
619 def test_tarfile_root_owner(self):
620 tmpdir, tmpdir2, base_name = self._create_files()
621 old_dir = os.getcwd()
622 os.chdir(tmpdir)
623 group = grp.getgrgid(0)[0]
624 owner = pwd.getpwuid(0)[0]
625 try:
626 archive_name = _make_tarball(base_name, 'dist', compress=None,
627 owner=owner, group=group)
628 finally:
629 os.chdir(old_dir)
630
631 # check if the compressed tarball was created
632 self.assertTrue(os.path.exists(archive_name))
633
634 # now checks the rights
635 archive = tarfile.open(archive_name)
636 try:
637 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000638 self.assertEqual(member.uid, 0)
639 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000640 finally:
641 archive.close()
642
643 def test_make_archive_cwd(self):
644 current_dir = os.getcwd()
645 def _breaks(*args, **kw):
646 raise RuntimeError()
647
648 register_archive_format('xxx', _breaks, [], 'xxx file')
649 try:
650 try:
651 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
652 except Exception:
653 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000654 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000655 finally:
656 unregister_archive_format('xxx')
657
658 def test_register_archive_format(self):
659
660 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
661 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
662 1)
663 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
664 [(1, 2), (1, 2, 3)])
665
666 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
667 formats = [name for name, params in get_archive_formats()]
668 self.assertIn('xxx', formats)
669
670 unregister_archive_format('xxx')
671 formats = [name for name, params in get_archive_formats()]
672 self.assertNotIn('xxx', formats)
673
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000674 def _compare_dirs(self, dir1, dir2):
675 # check that dir1 and dir2 are equivalent,
676 # return the diff
677 diff = []
678 for root, dirs, files in os.walk(dir1):
679 for file_ in files:
680 path = os.path.join(root, file_)
681 target_path = os.path.join(dir2, os.path.split(path)[-1])
682 if not os.path.exists(target_path):
683 diff.append(file_)
684 return diff
685
686 @unittest.skipUnless(zlib, "Requires zlib")
687 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000688 formats = ['tar', 'gztar', 'zip']
689 if BZ2_SUPPORTED:
690 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000691
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000692 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000693 tmpdir = self.mkdtemp()
694 base_dir, root_dir, base_name = self._create_files()
695 tmpdir2 = self.mkdtemp()
696 filename = make_archive(base_name, format, root_dir, base_dir)
697
698 # let's try to unpack it now
699 unpack_archive(filename, tmpdir2)
700 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000701 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000702
Nick Coghlanabf202d2011-03-16 13:52:20 -0400703 # and again, this time with the format specified
704 tmpdir3 = self.mkdtemp()
705 unpack_archive(filename, tmpdir3, format=format)
706 diff = self._compare_dirs(tmpdir, tmpdir3)
707 self.assertEqual(diff, [])
708 self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
709 self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
710
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000711 def test_unpack_registery(self):
712
713 formats = get_unpack_formats()
714
715 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000716 self.assertEqual(extra, 1)
717 self.assertEqual(filename, 'stuff.boo')
718 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000719
720 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
721 unpack_archive('stuff.boo', 'xx')
722
723 # trying to register a .boo unpacker again
724 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
725 ['.boo'], _boo)
726
727 # should work now
728 unregister_unpack_format('Boo')
729 register_unpack_format('Boo2', ['.boo'], _boo)
730 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
731 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
732
733 # let's leave a clean state
734 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000735 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000736
Christian Heimes9bd667a2008-01-20 15:14:11 +0000737
Christian Heimesada8c3b2008-03-18 18:26:33 +0000738class TestMove(unittest.TestCase):
739
740 def setUp(self):
741 filename = "foo"
742 self.src_dir = tempfile.mkdtemp()
743 self.dst_dir = tempfile.mkdtemp()
744 self.src_file = os.path.join(self.src_dir, filename)
745 self.dst_file = os.path.join(self.dst_dir, filename)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000746 with open(self.src_file, "wb") as f:
747 f.write(b"spam")
748
749 def tearDown(self):
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400750 for d in (self.src_dir, self.dst_dir):
Christian Heimesada8c3b2008-03-18 18:26:33 +0000751 try:
752 if d:
753 shutil.rmtree(d)
754 except:
755 pass
756
757 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000758 with open(src, "rb") as f:
759 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000760 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000761 with open(real_dst, "rb") as f:
762 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000763 self.assertFalse(os.path.exists(src))
764
765 def _check_move_dir(self, src, dst, real_dst):
766 contents = sorted(os.listdir(src))
767 shutil.move(src, dst)
768 self.assertEqual(contents, sorted(os.listdir(real_dst)))
769 self.assertFalse(os.path.exists(src))
770
771 def test_move_file(self):
772 # Move a file to another location on the same filesystem.
773 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
774
775 def test_move_file_to_dir(self):
776 # Move a file inside an existing dir on the same filesystem.
777 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
778
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400779 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000780 def test_move_file_other_fs(self):
781 # Move a file to an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400782 self.test_move_file()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000783
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400784 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000785 def test_move_file_to_dir_other_fs(self):
786 # Move a file to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400787 self.test_move_file_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000788
789 def test_move_dir(self):
790 # Move a dir to another location on the same filesystem.
791 dst_dir = tempfile.mktemp()
792 try:
793 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
794 finally:
795 try:
796 shutil.rmtree(dst_dir)
797 except:
798 pass
799
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400800 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000801 def test_move_dir_other_fs(self):
802 # Move a dir to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400803 self.test_move_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000804
805 def test_move_dir_to_dir(self):
806 # Move a dir inside an existing dir on the same filesystem.
807 self._check_move_dir(self.src_dir, self.dst_dir,
808 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
809
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400810 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000811 def test_move_dir_to_dir_other_fs(self):
812 # Move a dir inside an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400813 self.test_move_dir_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000814
815 def test_existing_file_inside_dest_dir(self):
816 # A file with the same name inside the destination dir already exists.
817 with open(self.dst_file, "wb"):
818 pass
819 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
820
821 def test_dont_move_dir_in_itself(self):
822 # Moving a dir inside itself raises an Error.
823 dst = os.path.join(self.src_dir, "bar")
824 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
825
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000826 def test_destinsrc_false_negative(self):
827 os.mkdir(TESTFN)
828 try:
829 for src, dst in [('srcdir', 'srcdir/dest')]:
830 src = os.path.join(TESTFN, src)
831 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000832 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000833 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000834 'dst (%s) is not in src (%s)' % (dst, src))
835 finally:
836 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000837
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000838 def test_destinsrc_false_positive(self):
839 os.mkdir(TESTFN)
840 try:
841 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
842 src = os.path.join(TESTFN, src)
843 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000844 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000845 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000846 'dst (%s) is in src (%s)' % (dst, src))
847 finally:
848 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000849
Tarek Ziadé5340db32010-04-19 22:30:51 +0000850
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000851class TestCopyFile(unittest.TestCase):
852
853 _delete = False
854
855 class Faux(object):
856 _entered = False
857 _exited_with = None
858 _raised = False
859 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
860 self._raise_in_exit = raise_in_exit
861 self._suppress_at_exit = suppress_at_exit
862 def read(self, *args):
863 return ''
864 def __enter__(self):
865 self._entered = True
866 def __exit__(self, exc_type, exc_val, exc_tb):
867 self._exited_with = exc_type, exc_val, exc_tb
868 if self._raise_in_exit:
869 self._raised = True
870 raise IOError("Cannot close")
871 return self._suppress_at_exit
872
873 def tearDown(self):
874 if self._delete:
875 del shutil.open
876
877 def _set_shutil_open(self, func):
878 shutil.open = func
879 self._delete = True
880
881 def test_w_source_open_fails(self):
882 def _open(filename, mode='r'):
883 if filename == 'srcfile':
884 raise IOError('Cannot open "srcfile"')
885 assert 0 # shouldn't reach here.
886
887 self._set_shutil_open(_open)
888
889 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
890
891 def test_w_dest_open_fails(self):
892
893 srcfile = self.Faux()
894
895 def _open(filename, mode='r'):
896 if filename == 'srcfile':
897 return srcfile
898 if filename == 'destfile':
899 raise IOError('Cannot open "destfile"')
900 assert 0 # shouldn't reach here.
901
902 self._set_shutil_open(_open)
903
904 shutil.copyfile('srcfile', 'destfile')
905 self.assertTrue(srcfile._entered)
906 self.assertTrue(srcfile._exited_with[0] is IOError)
907 self.assertEqual(srcfile._exited_with[1].args,
908 ('Cannot open "destfile"',))
909
910 def test_w_dest_close_fails(self):
911
912 srcfile = self.Faux()
913 destfile = self.Faux(True)
914
915 def _open(filename, mode='r'):
916 if filename == 'srcfile':
917 return srcfile
918 if filename == 'destfile':
919 return destfile
920 assert 0 # shouldn't reach here.
921
922 self._set_shutil_open(_open)
923
924 shutil.copyfile('srcfile', 'destfile')
925 self.assertTrue(srcfile._entered)
926 self.assertTrue(destfile._entered)
927 self.assertTrue(destfile._raised)
928 self.assertTrue(srcfile._exited_with[0] is IOError)
929 self.assertEqual(srcfile._exited_with[1].args,
930 ('Cannot close',))
931
932 def test_w_source_close_fails(self):
933
934 srcfile = self.Faux(True)
935 destfile = self.Faux()
936
937 def _open(filename, mode='r'):
938 if filename == 'srcfile':
939 return srcfile
940 if filename == 'destfile':
941 return destfile
942 assert 0 # shouldn't reach here.
943
944 self._set_shutil_open(_open)
945
946 self.assertRaises(IOError,
947 shutil.copyfile, 'srcfile', 'destfile')
948 self.assertTrue(srcfile._entered)
949 self.assertTrue(destfile._entered)
950 self.assertFalse(destfile._raised)
951 self.assertTrue(srcfile._exited_with[0] is None)
952 self.assertTrue(srcfile._raised)
953
954
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000955def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000956 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000957
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000958if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000959 test_main()