blob: da4260492273110d772f86f30f18763ff790facf [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
Ned Deily5fddf862012-05-10 17:21:23 -070011import errno
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
13from test.support import TESTFN
Tarek Ziadé396fad72010-02-23 05:30:31 +000014from os.path import splitdrive
15from distutils.spawn import find_executable, spawn
16from shutil import (_make_tarball, _make_zipfile, make_archive,
17 register_archive_format, unregister_archive_format,
Tarek Ziadé6ac91722010-04-28 17:51:36 +000018 get_archive_formats, Error, unpack_archive,
19 register_unpack_format, RegistryError,
20 unregister_unpack_format, get_unpack_formats)
Tarek Ziadé396fad72010-02-23 05:30:31 +000021import tarfile
22import warnings
23
24from test import support
25from test.support import TESTFN, check_warnings, captured_stdout
26
Tarek Ziadéffa155a2010-04-29 13:34:35 +000027try:
28 import bz2
29 BZ2_SUPPORTED = True
30except ImportError:
31 BZ2_SUPPORTED = False
32
Antoine Pitrou7fff0962009-05-01 21:09:44 +000033TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000034
Tarek Ziadé396fad72010-02-23 05:30:31 +000035try:
36 import grp
37 import pwd
38 UID_GID_SUPPORT = True
39except ImportError:
40 UID_GID_SUPPORT = False
41
42try:
43 import zlib
44except ImportError:
45 zlib = None
46
47try:
48 import zipfile
49 ZIP_SUPPORT = True
50except ImportError:
51 ZIP_SUPPORT = find_executable('zip')
52
Nick Coghlan8ed3cf32011-03-16 14:05:35 -040053def _fake_rename(*args, **kwargs):
54 # Pretend the destination path is on a different filesystem.
55 raise OSError()
56
57def mock_rename(func):
58 @functools.wraps(func)
59 def wrap(*args, **kwargs):
60 try:
61 builtin_rename = os.rename
62 os.rename = _fake_rename
63 return func(*args, **kwargs)
64 finally:
65 os.rename = builtin_rename
66 return wrap
67
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000068class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000069
70 def setUp(self):
71 super(TestShutil, self).setUp()
72 self.tempdirs = []
73
74 def tearDown(self):
75 super(TestShutil, self).tearDown()
76 while self.tempdirs:
77 d = self.tempdirs.pop()
78 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
79
80 def write_file(self, path, content='xxx'):
81 """Writes a file in the given path.
82
83
84 path can be a string or a sequence.
85 """
86 if isinstance(path, (list, tuple)):
87 path = os.path.join(*path)
88 f = open(path, 'w')
89 try:
90 f.write(content)
91 finally:
92 f.close()
93
94 def mkdtemp(self):
95 """Create a temporary directory that will be cleaned up.
96
97 Returns the path of the directory.
98 """
99 d = tempfile.mkdtemp()
100 self.tempdirs.append(d)
101 return d
Tarek Ziadé5340db32010-04-19 22:30:51 +0000102
Hynek Schlawackd16eacb2012-12-10 09:00:09 +0100103 @support.skip_unless_symlink
104 def test_rmtree_fails_on_symlink(self):
105 tmp = self.mkdtemp()
106 dir_ = os.path.join(tmp, 'dir')
107 os.mkdir(dir_)
108 link = os.path.join(tmp, 'link')
109 os.symlink(dir_, link)
110 self.assertRaises(OSError, shutil.rmtree, link)
111 self.assertTrue(os.path.exists(dir_))
112 self.assertTrue(os.path.lexists(link))
113 errors = []
114 def onerror(*args):
115 errors.append(args)
116 shutil.rmtree(link, onerror=onerror)
117 self.assertEqual(len(errors), 1)
118 self.assertIs(errors[0][0], os.path.islink)
119 self.assertEqual(errors[0][1], link)
120 self.assertIsInstance(errors[0][2][1], OSError)
121
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000122 def test_rmtree_errors(self):
123 # filename is guaranteed not to exist
124 filename = tempfile.mktemp()
125 self.assertRaises(OSError, shutil.rmtree, filename)
Hynek Schlawackd16eacb2012-12-10 09:00:09 +0100126 # test that ignore_errors option is honoured
127 shutil.rmtree(filename, ignore_errors=True)
128
129 # existing file
130 tmpdir = self.mkdtemp()
131 self.write_file((tmpdir, "tstfile"), "")
132 filename = os.path.join(tmpdir, "tstfile")
133 with self.assertRaises(OSError) as cm:
134 shutil.rmtree(filename)
135 self.assertEqual(cm.exception.filename, filename)
136 self.assertTrue(os.path.exists(filename))
137 # test that ignore_errors option is honoured
138 shutil.rmtree(filename, ignore_errors=True)
139 self.assertTrue(os.path.exists(filename))
140 errors = []
141 def onerror(*args):
142 errors.append(args)
143 shutil.rmtree(filename, onerror=onerror)
144 self.assertEqual(len(errors), 2)
145 self.assertIs(errors[0][0], os.listdir)
146 self.assertEqual(errors[0][1], filename)
147 self.assertIsInstance(errors[0][2][1], OSError)
148 self.assertEqual(errors[0][2][1].filename, filename)
149 self.assertIs(errors[1][0], os.rmdir)
150 self.assertEqual(errors[1][1], filename)
151 self.assertIsInstance(errors[1][2][1], OSError)
152 self.assertEqual(errors[1][2][1].filename, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000153
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000154 # See bug #1071513 for why we don't run this on cygwin
155 # and bug #1076467 for why we don't run this as root.
156 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +0000157 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000158 def test_on_error(self):
159 self.errorState = 0
160 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +0000161 self.childpath = os.path.join(TESTFN, 'a')
162 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000163 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000164 old_dir_mode = os.stat(TESTFN).st_mode
165 old_child_mode = os.stat(self.childpath).st_mode
166 # Make unwritable.
167 os.chmod(self.childpath, stat.S_IREAD)
168 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000169
170 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000171 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000172 self.assertEqual(self.errorState, 2,
173 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000174
Tim Peters4590c002004-11-01 02:40:52 +0000175 # Make writable again.
176 os.chmod(TESTFN, old_dir_mode)
177 os.chmod(self.childpath, old_child_mode)
178
179 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000180 shutil.rmtree(TESTFN)
181
182 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000183 # test_rmtree_errors deliberately runs rmtree
184 # on a directory that is chmod 400, which will fail.
185 # This function is run when shutil.rmtree fails.
186 # 99.9% of the time it initially fails to remove
187 # a file in the directory, so the first time through
188 # func is os.remove.
189 # However, some Linux machines running ZFS on
190 # FUSE experienced a failure earlier in the process
191 # at os.listdir. The first failure may legally
192 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000193 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000194 if func is os.remove:
195 self.assertEqual(arg, self.childpath)
196 else:
197 self.assertIs(func, os.listdir,
198 "func must be either os.remove or os.listdir")
199 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000200 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000201 self.errorState = 1
202 else:
203 self.assertEqual(func, os.rmdir)
204 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000205 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000206 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000207
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000208 def test_rmtree_dont_delete_file(self):
209 # When called on a file instead of a directory, don't delete it.
210 handle, path = tempfile.mkstemp()
211 os.fdopen(handle).close()
212 self.assertRaises(OSError, shutil.rmtree, path)
213 os.remove(path)
214
Tarek Ziadé5340db32010-04-19 22:30:51 +0000215 def _write_data(self, path, data):
216 f = open(path, "w")
217 f.write(data)
218 f.close()
219
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000220 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000221
222 def read_data(path):
223 f = open(path)
224 data = f.read()
225 f.close()
226 return data
227
228 src_dir = tempfile.mkdtemp()
229 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000230 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000231 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000232 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000233
234 try:
235 shutil.copytree(src_dir, dst_dir)
236 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
237 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
238 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
239 'test.txt')))
240 actual = read_data(os.path.join(dst_dir, 'test.txt'))
241 self.assertEqual(actual, '123')
242 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
243 self.assertEqual(actual, '456')
244 finally:
245 for path in (
246 os.path.join(src_dir, 'test.txt'),
247 os.path.join(dst_dir, 'test.txt'),
248 os.path.join(src_dir, 'test_dir', 'test.txt'),
249 os.path.join(dst_dir, 'test_dir', 'test.txt'),
250 ):
251 if os.path.exists(path):
252 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000253 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000254 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000255 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000256 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000257 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000258
Georg Brandl2ee470f2008-07-16 12:55:28 +0000259 def test_copytree_with_exclude(self):
260
Georg Brandl2ee470f2008-07-16 12:55:28 +0000261 def read_data(path):
262 f = open(path)
263 data = f.read()
264 f.close()
265 return data
266
267 # creating data
268 join = os.path.join
269 exists = os.path.exists
270 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000271 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000272 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000273 self._write_data(join(src_dir, 'test.txt'), '123')
274 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000275 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000276 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000277 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000278 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000279 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
280 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000281 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
282 '456')
283 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
284 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000285
286
287 # testing glob-like patterns
288 try:
289 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
290 shutil.copytree(src_dir, dst_dir, ignore=patterns)
291 # checking the result: some elements should not be copied
292 self.assertTrue(exists(join(dst_dir, 'test.txt')))
293 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
294 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
295 finally:
296 if os.path.exists(dst_dir):
297 shutil.rmtree(dst_dir)
298 try:
299 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
300 shutil.copytree(src_dir, dst_dir, ignore=patterns)
301 # checking the result: some elements should not be copied
302 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
303 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
304 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
305 finally:
306 if os.path.exists(dst_dir):
307 shutil.rmtree(dst_dir)
308
309 # testing callable-style
310 try:
311 def _filter(src, names):
312 res = []
313 for name in names:
314 path = os.path.join(src, name)
315
316 if (os.path.isdir(path) and
317 path.split()[-1] == 'subdir'):
318 res.append(name)
319 elif os.path.splitext(path)[-1] in ('.py'):
320 res.append(name)
321 return res
322
323 shutil.copytree(src_dir, dst_dir, ignore=_filter)
324
325 # checking the result: some elements should not be copied
326 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
327 'test.py')))
328 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
329
330 finally:
331 if os.path.exists(dst_dir):
332 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000333 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000334 shutil.rmtree(src_dir)
335 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000336
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000337 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000338 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000339 # Temporarily disable test on Windows.
340 if os.name == 'nt':
341 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000342 # bug 851123.
343 os.mkdir(TESTFN)
344 src = os.path.join(TESTFN, 'cheese')
345 dst = os.path.join(TESTFN, 'shop')
346 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000347 with open(src, 'w') as f:
348 f.write('cheddar')
349 os.link(src, dst)
350 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
351 with open(src, 'r') as f:
352 self.assertEqual(f.read(), 'cheddar')
353 os.remove(dst)
354 finally:
355 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000356
Ned Deily5fddf862012-05-10 17:21:23 -0700357 @unittest.skipUnless(hasattr(os, 'chflags') and
358 hasattr(errno, 'EOPNOTSUPP') and
359 hasattr(errno, 'ENOTSUP'),
360 "requires os.chflags, EOPNOTSUPP & ENOTSUP")
361 def test_copystat_handles_harmless_chflags_errors(self):
362 tmpdir = self.mkdtemp()
363 file1 = os.path.join(tmpdir, 'file1')
364 file2 = os.path.join(tmpdir, 'file2')
365 self.write_file(file1, 'xxx')
366 self.write_file(file2, 'xxx')
367
368 def make_chflags_raiser(err):
369 ex = OSError()
370
371 def _chflags_raiser(path, flags):
372 ex.errno = err
373 raise ex
374 return _chflags_raiser
375 old_chflags = os.chflags
376 try:
377 for err in errno.EOPNOTSUPP, errno.ENOTSUP:
378 os.chflags = make_chflags_raiser(err)
379 shutil.copystat(file1, file2)
380 # assert others errors break it
381 os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
382 self.assertRaises(OSError, shutil.copystat, file1, file2)
383 finally:
384 os.chflags = old_chflags
385
Brian Curtin3b4499c2010-12-28 14:31:47 +0000386 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000387 def test_dont_copy_file_onto_symlink_to_itself(self):
388 # bug 851123.
389 os.mkdir(TESTFN)
390 src = os.path.join(TESTFN, 'cheese')
391 dst = os.path.join(TESTFN, 'shop')
392 try:
393 with open(src, 'w') as f:
394 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000395 # Using `src` here would mean we end up with a symlink pointing
396 # to TESTFN/TESTFN/cheese, while it should point at
397 # TESTFN/cheese.
398 os.symlink('cheese', dst)
399 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000400 with open(src, 'r') as f:
401 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000402 os.remove(dst)
403 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000404 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000405
Brian Curtin3b4499c2010-12-28 14:31:47 +0000406 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000407 def test_rmtree_on_symlink(self):
408 # bug 1669.
409 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000410 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000411 src = os.path.join(TESTFN, 'cheese')
412 dst = os.path.join(TESTFN, 'shop')
413 os.mkdir(src)
414 os.symlink(src, dst)
415 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000416 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000417 shutil.rmtree(TESTFN, ignore_errors=True)
418
419 if hasattr(os, "mkfifo"):
420 # Issue #3002: copyfile and copytree block indefinitely on named pipes
421 def test_copyfile_named_pipe(self):
422 os.mkfifo(TESTFN)
423 try:
424 self.assertRaises(shutil.SpecialFileError,
425 shutil.copyfile, TESTFN, TESTFN2)
426 self.assertRaises(shutil.SpecialFileError,
427 shutil.copyfile, __file__, TESTFN)
428 finally:
429 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000430
Brian Curtin3b4499c2010-12-28 14:31:47 +0000431 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000432 def test_copytree_named_pipe(self):
433 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000434 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000435 subdir = os.path.join(TESTFN, "subdir")
436 os.mkdir(subdir)
437 pipe = os.path.join(subdir, "mypipe")
438 os.mkfifo(pipe)
439 try:
440 shutil.copytree(TESTFN, TESTFN2)
441 except shutil.Error as e:
442 errors = e.args[0]
443 self.assertEqual(len(errors), 1)
444 src, dst, error_msg = errors[0]
445 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
446 else:
447 self.fail("shutil.Error should have been raised")
448 finally:
449 shutil.rmtree(TESTFN, ignore_errors=True)
450 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000451
Tarek Ziadé5340db32010-04-19 22:30:51 +0000452 def test_copytree_special_func(self):
453
454 src_dir = self.mkdtemp()
455 dst_dir = os.path.join(self.mkdtemp(), 'destination')
456 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
457 os.mkdir(os.path.join(src_dir, 'test_dir'))
458 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
459
460 copied = []
461 def _copy(src, dst):
462 copied.append((src, dst))
463
464 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000465 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000466
Brian Curtin3b4499c2010-12-28 14:31:47 +0000467 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000468 def test_copytree_dangling_symlinks(self):
469
470 # a dangling symlink raises an error at the end
471 src_dir = self.mkdtemp()
472 dst_dir = os.path.join(self.mkdtemp(), 'destination')
473 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
474 os.mkdir(os.path.join(src_dir, 'test_dir'))
475 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
476 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
477
478 # a dangling symlink is ignored with the proper flag
479 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
480 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
481 self.assertNotIn('test.txt', os.listdir(dst_dir))
482
483 # a dangling symlink is copied if symlinks=True
484 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
485 shutil.copytree(src_dir, dst_dir, symlinks=True)
486 self.assertIn('test.txt', os.listdir(dst_dir))
487
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400488 def _copy_file(self, method):
489 fname = 'test.txt'
490 tmpdir = self.mkdtemp()
491 self.write_file([tmpdir, fname])
492 file1 = os.path.join(tmpdir, fname)
493 tmpdir2 = self.mkdtemp()
494 method(file1, tmpdir2)
495 file2 = os.path.join(tmpdir2, fname)
496 return (file1, file2)
497
498 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
499 def test_copy(self):
500 # Ensure that the copied file exists and has the same mode bits.
501 file1, file2 = self._copy_file(shutil.copy)
502 self.assertTrue(os.path.exists(file2))
503 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
504
505 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
Senthil Kumaran0c2dba52011-07-03 18:21:38 -0700506 @unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400507 def test_copy2(self):
508 # Ensure that the copied file exists and has the same mode and
509 # modification time bits.
510 file1, file2 = self._copy_file(shutil.copy2)
511 self.assertTrue(os.path.exists(file2))
512 file1_stat = os.stat(file1)
513 file2_stat = os.stat(file2)
514 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
515 for attr in 'st_atime', 'st_mtime':
516 # The modification times may be truncated in the new file.
517 self.assertLessEqual(getattr(file1_stat, attr),
518 getattr(file2_stat, attr) + 1)
519 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
520 self.assertEqual(getattr(file1_stat, 'st_flags'),
521 getattr(file2_stat, 'st_flags'))
522
Tarek Ziadé396fad72010-02-23 05:30:31 +0000523 @unittest.skipUnless(zlib, "requires zlib")
524 def test_make_tarball(self):
525 # creating something to tar
526 tmpdir = self.mkdtemp()
527 self.write_file([tmpdir, 'file1'], 'xxx')
528 self.write_file([tmpdir, 'file2'], 'xxx')
529 os.mkdir(os.path.join(tmpdir, 'sub'))
530 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
531
532 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400533 # force shutil to create the directory
534 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000535 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
536 "source and target should be on same drive")
537
538 base_name = os.path.join(tmpdir2, 'archive')
539
540 # working with relative paths to avoid tar warnings
541 old_dir = os.getcwd()
542 os.chdir(tmpdir)
543 try:
544 _make_tarball(splitdrive(base_name)[1], '.')
545 finally:
546 os.chdir(old_dir)
547
548 # check if the compressed tarball was created
549 tarball = base_name + '.tar.gz'
550 self.assertTrue(os.path.exists(tarball))
551
552 # trying an uncompressed one
553 base_name = os.path.join(tmpdir2, 'archive')
554 old_dir = os.getcwd()
555 os.chdir(tmpdir)
556 try:
557 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
558 finally:
559 os.chdir(old_dir)
560 tarball = base_name + '.tar'
561 self.assertTrue(os.path.exists(tarball))
562
563 def _tarinfo(self, path):
564 tar = tarfile.open(path)
565 try:
566 names = tar.getnames()
567 names.sort()
568 return tuple(names)
569 finally:
570 tar.close()
571
572 def _create_files(self):
573 # creating something to tar
574 tmpdir = self.mkdtemp()
575 dist = os.path.join(tmpdir, 'dist')
576 os.mkdir(dist)
577 self.write_file([dist, 'file1'], 'xxx')
578 self.write_file([dist, 'file2'], 'xxx')
579 os.mkdir(os.path.join(dist, 'sub'))
580 self.write_file([dist, 'sub', 'file3'], 'xxx')
581 os.mkdir(os.path.join(dist, 'sub2'))
582 tmpdir2 = self.mkdtemp()
583 base_name = os.path.join(tmpdir2, 'archive')
584 return tmpdir, tmpdir2, base_name
585
586 @unittest.skipUnless(zlib, "Requires zlib")
587 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
588 'Need the tar command to run')
589 def test_tarfile_vs_tar(self):
590 tmpdir, tmpdir2, base_name = self._create_files()
591 old_dir = os.getcwd()
592 os.chdir(tmpdir)
593 try:
594 _make_tarball(base_name, 'dist')
595 finally:
596 os.chdir(old_dir)
597
598 # check if the compressed tarball was created
599 tarball = base_name + '.tar.gz'
600 self.assertTrue(os.path.exists(tarball))
601
602 # now create another tarball using `tar`
603 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
604 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
605 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
606 old_dir = os.getcwd()
607 os.chdir(tmpdir)
608 try:
609 with captured_stdout() as s:
610 spawn(tar_cmd)
611 spawn(gzip_cmd)
612 finally:
613 os.chdir(old_dir)
614
615 self.assertTrue(os.path.exists(tarball2))
616 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000617 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000618
619 # trying an uncompressed one
620 base_name = os.path.join(tmpdir2, 'archive')
621 old_dir = os.getcwd()
622 os.chdir(tmpdir)
623 try:
624 _make_tarball(base_name, 'dist', compress=None)
625 finally:
626 os.chdir(old_dir)
627 tarball = base_name + '.tar'
628 self.assertTrue(os.path.exists(tarball))
629
630 # now for a dry_run
631 base_name = os.path.join(tmpdir2, 'archive')
632 old_dir = os.getcwd()
633 os.chdir(tmpdir)
634 try:
635 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
636 finally:
637 os.chdir(old_dir)
638 tarball = base_name + '.tar'
639 self.assertTrue(os.path.exists(tarball))
640
Tarek Ziadé396fad72010-02-23 05:30:31 +0000641 @unittest.skipUnless(zlib, "Requires zlib")
642 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
643 def test_make_zipfile(self):
644 # creating something to tar
645 tmpdir = self.mkdtemp()
646 self.write_file([tmpdir, 'file1'], 'xxx')
647 self.write_file([tmpdir, 'file2'], 'xxx')
648
649 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400650 # force shutil to create the directory
651 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000652 base_name = os.path.join(tmpdir2, 'archive')
653 _make_zipfile(base_name, tmpdir)
654
655 # check if the compressed tarball was created
656 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000657 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000658
659
660 def test_make_archive(self):
661 tmpdir = self.mkdtemp()
662 base_name = os.path.join(tmpdir, 'archive')
663 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
664
665 @unittest.skipUnless(zlib, "Requires zlib")
666 def test_make_archive_owner_group(self):
667 # testing make_archive with owner and group, with various combinations
668 # this works even if there's not gid/uid support
669 if UID_GID_SUPPORT:
670 group = grp.getgrgid(0)[0]
671 owner = pwd.getpwuid(0)[0]
672 else:
673 group = owner = 'root'
674
675 base_dir, root_dir, base_name = self._create_files()
676 base_name = os.path.join(self.mkdtemp() , 'archive')
677 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
678 group=group)
679 self.assertTrue(os.path.exists(res))
680
681 res = make_archive(base_name, 'zip', root_dir, base_dir)
682 self.assertTrue(os.path.exists(res))
683
684 res = make_archive(base_name, 'tar', root_dir, base_dir,
685 owner=owner, group=group)
686 self.assertTrue(os.path.exists(res))
687
688 res = make_archive(base_name, 'tar', root_dir, base_dir,
689 owner='kjhkjhkjg', group='oihohoh')
690 self.assertTrue(os.path.exists(res))
691
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000692
Tarek Ziadé396fad72010-02-23 05:30:31 +0000693 @unittest.skipUnless(zlib, "Requires zlib")
694 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
695 def test_tarfile_root_owner(self):
696 tmpdir, tmpdir2, base_name = self._create_files()
697 old_dir = os.getcwd()
698 os.chdir(tmpdir)
699 group = grp.getgrgid(0)[0]
700 owner = pwd.getpwuid(0)[0]
701 try:
702 archive_name = _make_tarball(base_name, 'dist', compress=None,
703 owner=owner, group=group)
704 finally:
705 os.chdir(old_dir)
706
707 # check if the compressed tarball was created
708 self.assertTrue(os.path.exists(archive_name))
709
710 # now checks the rights
711 archive = tarfile.open(archive_name)
712 try:
713 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000714 self.assertEqual(member.uid, 0)
715 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000716 finally:
717 archive.close()
718
719 def test_make_archive_cwd(self):
720 current_dir = os.getcwd()
721 def _breaks(*args, **kw):
722 raise RuntimeError()
723
724 register_archive_format('xxx', _breaks, [], 'xxx file')
725 try:
726 try:
727 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
728 except Exception:
729 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000730 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000731 finally:
732 unregister_archive_format('xxx')
733
734 def test_register_archive_format(self):
735
736 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
737 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
738 1)
739 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
740 [(1, 2), (1, 2, 3)])
741
742 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
743 formats = [name for name, params in get_archive_formats()]
744 self.assertIn('xxx', formats)
745
746 unregister_archive_format('xxx')
747 formats = [name for name, params in get_archive_formats()]
748 self.assertNotIn('xxx', formats)
749
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000750 def _compare_dirs(self, dir1, dir2):
751 # check that dir1 and dir2 are equivalent,
752 # return the diff
753 diff = []
754 for root, dirs, files in os.walk(dir1):
755 for file_ in files:
756 path = os.path.join(root, file_)
757 target_path = os.path.join(dir2, os.path.split(path)[-1])
758 if not os.path.exists(target_path):
759 diff.append(file_)
760 return diff
761
762 @unittest.skipUnless(zlib, "Requires zlib")
763 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000764 formats = ['tar', 'gztar', 'zip']
765 if BZ2_SUPPORTED:
766 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000767
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000768 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000769 tmpdir = self.mkdtemp()
770 base_dir, root_dir, base_name = self._create_files()
771 tmpdir2 = self.mkdtemp()
772 filename = make_archive(base_name, format, root_dir, base_dir)
773
774 # let's try to unpack it now
775 unpack_archive(filename, tmpdir2)
776 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000777 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000778
Nick Coghlanabf202d2011-03-16 13:52:20 -0400779 # and again, this time with the format specified
780 tmpdir3 = self.mkdtemp()
781 unpack_archive(filename, tmpdir3, format=format)
782 diff = self._compare_dirs(tmpdir, tmpdir3)
783 self.assertEqual(diff, [])
784 self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
785 self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
786
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000787 def test_unpack_registery(self):
788
789 formats = get_unpack_formats()
790
791 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000792 self.assertEqual(extra, 1)
793 self.assertEqual(filename, 'stuff.boo')
794 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000795
796 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
797 unpack_archive('stuff.boo', 'xx')
798
799 # trying to register a .boo unpacker again
800 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
801 ['.boo'], _boo)
802
803 # should work now
804 unregister_unpack_format('Boo')
805 register_unpack_format('Boo2', ['.boo'], _boo)
806 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
807 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
808
809 # let's leave a clean state
810 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000811 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000812
Christian Heimes9bd667a2008-01-20 15:14:11 +0000813
Christian Heimesada8c3b2008-03-18 18:26:33 +0000814class TestMove(unittest.TestCase):
815
816 def setUp(self):
817 filename = "foo"
818 self.src_dir = tempfile.mkdtemp()
819 self.dst_dir = tempfile.mkdtemp()
820 self.src_file = os.path.join(self.src_dir, filename)
821 self.dst_file = os.path.join(self.dst_dir, filename)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000822 with open(self.src_file, "wb") as f:
823 f.write(b"spam")
824
825 def tearDown(self):
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400826 for d in (self.src_dir, self.dst_dir):
Christian Heimesada8c3b2008-03-18 18:26:33 +0000827 try:
828 if d:
829 shutil.rmtree(d)
830 except:
831 pass
832
833 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000834 with open(src, "rb") as f:
835 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000836 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000837 with open(real_dst, "rb") as f:
838 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000839 self.assertFalse(os.path.exists(src))
840
841 def _check_move_dir(self, src, dst, real_dst):
842 contents = sorted(os.listdir(src))
843 shutil.move(src, dst)
844 self.assertEqual(contents, sorted(os.listdir(real_dst)))
845 self.assertFalse(os.path.exists(src))
846
847 def test_move_file(self):
848 # Move a file to another location on the same filesystem.
849 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
850
851 def test_move_file_to_dir(self):
852 # Move a file inside an existing dir on the same filesystem.
853 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
854
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400855 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000856 def test_move_file_other_fs(self):
857 # Move a file to an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400858 self.test_move_file()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000859
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400860 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000861 def test_move_file_to_dir_other_fs(self):
862 # Move a file to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400863 self.test_move_file_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000864
865 def test_move_dir(self):
866 # Move a dir to another location on the same filesystem.
867 dst_dir = tempfile.mktemp()
868 try:
869 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
870 finally:
871 try:
872 shutil.rmtree(dst_dir)
873 except:
874 pass
875
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400876 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000877 def test_move_dir_other_fs(self):
878 # Move a dir to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400879 self.test_move_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000880
881 def test_move_dir_to_dir(self):
882 # Move a dir inside an existing dir on the same filesystem.
883 self._check_move_dir(self.src_dir, self.dst_dir,
884 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
885
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400886 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000887 def test_move_dir_to_dir_other_fs(self):
888 # Move a dir inside an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400889 self.test_move_dir_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000890
891 def test_existing_file_inside_dest_dir(self):
892 # A file with the same name inside the destination dir already exists.
893 with open(self.dst_file, "wb"):
894 pass
895 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
896
897 def test_dont_move_dir_in_itself(self):
898 # Moving a dir inside itself raises an Error.
899 dst = os.path.join(self.src_dir, "bar")
900 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
901
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000902 def test_destinsrc_false_negative(self):
903 os.mkdir(TESTFN)
904 try:
905 for src, dst in [('srcdir', 'srcdir/dest')]:
906 src = os.path.join(TESTFN, src)
907 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000908 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000909 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000910 'dst (%s) is not in src (%s)' % (dst, src))
911 finally:
912 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000913
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000914 def test_destinsrc_false_positive(self):
915 os.mkdir(TESTFN)
916 try:
917 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
918 src = os.path.join(TESTFN, src)
919 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000920 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000921 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000922 'dst (%s) is in src (%s)' % (dst, src))
923 finally:
924 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000925
Tarek Ziadé5340db32010-04-19 22:30:51 +0000926
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000927class TestCopyFile(unittest.TestCase):
928
929 _delete = False
930
931 class Faux(object):
932 _entered = False
933 _exited_with = None
934 _raised = False
935 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
936 self._raise_in_exit = raise_in_exit
937 self._suppress_at_exit = suppress_at_exit
938 def read(self, *args):
939 return ''
940 def __enter__(self):
941 self._entered = True
942 def __exit__(self, exc_type, exc_val, exc_tb):
943 self._exited_with = exc_type, exc_val, exc_tb
944 if self._raise_in_exit:
945 self._raised = True
946 raise IOError("Cannot close")
947 return self._suppress_at_exit
948
949 def tearDown(self):
950 if self._delete:
951 del shutil.open
952
953 def _set_shutil_open(self, func):
954 shutil.open = func
955 self._delete = True
956
957 def test_w_source_open_fails(self):
958 def _open(filename, mode='r'):
959 if filename == 'srcfile':
960 raise IOError('Cannot open "srcfile"')
961 assert 0 # shouldn't reach here.
962
963 self._set_shutil_open(_open)
964
965 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
966
967 def test_w_dest_open_fails(self):
968
969 srcfile = self.Faux()
970
971 def _open(filename, mode='r'):
972 if filename == 'srcfile':
973 return srcfile
974 if filename == 'destfile':
975 raise IOError('Cannot open "destfile"')
976 assert 0 # shouldn't reach here.
977
978 self._set_shutil_open(_open)
979
980 shutil.copyfile('srcfile', 'destfile')
981 self.assertTrue(srcfile._entered)
982 self.assertTrue(srcfile._exited_with[0] is IOError)
983 self.assertEqual(srcfile._exited_with[1].args,
984 ('Cannot open "destfile"',))
985
986 def test_w_dest_close_fails(self):
987
988 srcfile = self.Faux()
989 destfile = self.Faux(True)
990
991 def _open(filename, mode='r'):
992 if filename == 'srcfile':
993 return srcfile
994 if filename == 'destfile':
995 return destfile
996 assert 0 # shouldn't reach here.
997
998 self._set_shutil_open(_open)
999
1000 shutil.copyfile('srcfile', 'destfile')
1001 self.assertTrue(srcfile._entered)
1002 self.assertTrue(destfile._entered)
1003 self.assertTrue(destfile._raised)
1004 self.assertTrue(srcfile._exited_with[0] is IOError)
1005 self.assertEqual(srcfile._exited_with[1].args,
1006 ('Cannot close',))
1007
1008 def test_w_source_close_fails(self):
1009
1010 srcfile = self.Faux(True)
1011 destfile = self.Faux()
1012
1013 def _open(filename, mode='r'):
1014 if filename == 'srcfile':
1015 return srcfile
1016 if filename == 'destfile':
1017 return destfile
1018 assert 0 # shouldn't reach here.
1019
1020 self._set_shutil_open(_open)
1021
1022 self.assertRaises(IOError,
1023 shutil.copyfile, 'srcfile', 'destfile')
1024 self.assertTrue(srcfile._entered)
1025 self.assertTrue(destfile._entered)
1026 self.assertFalse(destfile._raised)
1027 self.assertTrue(srcfile._exited_with[0] is None)
1028 self.assertTrue(srcfile._raised)
1029
Ronald Oussorenf51738b2011-05-06 10:23:04 +02001030 def test_move_dir_caseinsensitive(self):
1031 # Renames a folder to the same name
1032 # but a different case.
1033
1034 self.src_dir = tempfile.mkdtemp()
1035 dst_dir = os.path.join(
1036 os.path.dirname(self.src_dir),
1037 os.path.basename(self.src_dir).upper())
1038 self.assertNotEqual(self.src_dir, dst_dir)
1039
1040 try:
1041 shutil.move(self.src_dir, dst_dir)
1042 self.assertTrue(os.path.isdir(dst_dir))
1043 finally:
1044 if os.path.exists(dst_dir):
1045 os.rmdir(dst_dir)
1046
1047
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001048
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001049def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001050 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001051
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001052if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +00001053 test_main()