blob: 9dab5f510d41dce6a9c2fad546cf613705efb8fc [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)
Hynek Schlawack9e8ac562012-12-10 10:07:11 +0100135 if os.name == 'nt':
136 rm_name = os.path.join(filename, '*.*')
137 else:
138 rm_name = filename
139 self.assertEqual(cm.exception.filename, rm_name)
Hynek Schlawackd16eacb2012-12-10 09:00:09 +0100140 self.assertTrue(os.path.exists(filename))
141 # test that ignore_errors option is honoured
142 shutil.rmtree(filename, ignore_errors=True)
143 self.assertTrue(os.path.exists(filename))
144 errors = []
145 def onerror(*args):
146 errors.append(args)
147 shutil.rmtree(filename, onerror=onerror)
148 self.assertEqual(len(errors), 2)
149 self.assertIs(errors[0][0], os.listdir)
150 self.assertEqual(errors[0][1], filename)
151 self.assertIsInstance(errors[0][2][1], OSError)
152 self.assertEqual(errors[0][2][1].filename, filename)
153 self.assertIs(errors[1][0], os.rmdir)
154 self.assertEqual(errors[1][1], filename)
155 self.assertIsInstance(errors[1][2][1], OSError)
156 self.assertEqual(errors[1][2][1].filename, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000157
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000158 # See bug #1071513 for why we don't run this on cygwin
159 # and bug #1076467 for why we don't run this as root.
160 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +0000161 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000162 def test_on_error(self):
163 self.errorState = 0
164 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +0000165 self.childpath = os.path.join(TESTFN, 'a')
166 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000167 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000168 old_dir_mode = os.stat(TESTFN).st_mode
169 old_child_mode = os.stat(self.childpath).st_mode
170 # Make unwritable.
171 os.chmod(self.childpath, stat.S_IREAD)
172 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000173
174 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000175 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000176 self.assertEqual(self.errorState, 2,
177 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000178
Tim Peters4590c002004-11-01 02:40:52 +0000179 # Make writable again.
180 os.chmod(TESTFN, old_dir_mode)
181 os.chmod(self.childpath, old_child_mode)
182
183 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000184 shutil.rmtree(TESTFN)
185
186 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000187 # test_rmtree_errors deliberately runs rmtree
188 # on a directory that is chmod 400, which will fail.
189 # This function is run when shutil.rmtree fails.
190 # 99.9% of the time it initially fails to remove
191 # a file in the directory, so the first time through
192 # func is os.remove.
193 # However, some Linux machines running ZFS on
194 # FUSE experienced a failure earlier in the process
195 # at os.listdir. The first failure may legally
196 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000197 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000198 if func is os.remove:
199 self.assertEqual(arg, self.childpath)
200 else:
201 self.assertIs(func, os.listdir,
202 "func must be either os.remove or os.listdir")
203 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000204 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000205 self.errorState = 1
206 else:
207 self.assertEqual(func, os.rmdir)
208 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000209 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000210 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000211
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000212 def test_rmtree_dont_delete_file(self):
213 # When called on a file instead of a directory, don't delete it.
214 handle, path = tempfile.mkstemp()
215 os.fdopen(handle).close()
216 self.assertRaises(OSError, shutil.rmtree, path)
217 os.remove(path)
218
Tarek Ziadé5340db32010-04-19 22:30:51 +0000219 def _write_data(self, path, data):
220 f = open(path, "w")
221 f.write(data)
222 f.close()
223
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000225
226 def read_data(path):
227 f = open(path)
228 data = f.read()
229 f.close()
230 return data
231
232 src_dir = tempfile.mkdtemp()
233 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000234 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000235 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000236 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000237
238 try:
239 shutil.copytree(src_dir, dst_dir)
240 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
241 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
242 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
243 'test.txt')))
244 actual = read_data(os.path.join(dst_dir, 'test.txt'))
245 self.assertEqual(actual, '123')
246 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
247 self.assertEqual(actual, '456')
248 finally:
249 for path in (
250 os.path.join(src_dir, 'test.txt'),
251 os.path.join(dst_dir, 'test.txt'),
252 os.path.join(src_dir, 'test_dir', 'test.txt'),
253 os.path.join(dst_dir, 'test_dir', 'test.txt'),
254 ):
255 if os.path.exists(path):
256 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000257 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000258 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000259 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000260 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000261 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000262
Georg Brandl2ee470f2008-07-16 12:55:28 +0000263 def test_copytree_with_exclude(self):
264
Georg Brandl2ee470f2008-07-16 12:55:28 +0000265 def read_data(path):
266 f = open(path)
267 data = f.read()
268 f.close()
269 return data
270
271 # creating data
272 join = os.path.join
273 exists = os.path.exists
274 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000275 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000276 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000277 self._write_data(join(src_dir, 'test.txt'), '123')
278 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000279 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000280 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000281 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000282 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000283 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
284 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000285 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
286 '456')
287 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
288 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000289
290
291 # testing glob-like patterns
292 try:
293 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
294 shutil.copytree(src_dir, dst_dir, ignore=patterns)
295 # checking the result: some elements should not be copied
296 self.assertTrue(exists(join(dst_dir, 'test.txt')))
297 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
298 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
299 finally:
300 if os.path.exists(dst_dir):
301 shutil.rmtree(dst_dir)
302 try:
303 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
304 shutil.copytree(src_dir, dst_dir, ignore=patterns)
305 # checking the result: some elements should not be copied
306 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
307 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
308 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
309 finally:
310 if os.path.exists(dst_dir):
311 shutil.rmtree(dst_dir)
312
313 # testing callable-style
314 try:
315 def _filter(src, names):
316 res = []
317 for name in names:
318 path = os.path.join(src, name)
319
320 if (os.path.isdir(path) and
321 path.split()[-1] == 'subdir'):
322 res.append(name)
323 elif os.path.splitext(path)[-1] in ('.py'):
324 res.append(name)
325 return res
326
327 shutil.copytree(src_dir, dst_dir, ignore=_filter)
328
329 # checking the result: some elements should not be copied
330 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
331 'test.py')))
332 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
333
334 finally:
335 if os.path.exists(dst_dir):
336 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000337 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000338 shutil.rmtree(src_dir)
339 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000340
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000341 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000342 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000343 # Temporarily disable test on Windows.
344 if os.name == 'nt':
345 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000346 # bug 851123.
347 os.mkdir(TESTFN)
348 src = os.path.join(TESTFN, 'cheese')
349 dst = os.path.join(TESTFN, 'shop')
350 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000351 with open(src, 'w') as f:
352 f.write('cheddar')
353 os.link(src, dst)
354 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
355 with open(src, 'r') as f:
356 self.assertEqual(f.read(), 'cheddar')
357 os.remove(dst)
358 finally:
359 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000360
Ned Deily5fddf862012-05-10 17:21:23 -0700361 @unittest.skipUnless(hasattr(os, 'chflags') and
362 hasattr(errno, 'EOPNOTSUPP') and
363 hasattr(errno, 'ENOTSUP'),
364 "requires os.chflags, EOPNOTSUPP & ENOTSUP")
365 def test_copystat_handles_harmless_chflags_errors(self):
366 tmpdir = self.mkdtemp()
367 file1 = os.path.join(tmpdir, 'file1')
368 file2 = os.path.join(tmpdir, 'file2')
369 self.write_file(file1, 'xxx')
370 self.write_file(file2, 'xxx')
371
372 def make_chflags_raiser(err):
373 ex = OSError()
374
375 def _chflags_raiser(path, flags):
376 ex.errno = err
377 raise ex
378 return _chflags_raiser
379 old_chflags = os.chflags
380 try:
381 for err in errno.EOPNOTSUPP, errno.ENOTSUP:
382 os.chflags = make_chflags_raiser(err)
383 shutil.copystat(file1, file2)
384 # assert others errors break it
385 os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
386 self.assertRaises(OSError, shutil.copystat, file1, file2)
387 finally:
388 os.chflags = old_chflags
389
Brian Curtin3b4499c2010-12-28 14:31:47 +0000390 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000391 def test_dont_copy_file_onto_symlink_to_itself(self):
392 # bug 851123.
393 os.mkdir(TESTFN)
394 src = os.path.join(TESTFN, 'cheese')
395 dst = os.path.join(TESTFN, 'shop')
396 try:
397 with open(src, 'w') as f:
398 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000399 # Using `src` here would mean we end up with a symlink pointing
400 # to TESTFN/TESTFN/cheese, while it should point at
401 # TESTFN/cheese.
402 os.symlink('cheese', dst)
403 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000404 with open(src, 'r') as f:
405 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000406 os.remove(dst)
407 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000408 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000409
Brian Curtin3b4499c2010-12-28 14:31:47 +0000410 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000411 def test_rmtree_on_symlink(self):
412 # bug 1669.
413 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000414 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000415 src = os.path.join(TESTFN, 'cheese')
416 dst = os.path.join(TESTFN, 'shop')
417 os.mkdir(src)
418 os.symlink(src, dst)
419 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000420 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000421 shutil.rmtree(TESTFN, ignore_errors=True)
422
423 if hasattr(os, "mkfifo"):
424 # Issue #3002: copyfile and copytree block indefinitely on named pipes
425 def test_copyfile_named_pipe(self):
426 os.mkfifo(TESTFN)
427 try:
428 self.assertRaises(shutil.SpecialFileError,
429 shutil.copyfile, TESTFN, TESTFN2)
430 self.assertRaises(shutil.SpecialFileError,
431 shutil.copyfile, __file__, TESTFN)
432 finally:
433 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000434
Brian Curtin3b4499c2010-12-28 14:31:47 +0000435 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000436 def test_copytree_named_pipe(self):
437 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000438 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000439 subdir = os.path.join(TESTFN, "subdir")
440 os.mkdir(subdir)
441 pipe = os.path.join(subdir, "mypipe")
442 os.mkfifo(pipe)
443 try:
444 shutil.copytree(TESTFN, TESTFN2)
445 except shutil.Error as e:
446 errors = e.args[0]
447 self.assertEqual(len(errors), 1)
448 src, dst, error_msg = errors[0]
449 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
450 else:
451 self.fail("shutil.Error should have been raised")
452 finally:
453 shutil.rmtree(TESTFN, ignore_errors=True)
454 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000455
Tarek Ziadé5340db32010-04-19 22:30:51 +0000456 def test_copytree_special_func(self):
457
458 src_dir = self.mkdtemp()
459 dst_dir = os.path.join(self.mkdtemp(), 'destination')
460 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
461 os.mkdir(os.path.join(src_dir, 'test_dir'))
462 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
463
464 copied = []
465 def _copy(src, dst):
466 copied.append((src, dst))
467
468 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000469 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000470
Brian Curtin3b4499c2010-12-28 14:31:47 +0000471 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000472 def test_copytree_dangling_symlinks(self):
473
474 # a dangling symlink raises an error at the end
475 src_dir = self.mkdtemp()
476 dst_dir = os.path.join(self.mkdtemp(), 'destination')
477 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
478 os.mkdir(os.path.join(src_dir, 'test_dir'))
479 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
480 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
481
482 # a dangling symlink is ignored with the proper flag
483 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
484 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
485 self.assertNotIn('test.txt', os.listdir(dst_dir))
486
487 # a dangling symlink is copied if symlinks=True
488 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
489 shutil.copytree(src_dir, dst_dir, symlinks=True)
490 self.assertIn('test.txt', os.listdir(dst_dir))
491
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400492 def _copy_file(self, method):
493 fname = 'test.txt'
494 tmpdir = self.mkdtemp()
495 self.write_file([tmpdir, fname])
496 file1 = os.path.join(tmpdir, fname)
497 tmpdir2 = self.mkdtemp()
498 method(file1, tmpdir2)
499 file2 = os.path.join(tmpdir2, fname)
500 return (file1, file2)
501
502 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
503 def test_copy(self):
504 # Ensure that the copied file exists and has the same mode bits.
505 file1, file2 = self._copy_file(shutil.copy)
506 self.assertTrue(os.path.exists(file2))
507 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
508
509 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
Senthil Kumaran0c2dba52011-07-03 18:21:38 -0700510 @unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400511 def test_copy2(self):
512 # Ensure that the copied file exists and has the same mode and
513 # modification time bits.
514 file1, file2 = self._copy_file(shutil.copy2)
515 self.assertTrue(os.path.exists(file2))
516 file1_stat = os.stat(file1)
517 file2_stat = os.stat(file2)
518 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
519 for attr in 'st_atime', 'st_mtime':
520 # The modification times may be truncated in the new file.
521 self.assertLessEqual(getattr(file1_stat, attr),
522 getattr(file2_stat, attr) + 1)
523 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
524 self.assertEqual(getattr(file1_stat, 'st_flags'),
525 getattr(file2_stat, 'st_flags'))
526
Tarek Ziadé396fad72010-02-23 05:30:31 +0000527 @unittest.skipUnless(zlib, "requires zlib")
528 def test_make_tarball(self):
529 # creating something to tar
530 tmpdir = self.mkdtemp()
531 self.write_file([tmpdir, 'file1'], 'xxx')
532 self.write_file([tmpdir, 'file2'], 'xxx')
533 os.mkdir(os.path.join(tmpdir, 'sub'))
534 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
535
536 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400537 # force shutil to create the directory
538 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000539 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
540 "source and target should be on same drive")
541
542 base_name = os.path.join(tmpdir2, 'archive')
543
544 # working with relative paths to avoid tar warnings
545 old_dir = os.getcwd()
546 os.chdir(tmpdir)
547 try:
548 _make_tarball(splitdrive(base_name)[1], '.')
549 finally:
550 os.chdir(old_dir)
551
552 # check if the compressed tarball was created
553 tarball = base_name + '.tar.gz'
554 self.assertTrue(os.path.exists(tarball))
555
556 # trying an uncompressed one
557 base_name = os.path.join(tmpdir2, 'archive')
558 old_dir = os.getcwd()
559 os.chdir(tmpdir)
560 try:
561 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
562 finally:
563 os.chdir(old_dir)
564 tarball = base_name + '.tar'
565 self.assertTrue(os.path.exists(tarball))
566
567 def _tarinfo(self, path):
568 tar = tarfile.open(path)
569 try:
570 names = tar.getnames()
571 names.sort()
572 return tuple(names)
573 finally:
574 tar.close()
575
576 def _create_files(self):
577 # creating something to tar
578 tmpdir = self.mkdtemp()
579 dist = os.path.join(tmpdir, 'dist')
580 os.mkdir(dist)
581 self.write_file([dist, 'file1'], 'xxx')
582 self.write_file([dist, 'file2'], 'xxx')
583 os.mkdir(os.path.join(dist, 'sub'))
584 self.write_file([dist, 'sub', 'file3'], 'xxx')
585 os.mkdir(os.path.join(dist, 'sub2'))
586 tmpdir2 = self.mkdtemp()
587 base_name = os.path.join(tmpdir2, 'archive')
588 return tmpdir, tmpdir2, base_name
589
590 @unittest.skipUnless(zlib, "Requires zlib")
591 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
592 'Need the tar command to run')
593 def test_tarfile_vs_tar(self):
594 tmpdir, tmpdir2, base_name = self._create_files()
595 old_dir = os.getcwd()
596 os.chdir(tmpdir)
597 try:
598 _make_tarball(base_name, 'dist')
599 finally:
600 os.chdir(old_dir)
601
602 # check if the compressed tarball was created
603 tarball = base_name + '.tar.gz'
604 self.assertTrue(os.path.exists(tarball))
605
606 # now create another tarball using `tar`
607 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
608 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
609 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
610 old_dir = os.getcwd()
611 os.chdir(tmpdir)
612 try:
613 with captured_stdout() as s:
614 spawn(tar_cmd)
615 spawn(gzip_cmd)
616 finally:
617 os.chdir(old_dir)
618
619 self.assertTrue(os.path.exists(tarball2))
620 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000621 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000622
623 # trying an uncompressed one
624 base_name = os.path.join(tmpdir2, 'archive')
625 old_dir = os.getcwd()
626 os.chdir(tmpdir)
627 try:
628 _make_tarball(base_name, 'dist', compress=None)
629 finally:
630 os.chdir(old_dir)
631 tarball = base_name + '.tar'
632 self.assertTrue(os.path.exists(tarball))
633
634 # now for a dry_run
635 base_name = os.path.join(tmpdir2, 'archive')
636 old_dir = os.getcwd()
637 os.chdir(tmpdir)
638 try:
639 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
640 finally:
641 os.chdir(old_dir)
642 tarball = base_name + '.tar'
643 self.assertTrue(os.path.exists(tarball))
644
Tarek Ziadé396fad72010-02-23 05:30:31 +0000645 @unittest.skipUnless(zlib, "Requires zlib")
646 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
647 def test_make_zipfile(self):
648 # creating something to tar
649 tmpdir = self.mkdtemp()
650 self.write_file([tmpdir, 'file1'], 'xxx')
651 self.write_file([tmpdir, 'file2'], 'xxx')
652
653 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400654 # force shutil to create the directory
655 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000656 base_name = os.path.join(tmpdir2, 'archive')
657 _make_zipfile(base_name, tmpdir)
658
659 # check if the compressed tarball was created
660 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000661 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000662
663
664 def test_make_archive(self):
665 tmpdir = self.mkdtemp()
666 base_name = os.path.join(tmpdir, 'archive')
667 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
668
669 @unittest.skipUnless(zlib, "Requires zlib")
670 def test_make_archive_owner_group(self):
671 # testing make_archive with owner and group, with various combinations
672 # this works even if there's not gid/uid support
673 if UID_GID_SUPPORT:
674 group = grp.getgrgid(0)[0]
675 owner = pwd.getpwuid(0)[0]
676 else:
677 group = owner = 'root'
678
679 base_dir, root_dir, base_name = self._create_files()
680 base_name = os.path.join(self.mkdtemp() , 'archive')
681 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
682 group=group)
683 self.assertTrue(os.path.exists(res))
684
685 res = make_archive(base_name, 'zip', root_dir, base_dir)
686 self.assertTrue(os.path.exists(res))
687
688 res = make_archive(base_name, 'tar', root_dir, base_dir,
689 owner=owner, group=group)
690 self.assertTrue(os.path.exists(res))
691
692 res = make_archive(base_name, 'tar', root_dir, base_dir,
693 owner='kjhkjhkjg', group='oihohoh')
694 self.assertTrue(os.path.exists(res))
695
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000696
Tarek Ziadé396fad72010-02-23 05:30:31 +0000697 @unittest.skipUnless(zlib, "Requires zlib")
698 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
699 def test_tarfile_root_owner(self):
700 tmpdir, tmpdir2, base_name = self._create_files()
701 old_dir = os.getcwd()
702 os.chdir(tmpdir)
703 group = grp.getgrgid(0)[0]
704 owner = pwd.getpwuid(0)[0]
705 try:
706 archive_name = _make_tarball(base_name, 'dist', compress=None,
707 owner=owner, group=group)
708 finally:
709 os.chdir(old_dir)
710
711 # check if the compressed tarball was created
712 self.assertTrue(os.path.exists(archive_name))
713
714 # now checks the rights
715 archive = tarfile.open(archive_name)
716 try:
717 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000718 self.assertEqual(member.uid, 0)
719 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000720 finally:
721 archive.close()
722
723 def test_make_archive_cwd(self):
724 current_dir = os.getcwd()
725 def _breaks(*args, **kw):
726 raise RuntimeError()
727
728 register_archive_format('xxx', _breaks, [], 'xxx file')
729 try:
730 try:
731 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
732 except Exception:
733 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000734 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000735 finally:
736 unregister_archive_format('xxx')
737
738 def test_register_archive_format(self):
739
740 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
741 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
742 1)
743 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
744 [(1, 2), (1, 2, 3)])
745
746 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
747 formats = [name for name, params in get_archive_formats()]
748 self.assertIn('xxx', formats)
749
750 unregister_archive_format('xxx')
751 formats = [name for name, params in get_archive_formats()]
752 self.assertNotIn('xxx', formats)
753
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000754 def _compare_dirs(self, dir1, dir2):
755 # check that dir1 and dir2 are equivalent,
756 # return the diff
757 diff = []
758 for root, dirs, files in os.walk(dir1):
759 for file_ in files:
760 path = os.path.join(root, file_)
761 target_path = os.path.join(dir2, os.path.split(path)[-1])
762 if not os.path.exists(target_path):
763 diff.append(file_)
764 return diff
765
766 @unittest.skipUnless(zlib, "Requires zlib")
767 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000768 formats = ['tar', 'gztar', 'zip']
769 if BZ2_SUPPORTED:
770 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000771
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000772 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000773 tmpdir = self.mkdtemp()
774 base_dir, root_dir, base_name = self._create_files()
775 tmpdir2 = self.mkdtemp()
776 filename = make_archive(base_name, format, root_dir, base_dir)
777
778 # let's try to unpack it now
779 unpack_archive(filename, tmpdir2)
780 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000781 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000782
Nick Coghlanabf202d2011-03-16 13:52:20 -0400783 # and again, this time with the format specified
784 tmpdir3 = self.mkdtemp()
785 unpack_archive(filename, tmpdir3, format=format)
786 diff = self._compare_dirs(tmpdir, tmpdir3)
787 self.assertEqual(diff, [])
788 self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
789 self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
790
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000791 def test_unpack_registery(self):
792
793 formats = get_unpack_formats()
794
795 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000796 self.assertEqual(extra, 1)
797 self.assertEqual(filename, 'stuff.boo')
798 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000799
800 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
801 unpack_archive('stuff.boo', 'xx')
802
803 # trying to register a .boo unpacker again
804 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
805 ['.boo'], _boo)
806
807 # should work now
808 unregister_unpack_format('Boo')
809 register_unpack_format('Boo2', ['.boo'], _boo)
810 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
811 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
812
813 # let's leave a clean state
814 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000815 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000816
Christian Heimes9bd667a2008-01-20 15:14:11 +0000817
Christian Heimesada8c3b2008-03-18 18:26:33 +0000818class TestMove(unittest.TestCase):
819
820 def setUp(self):
821 filename = "foo"
822 self.src_dir = tempfile.mkdtemp()
823 self.dst_dir = tempfile.mkdtemp()
824 self.src_file = os.path.join(self.src_dir, filename)
825 self.dst_file = os.path.join(self.dst_dir, filename)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000826 with open(self.src_file, "wb") as f:
827 f.write(b"spam")
828
829 def tearDown(self):
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400830 for d in (self.src_dir, self.dst_dir):
Christian Heimesada8c3b2008-03-18 18:26:33 +0000831 try:
832 if d:
833 shutil.rmtree(d)
834 except:
835 pass
836
837 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000838 with open(src, "rb") as f:
839 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000840 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000841 with open(real_dst, "rb") as f:
842 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000843 self.assertFalse(os.path.exists(src))
844
845 def _check_move_dir(self, src, dst, real_dst):
846 contents = sorted(os.listdir(src))
847 shutil.move(src, dst)
848 self.assertEqual(contents, sorted(os.listdir(real_dst)))
849 self.assertFalse(os.path.exists(src))
850
851 def test_move_file(self):
852 # Move a file to another location on the same filesystem.
853 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
854
855 def test_move_file_to_dir(self):
856 # Move a file inside an existing dir on the same filesystem.
857 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
858
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400859 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000860 def test_move_file_other_fs(self):
861 # Move a file to an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400862 self.test_move_file()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000863
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400864 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000865 def test_move_file_to_dir_other_fs(self):
866 # Move a file to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400867 self.test_move_file_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000868
869 def test_move_dir(self):
870 # Move a dir to another location on the same filesystem.
871 dst_dir = tempfile.mktemp()
872 try:
873 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
874 finally:
875 try:
876 shutil.rmtree(dst_dir)
877 except:
878 pass
879
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400880 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000881 def test_move_dir_other_fs(self):
882 # Move a dir to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400883 self.test_move_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000884
885 def test_move_dir_to_dir(self):
886 # Move a dir inside an existing dir on the same filesystem.
887 self._check_move_dir(self.src_dir, self.dst_dir,
888 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
889
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400890 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000891 def test_move_dir_to_dir_other_fs(self):
892 # Move a dir inside an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400893 self.test_move_dir_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000894
895 def test_existing_file_inside_dest_dir(self):
896 # A file with the same name inside the destination dir already exists.
897 with open(self.dst_file, "wb"):
898 pass
899 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
900
901 def test_dont_move_dir_in_itself(self):
902 # Moving a dir inside itself raises an Error.
903 dst = os.path.join(self.src_dir, "bar")
904 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
905
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000906 def test_destinsrc_false_negative(self):
907 os.mkdir(TESTFN)
908 try:
909 for src, dst in [('srcdir', 'srcdir/dest')]:
910 src = os.path.join(TESTFN, src)
911 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000912 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000913 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000914 'dst (%s) is not in src (%s)' % (dst, src))
915 finally:
916 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000917
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000918 def test_destinsrc_false_positive(self):
919 os.mkdir(TESTFN)
920 try:
921 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
922 src = os.path.join(TESTFN, src)
923 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000924 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000925 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000926 'dst (%s) is in src (%s)' % (dst, src))
927 finally:
928 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000929
Tarek Ziadé5340db32010-04-19 22:30:51 +0000930
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000931class TestCopyFile(unittest.TestCase):
932
933 _delete = False
934
935 class Faux(object):
936 _entered = False
937 _exited_with = None
938 _raised = False
939 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
940 self._raise_in_exit = raise_in_exit
941 self._suppress_at_exit = suppress_at_exit
942 def read(self, *args):
943 return ''
944 def __enter__(self):
945 self._entered = True
946 def __exit__(self, exc_type, exc_val, exc_tb):
947 self._exited_with = exc_type, exc_val, exc_tb
948 if self._raise_in_exit:
949 self._raised = True
950 raise IOError("Cannot close")
951 return self._suppress_at_exit
952
953 def tearDown(self):
954 if self._delete:
955 del shutil.open
956
957 def _set_shutil_open(self, func):
958 shutil.open = func
959 self._delete = True
960
961 def test_w_source_open_fails(self):
962 def _open(filename, mode='r'):
963 if filename == 'srcfile':
964 raise IOError('Cannot open "srcfile"')
965 assert 0 # shouldn't reach here.
966
967 self._set_shutil_open(_open)
968
969 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
970
971 def test_w_dest_open_fails(self):
972
973 srcfile = self.Faux()
974
975 def _open(filename, mode='r'):
976 if filename == 'srcfile':
977 return srcfile
978 if filename == 'destfile':
979 raise IOError('Cannot open "destfile"')
980 assert 0 # shouldn't reach here.
981
982 self._set_shutil_open(_open)
983
984 shutil.copyfile('srcfile', 'destfile')
985 self.assertTrue(srcfile._entered)
986 self.assertTrue(srcfile._exited_with[0] is IOError)
987 self.assertEqual(srcfile._exited_with[1].args,
988 ('Cannot open "destfile"',))
989
990 def test_w_dest_close_fails(self):
991
992 srcfile = self.Faux()
993 destfile = self.Faux(True)
994
995 def _open(filename, mode='r'):
996 if filename == 'srcfile':
997 return srcfile
998 if filename == 'destfile':
999 return destfile
1000 assert 0 # shouldn't reach here.
1001
1002 self._set_shutil_open(_open)
1003
1004 shutil.copyfile('srcfile', 'destfile')
1005 self.assertTrue(srcfile._entered)
1006 self.assertTrue(destfile._entered)
1007 self.assertTrue(destfile._raised)
1008 self.assertTrue(srcfile._exited_with[0] is IOError)
1009 self.assertEqual(srcfile._exited_with[1].args,
1010 ('Cannot close',))
1011
1012 def test_w_source_close_fails(self):
1013
1014 srcfile = self.Faux(True)
1015 destfile = self.Faux()
1016
1017 def _open(filename, mode='r'):
1018 if filename == 'srcfile':
1019 return srcfile
1020 if filename == 'destfile':
1021 return destfile
1022 assert 0 # shouldn't reach here.
1023
1024 self._set_shutil_open(_open)
1025
1026 self.assertRaises(IOError,
1027 shutil.copyfile, 'srcfile', 'destfile')
1028 self.assertTrue(srcfile._entered)
1029 self.assertTrue(destfile._entered)
1030 self.assertFalse(destfile._raised)
1031 self.assertTrue(srcfile._exited_with[0] is None)
1032 self.assertTrue(srcfile._raised)
1033
Ronald Oussorenf51738b2011-05-06 10:23:04 +02001034 def test_move_dir_caseinsensitive(self):
1035 # Renames a folder to the same name
1036 # but a different case.
1037
1038 self.src_dir = tempfile.mkdtemp()
1039 dst_dir = os.path.join(
1040 os.path.dirname(self.src_dir),
1041 os.path.basename(self.src_dir).upper())
1042 self.assertNotEqual(self.src_dir, dst_dir)
1043
1044 try:
1045 shutil.move(self.src_dir, dst_dir)
1046 self.assertTrue(os.path.isdir(dst_dir))
1047 finally:
1048 if os.path.exists(dst_dir):
1049 os.rmdir(dst_dir)
1050
1051
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001052
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001053def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001054 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001055
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001056if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +00001057 test_main()