blob: a9b4676dfff3bd6b38255986e18110eaaf29dfad [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 Schlawack87f9b462012-12-10 16:29:57 +0100135 # The reason for this rather odd construct is that Windows sprinkles
136 # a \*.* at the end of file names. But only sometimes on some buildbots
137 possible_args = [filename, os.path.join(filename, '*.*')]
138 self.assertIn(cm.exception.filename, possible_args)
Hynek Schlawackd16eacb2012-12-10 09:00:09 +0100139 self.assertTrue(os.path.exists(filename))
Hynek Schlawack87f9b462012-12-10 16:29:57 +0100140 # test that ignore_errors option is honored
Hynek Schlawackd16eacb2012-12-10 09:00:09 +0100141 shutil.rmtree(filename, ignore_errors=True)
142 self.assertTrue(os.path.exists(filename))
143 errors = []
144 def onerror(*args):
145 errors.append(args)
146 shutil.rmtree(filename, onerror=onerror)
147 self.assertEqual(len(errors), 2)
148 self.assertIs(errors[0][0], os.listdir)
149 self.assertEqual(errors[0][1], filename)
150 self.assertIsInstance(errors[0][2][1], OSError)
Hynek Schlawack87f9b462012-12-10 16:29:57 +0100151 self.assertIn(errors[0][2][1].filename, possible_args)
Hynek Schlawackd16eacb2012-12-10 09:00:09 +0100152 self.assertIs(errors[1][0], os.rmdir)
153 self.assertEqual(errors[1][1], filename)
154 self.assertIsInstance(errors[1][2][1], OSError)
Hynek Schlawack87f9b462012-12-10 16:29:57 +0100155 self.assertIn(errors[1][2][1].filename, possible_args)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000156
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000157 # See bug #1071513 for why we don't run this on cygwin
158 # and bug #1076467 for why we don't run this as root.
159 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +0000160 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000161 def test_on_error(self):
162 self.errorState = 0
163 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +0000164 self.childpath = os.path.join(TESTFN, 'a')
165 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000166 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000167 old_dir_mode = os.stat(TESTFN).st_mode
168 old_child_mode = os.stat(self.childpath).st_mode
169 # Make unwritable.
170 os.chmod(self.childpath, stat.S_IREAD)
171 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000172
173 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000174 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000175 self.assertEqual(self.errorState, 2,
176 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000177
Tim Peters4590c002004-11-01 02:40:52 +0000178 # Make writable again.
179 os.chmod(TESTFN, old_dir_mode)
180 os.chmod(self.childpath, old_child_mode)
181
182 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000183 shutil.rmtree(TESTFN)
184
185 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000186 # test_rmtree_errors deliberately runs rmtree
187 # on a directory that is chmod 400, which will fail.
188 # This function is run when shutil.rmtree fails.
189 # 99.9% of the time it initially fails to remove
190 # a file in the directory, so the first time through
191 # func is os.remove.
192 # However, some Linux machines running ZFS on
193 # FUSE experienced a failure earlier in the process
194 # at os.listdir. The first failure may legally
195 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000196 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000197 if func is os.remove:
198 self.assertEqual(arg, self.childpath)
199 else:
200 self.assertIs(func, os.listdir,
201 "func must be either os.remove or os.listdir")
202 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000203 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000204 self.errorState = 1
205 else:
206 self.assertEqual(func, os.rmdir)
207 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000208 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000209 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000210
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000211 def test_rmtree_dont_delete_file(self):
212 # When called on a file instead of a directory, don't delete it.
213 handle, path = tempfile.mkstemp()
214 os.fdopen(handle).close()
215 self.assertRaises(OSError, shutil.rmtree, path)
216 os.remove(path)
217
Tarek Ziadé5340db32010-04-19 22:30:51 +0000218 def _write_data(self, path, data):
219 f = open(path, "w")
220 f.write(data)
221 f.close()
222
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000223 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224
225 def read_data(path):
226 f = open(path)
227 data = f.read()
228 f.close()
229 return data
230
231 src_dir = tempfile.mkdtemp()
232 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000233 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000234 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000235 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000236
237 try:
238 shutil.copytree(src_dir, dst_dir)
239 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
240 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
241 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
242 'test.txt')))
243 actual = read_data(os.path.join(dst_dir, 'test.txt'))
244 self.assertEqual(actual, '123')
245 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
246 self.assertEqual(actual, '456')
247 finally:
248 for path in (
249 os.path.join(src_dir, 'test.txt'),
250 os.path.join(dst_dir, 'test.txt'),
251 os.path.join(src_dir, 'test_dir', 'test.txt'),
252 os.path.join(dst_dir, 'test_dir', 'test.txt'),
253 ):
254 if os.path.exists(path):
255 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000256 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000257 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000258 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000259 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000260 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000261
Georg Brandl2ee470f2008-07-16 12:55:28 +0000262 def test_copytree_with_exclude(self):
263
Georg Brandl2ee470f2008-07-16 12:55:28 +0000264 def read_data(path):
265 f = open(path)
266 data = f.read()
267 f.close()
268 return data
269
270 # creating data
271 join = os.path.join
272 exists = os.path.exists
273 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000274 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000275 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000276 self._write_data(join(src_dir, 'test.txt'), '123')
277 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000278 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000279 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000280 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000281 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000282 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
283 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000284 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
285 '456')
286 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
287 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000288
289
290 # testing glob-like patterns
291 try:
292 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
293 shutil.copytree(src_dir, dst_dir, ignore=patterns)
294 # checking the result: some elements should not be copied
295 self.assertTrue(exists(join(dst_dir, 'test.txt')))
296 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
297 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
298 finally:
299 if os.path.exists(dst_dir):
300 shutil.rmtree(dst_dir)
301 try:
302 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
303 shutil.copytree(src_dir, dst_dir, ignore=patterns)
304 # checking the result: some elements should not be copied
305 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
306 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
307 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
308 finally:
309 if os.path.exists(dst_dir):
310 shutil.rmtree(dst_dir)
311
312 # testing callable-style
313 try:
314 def _filter(src, names):
315 res = []
316 for name in names:
317 path = os.path.join(src, name)
318
319 if (os.path.isdir(path) and
320 path.split()[-1] == 'subdir'):
321 res.append(name)
322 elif os.path.splitext(path)[-1] in ('.py'):
323 res.append(name)
324 return res
325
326 shutil.copytree(src_dir, dst_dir, ignore=_filter)
327
328 # checking the result: some elements should not be copied
329 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
330 'test.py')))
331 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
332
333 finally:
334 if os.path.exists(dst_dir):
335 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000336 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000337 shutil.rmtree(src_dir)
338 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000339
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000340 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000341 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000342 # Temporarily disable test on Windows.
343 if os.name == 'nt':
344 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000345 # bug 851123.
346 os.mkdir(TESTFN)
347 src = os.path.join(TESTFN, 'cheese')
348 dst = os.path.join(TESTFN, 'shop')
349 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000350 with open(src, 'w') as f:
351 f.write('cheddar')
352 os.link(src, dst)
353 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
354 with open(src, 'r') as f:
355 self.assertEqual(f.read(), 'cheddar')
356 os.remove(dst)
357 finally:
358 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000359
Ned Deily5fddf862012-05-10 17:21:23 -0700360 @unittest.skipUnless(hasattr(os, 'chflags') and
361 hasattr(errno, 'EOPNOTSUPP') and
362 hasattr(errno, 'ENOTSUP'),
363 "requires os.chflags, EOPNOTSUPP & ENOTSUP")
364 def test_copystat_handles_harmless_chflags_errors(self):
365 tmpdir = self.mkdtemp()
366 file1 = os.path.join(tmpdir, 'file1')
367 file2 = os.path.join(tmpdir, 'file2')
368 self.write_file(file1, 'xxx')
369 self.write_file(file2, 'xxx')
370
371 def make_chflags_raiser(err):
372 ex = OSError()
373
374 def _chflags_raiser(path, flags):
375 ex.errno = err
376 raise ex
377 return _chflags_raiser
378 old_chflags = os.chflags
379 try:
380 for err in errno.EOPNOTSUPP, errno.ENOTSUP:
381 os.chflags = make_chflags_raiser(err)
382 shutil.copystat(file1, file2)
383 # assert others errors break it
384 os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
385 self.assertRaises(OSError, shutil.copystat, file1, file2)
386 finally:
387 os.chflags = old_chflags
388
Brian Curtin3b4499c2010-12-28 14:31:47 +0000389 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000390 def test_dont_copy_file_onto_symlink_to_itself(self):
391 # bug 851123.
392 os.mkdir(TESTFN)
393 src = os.path.join(TESTFN, 'cheese')
394 dst = os.path.join(TESTFN, 'shop')
395 try:
396 with open(src, 'w') as f:
397 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000398 # Using `src` here would mean we end up with a symlink pointing
399 # to TESTFN/TESTFN/cheese, while it should point at
400 # TESTFN/cheese.
401 os.symlink('cheese', dst)
402 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000403 with open(src, 'r') as f:
404 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000405 os.remove(dst)
406 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000407 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000408
Brian Curtin3b4499c2010-12-28 14:31:47 +0000409 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000410 def test_rmtree_on_symlink(self):
411 # bug 1669.
412 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000413 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000414 src = os.path.join(TESTFN, 'cheese')
415 dst = os.path.join(TESTFN, 'shop')
416 os.mkdir(src)
417 os.symlink(src, dst)
418 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000419 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000420 shutil.rmtree(TESTFN, ignore_errors=True)
421
422 if hasattr(os, "mkfifo"):
423 # Issue #3002: copyfile and copytree block indefinitely on named pipes
424 def test_copyfile_named_pipe(self):
425 os.mkfifo(TESTFN)
426 try:
427 self.assertRaises(shutil.SpecialFileError,
428 shutil.copyfile, TESTFN, TESTFN2)
429 self.assertRaises(shutil.SpecialFileError,
430 shutil.copyfile, __file__, TESTFN)
431 finally:
432 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000433
Brian Curtin3b4499c2010-12-28 14:31:47 +0000434 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000435 def test_copytree_named_pipe(self):
436 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000437 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000438 subdir = os.path.join(TESTFN, "subdir")
439 os.mkdir(subdir)
440 pipe = os.path.join(subdir, "mypipe")
441 os.mkfifo(pipe)
442 try:
443 shutil.copytree(TESTFN, TESTFN2)
444 except shutil.Error as e:
445 errors = e.args[0]
446 self.assertEqual(len(errors), 1)
447 src, dst, error_msg = errors[0]
448 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
449 else:
450 self.fail("shutil.Error should have been raised")
451 finally:
452 shutil.rmtree(TESTFN, ignore_errors=True)
453 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000454
Tarek Ziadé5340db32010-04-19 22:30:51 +0000455 def test_copytree_special_func(self):
456
457 src_dir = self.mkdtemp()
458 dst_dir = os.path.join(self.mkdtemp(), 'destination')
459 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
460 os.mkdir(os.path.join(src_dir, 'test_dir'))
461 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
462
463 copied = []
464 def _copy(src, dst):
465 copied.append((src, dst))
466
467 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000468 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000469
Brian Curtin3b4499c2010-12-28 14:31:47 +0000470 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000471 def test_copytree_dangling_symlinks(self):
472
473 # a dangling symlink raises an error at the end
474 src_dir = self.mkdtemp()
475 dst_dir = os.path.join(self.mkdtemp(), 'destination')
476 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
477 os.mkdir(os.path.join(src_dir, 'test_dir'))
478 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
479 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
480
481 # a dangling symlink is ignored with the proper flag
482 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
483 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
484 self.assertNotIn('test.txt', os.listdir(dst_dir))
485
486 # a dangling symlink is copied if symlinks=True
487 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
488 shutil.copytree(src_dir, dst_dir, symlinks=True)
489 self.assertIn('test.txt', os.listdir(dst_dir))
490
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400491 def _copy_file(self, method):
492 fname = 'test.txt'
493 tmpdir = self.mkdtemp()
494 self.write_file([tmpdir, fname])
495 file1 = os.path.join(tmpdir, fname)
496 tmpdir2 = self.mkdtemp()
497 method(file1, tmpdir2)
498 file2 = os.path.join(tmpdir2, fname)
499 return (file1, file2)
500
501 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
502 def test_copy(self):
503 # Ensure that the copied file exists and has the same mode bits.
504 file1, file2 = self._copy_file(shutil.copy)
505 self.assertTrue(os.path.exists(file2))
506 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
507
508 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
Senthil Kumaran0c2dba52011-07-03 18:21:38 -0700509 @unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400510 def test_copy2(self):
511 # Ensure that the copied file exists and has the same mode and
512 # modification time bits.
513 file1, file2 = self._copy_file(shutil.copy2)
514 self.assertTrue(os.path.exists(file2))
515 file1_stat = os.stat(file1)
516 file2_stat = os.stat(file2)
517 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
518 for attr in 'st_atime', 'st_mtime':
519 # The modification times may be truncated in the new file.
520 self.assertLessEqual(getattr(file1_stat, attr),
521 getattr(file2_stat, attr) + 1)
522 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
523 self.assertEqual(getattr(file1_stat, 'st_flags'),
524 getattr(file2_stat, 'st_flags'))
525
Tarek Ziadé396fad72010-02-23 05:30:31 +0000526 @unittest.skipUnless(zlib, "requires zlib")
527 def test_make_tarball(self):
528 # creating something to tar
529 tmpdir = self.mkdtemp()
530 self.write_file([tmpdir, 'file1'], 'xxx')
531 self.write_file([tmpdir, 'file2'], 'xxx')
532 os.mkdir(os.path.join(tmpdir, 'sub'))
533 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
534
535 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400536 # force shutil to create the directory
537 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000538 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
539 "source and target should be on same drive")
540
541 base_name = os.path.join(tmpdir2, 'archive')
542
543 # working with relative paths to avoid tar warnings
544 old_dir = os.getcwd()
545 os.chdir(tmpdir)
546 try:
547 _make_tarball(splitdrive(base_name)[1], '.')
548 finally:
549 os.chdir(old_dir)
550
551 # check if the compressed tarball was created
552 tarball = base_name + '.tar.gz'
553 self.assertTrue(os.path.exists(tarball))
554
555 # trying an uncompressed one
556 base_name = os.path.join(tmpdir2, 'archive')
557 old_dir = os.getcwd()
558 os.chdir(tmpdir)
559 try:
560 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
561 finally:
562 os.chdir(old_dir)
563 tarball = base_name + '.tar'
564 self.assertTrue(os.path.exists(tarball))
565
566 def _tarinfo(self, path):
567 tar = tarfile.open(path)
568 try:
569 names = tar.getnames()
570 names.sort()
571 return tuple(names)
572 finally:
573 tar.close()
574
575 def _create_files(self):
576 # creating something to tar
577 tmpdir = self.mkdtemp()
578 dist = os.path.join(tmpdir, 'dist')
579 os.mkdir(dist)
580 self.write_file([dist, 'file1'], 'xxx')
581 self.write_file([dist, 'file2'], 'xxx')
582 os.mkdir(os.path.join(dist, 'sub'))
583 self.write_file([dist, 'sub', 'file3'], 'xxx')
584 os.mkdir(os.path.join(dist, 'sub2'))
585 tmpdir2 = self.mkdtemp()
586 base_name = os.path.join(tmpdir2, 'archive')
587 return tmpdir, tmpdir2, base_name
588
589 @unittest.skipUnless(zlib, "Requires zlib")
590 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
591 'Need the tar command to run')
592 def test_tarfile_vs_tar(self):
593 tmpdir, tmpdir2, base_name = self._create_files()
594 old_dir = os.getcwd()
595 os.chdir(tmpdir)
596 try:
597 _make_tarball(base_name, 'dist')
598 finally:
599 os.chdir(old_dir)
600
601 # check if the compressed tarball was created
602 tarball = base_name + '.tar.gz'
603 self.assertTrue(os.path.exists(tarball))
604
605 # now create another tarball using `tar`
606 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
607 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
608 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
609 old_dir = os.getcwd()
610 os.chdir(tmpdir)
611 try:
612 with captured_stdout() as s:
613 spawn(tar_cmd)
614 spawn(gzip_cmd)
615 finally:
616 os.chdir(old_dir)
617
618 self.assertTrue(os.path.exists(tarball2))
619 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000620 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000621
622 # trying an uncompressed one
623 base_name = os.path.join(tmpdir2, 'archive')
624 old_dir = os.getcwd()
625 os.chdir(tmpdir)
626 try:
627 _make_tarball(base_name, 'dist', compress=None)
628 finally:
629 os.chdir(old_dir)
630 tarball = base_name + '.tar'
631 self.assertTrue(os.path.exists(tarball))
632
633 # now for a dry_run
634 base_name = os.path.join(tmpdir2, 'archive')
635 old_dir = os.getcwd()
636 os.chdir(tmpdir)
637 try:
638 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
639 finally:
640 os.chdir(old_dir)
641 tarball = base_name + '.tar'
642 self.assertTrue(os.path.exists(tarball))
643
Tarek Ziadé396fad72010-02-23 05:30:31 +0000644 @unittest.skipUnless(zlib, "Requires zlib")
645 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
646 def test_make_zipfile(self):
647 # creating something to tar
648 tmpdir = self.mkdtemp()
649 self.write_file([tmpdir, 'file1'], 'xxx')
650 self.write_file([tmpdir, 'file2'], 'xxx')
651
652 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400653 # force shutil to create the directory
654 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000655 base_name = os.path.join(tmpdir2, 'archive')
656 _make_zipfile(base_name, tmpdir)
657
658 # check if the compressed tarball was created
659 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000660 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000661
662
663 def test_make_archive(self):
664 tmpdir = self.mkdtemp()
665 base_name = os.path.join(tmpdir, 'archive')
666 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
667
668 @unittest.skipUnless(zlib, "Requires zlib")
669 def test_make_archive_owner_group(self):
670 # testing make_archive with owner and group, with various combinations
671 # this works even if there's not gid/uid support
672 if UID_GID_SUPPORT:
673 group = grp.getgrgid(0)[0]
674 owner = pwd.getpwuid(0)[0]
675 else:
676 group = owner = 'root'
677
678 base_dir, root_dir, base_name = self._create_files()
679 base_name = os.path.join(self.mkdtemp() , 'archive')
680 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
681 group=group)
682 self.assertTrue(os.path.exists(res))
683
684 res = make_archive(base_name, 'zip', root_dir, base_dir)
685 self.assertTrue(os.path.exists(res))
686
687 res = make_archive(base_name, 'tar', root_dir, base_dir,
688 owner=owner, group=group)
689 self.assertTrue(os.path.exists(res))
690
691 res = make_archive(base_name, 'tar', root_dir, base_dir,
692 owner='kjhkjhkjg', group='oihohoh')
693 self.assertTrue(os.path.exists(res))
694
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000695
Tarek Ziadé396fad72010-02-23 05:30:31 +0000696 @unittest.skipUnless(zlib, "Requires zlib")
697 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
698 def test_tarfile_root_owner(self):
699 tmpdir, tmpdir2, base_name = self._create_files()
700 old_dir = os.getcwd()
701 os.chdir(tmpdir)
702 group = grp.getgrgid(0)[0]
703 owner = pwd.getpwuid(0)[0]
704 try:
705 archive_name = _make_tarball(base_name, 'dist', compress=None,
706 owner=owner, group=group)
707 finally:
708 os.chdir(old_dir)
709
710 # check if the compressed tarball was created
711 self.assertTrue(os.path.exists(archive_name))
712
713 # now checks the rights
714 archive = tarfile.open(archive_name)
715 try:
716 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000717 self.assertEqual(member.uid, 0)
718 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000719 finally:
720 archive.close()
721
722 def test_make_archive_cwd(self):
723 current_dir = os.getcwd()
724 def _breaks(*args, **kw):
725 raise RuntimeError()
726
727 register_archive_format('xxx', _breaks, [], 'xxx file')
728 try:
729 try:
730 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
731 except Exception:
732 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000733 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000734 finally:
735 unregister_archive_format('xxx')
736
737 def test_register_archive_format(self):
738
739 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
740 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
741 1)
742 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
743 [(1, 2), (1, 2, 3)])
744
745 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
746 formats = [name for name, params in get_archive_formats()]
747 self.assertIn('xxx', formats)
748
749 unregister_archive_format('xxx')
750 formats = [name for name, params in get_archive_formats()]
751 self.assertNotIn('xxx', formats)
752
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000753 def _compare_dirs(self, dir1, dir2):
754 # check that dir1 and dir2 are equivalent,
755 # return the diff
756 diff = []
757 for root, dirs, files in os.walk(dir1):
758 for file_ in files:
759 path = os.path.join(root, file_)
760 target_path = os.path.join(dir2, os.path.split(path)[-1])
761 if not os.path.exists(target_path):
762 diff.append(file_)
763 return diff
764
765 @unittest.skipUnless(zlib, "Requires zlib")
766 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000767 formats = ['tar', 'gztar', 'zip']
768 if BZ2_SUPPORTED:
769 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000770
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000771 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000772 tmpdir = self.mkdtemp()
773 base_dir, root_dir, base_name = self._create_files()
774 tmpdir2 = self.mkdtemp()
775 filename = make_archive(base_name, format, root_dir, base_dir)
776
777 # let's try to unpack it now
778 unpack_archive(filename, tmpdir2)
779 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000780 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000781
Nick Coghlanabf202d2011-03-16 13:52:20 -0400782 # and again, this time with the format specified
783 tmpdir3 = self.mkdtemp()
784 unpack_archive(filename, tmpdir3, format=format)
785 diff = self._compare_dirs(tmpdir, tmpdir3)
786 self.assertEqual(diff, [])
787 self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
788 self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
789
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000790 def test_unpack_registery(self):
791
792 formats = get_unpack_formats()
793
794 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000795 self.assertEqual(extra, 1)
796 self.assertEqual(filename, 'stuff.boo')
797 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000798
799 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
800 unpack_archive('stuff.boo', 'xx')
801
802 # trying to register a .boo unpacker again
803 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
804 ['.boo'], _boo)
805
806 # should work now
807 unregister_unpack_format('Boo')
808 register_unpack_format('Boo2', ['.boo'], _boo)
809 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
810 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
811
812 # let's leave a clean state
813 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000814 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000815
Christian Heimes9bd667a2008-01-20 15:14:11 +0000816
Christian Heimesada8c3b2008-03-18 18:26:33 +0000817class TestMove(unittest.TestCase):
818
819 def setUp(self):
820 filename = "foo"
821 self.src_dir = tempfile.mkdtemp()
822 self.dst_dir = tempfile.mkdtemp()
823 self.src_file = os.path.join(self.src_dir, filename)
824 self.dst_file = os.path.join(self.dst_dir, filename)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000825 with open(self.src_file, "wb") as f:
826 f.write(b"spam")
827
828 def tearDown(self):
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400829 for d in (self.src_dir, self.dst_dir):
Christian Heimesada8c3b2008-03-18 18:26:33 +0000830 try:
831 if d:
832 shutil.rmtree(d)
833 except:
834 pass
835
836 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000837 with open(src, "rb") as f:
838 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000839 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000840 with open(real_dst, "rb") as f:
841 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000842 self.assertFalse(os.path.exists(src))
843
844 def _check_move_dir(self, src, dst, real_dst):
845 contents = sorted(os.listdir(src))
846 shutil.move(src, dst)
847 self.assertEqual(contents, sorted(os.listdir(real_dst)))
848 self.assertFalse(os.path.exists(src))
849
850 def test_move_file(self):
851 # Move a file to another location on the same filesystem.
852 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
853
854 def test_move_file_to_dir(self):
855 # Move a file inside an existing dir on the same filesystem.
856 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
857
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400858 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000859 def test_move_file_other_fs(self):
860 # Move a file to an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400861 self.test_move_file()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000862
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400863 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000864 def test_move_file_to_dir_other_fs(self):
865 # Move a file to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400866 self.test_move_file_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000867
868 def test_move_dir(self):
869 # Move a dir to another location on the same filesystem.
870 dst_dir = tempfile.mktemp()
871 try:
872 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
873 finally:
874 try:
875 shutil.rmtree(dst_dir)
876 except:
877 pass
878
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400879 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000880 def test_move_dir_other_fs(self):
881 # Move a dir to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400882 self.test_move_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000883
884 def test_move_dir_to_dir(self):
885 # Move a dir inside an existing dir on the same filesystem.
886 self._check_move_dir(self.src_dir, self.dst_dir,
887 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
888
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400889 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000890 def test_move_dir_to_dir_other_fs(self):
891 # Move a dir inside an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400892 self.test_move_dir_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000893
894 def test_existing_file_inside_dest_dir(self):
895 # A file with the same name inside the destination dir already exists.
896 with open(self.dst_file, "wb"):
897 pass
898 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
899
900 def test_dont_move_dir_in_itself(self):
901 # Moving a dir inside itself raises an Error.
902 dst = os.path.join(self.src_dir, "bar")
903 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
904
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000905 def test_destinsrc_false_negative(self):
906 os.mkdir(TESTFN)
907 try:
908 for src, dst in [('srcdir', 'srcdir/dest')]:
909 src = os.path.join(TESTFN, src)
910 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000911 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000912 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000913 'dst (%s) is not in src (%s)' % (dst, src))
914 finally:
915 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000916
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000917 def test_destinsrc_false_positive(self):
918 os.mkdir(TESTFN)
919 try:
920 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
921 src = os.path.join(TESTFN, src)
922 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000923 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000924 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000925 'dst (%s) is in src (%s)' % (dst, src))
926 finally:
927 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000928
Tarek Ziadé5340db32010-04-19 22:30:51 +0000929
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000930class TestCopyFile(unittest.TestCase):
931
932 _delete = False
933
934 class Faux(object):
935 _entered = False
936 _exited_with = None
937 _raised = False
938 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
939 self._raise_in_exit = raise_in_exit
940 self._suppress_at_exit = suppress_at_exit
941 def read(self, *args):
942 return ''
943 def __enter__(self):
944 self._entered = True
945 def __exit__(self, exc_type, exc_val, exc_tb):
946 self._exited_with = exc_type, exc_val, exc_tb
947 if self._raise_in_exit:
948 self._raised = True
949 raise IOError("Cannot close")
950 return self._suppress_at_exit
951
952 def tearDown(self):
953 if self._delete:
954 del shutil.open
955
956 def _set_shutil_open(self, func):
957 shutil.open = func
958 self._delete = True
959
960 def test_w_source_open_fails(self):
961 def _open(filename, mode='r'):
962 if filename == 'srcfile':
963 raise IOError('Cannot open "srcfile"')
964 assert 0 # shouldn't reach here.
965
966 self._set_shutil_open(_open)
967
968 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
969
970 def test_w_dest_open_fails(self):
971
972 srcfile = self.Faux()
973
974 def _open(filename, mode='r'):
975 if filename == 'srcfile':
976 return srcfile
977 if filename == 'destfile':
978 raise IOError('Cannot open "destfile"')
979 assert 0 # shouldn't reach here.
980
981 self._set_shutil_open(_open)
982
983 shutil.copyfile('srcfile', 'destfile')
984 self.assertTrue(srcfile._entered)
985 self.assertTrue(srcfile._exited_with[0] is IOError)
986 self.assertEqual(srcfile._exited_with[1].args,
987 ('Cannot open "destfile"',))
988
989 def test_w_dest_close_fails(self):
990
991 srcfile = self.Faux()
992 destfile = self.Faux(True)
993
994 def _open(filename, mode='r'):
995 if filename == 'srcfile':
996 return srcfile
997 if filename == 'destfile':
998 return destfile
999 assert 0 # shouldn't reach here.
1000
1001 self._set_shutil_open(_open)
1002
1003 shutil.copyfile('srcfile', 'destfile')
1004 self.assertTrue(srcfile._entered)
1005 self.assertTrue(destfile._entered)
1006 self.assertTrue(destfile._raised)
1007 self.assertTrue(srcfile._exited_with[0] is IOError)
1008 self.assertEqual(srcfile._exited_with[1].args,
1009 ('Cannot close',))
1010
1011 def test_w_source_close_fails(self):
1012
1013 srcfile = self.Faux(True)
1014 destfile = self.Faux()
1015
1016 def _open(filename, mode='r'):
1017 if filename == 'srcfile':
1018 return srcfile
1019 if filename == 'destfile':
1020 return destfile
1021 assert 0 # shouldn't reach here.
1022
1023 self._set_shutil_open(_open)
1024
1025 self.assertRaises(IOError,
1026 shutil.copyfile, 'srcfile', 'destfile')
1027 self.assertTrue(srcfile._entered)
1028 self.assertTrue(destfile._entered)
1029 self.assertFalse(destfile._raised)
1030 self.assertTrue(srcfile._exited_with[0] is None)
1031 self.assertTrue(srcfile._raised)
1032
Ronald Oussorenf51738b2011-05-06 10:23:04 +02001033 def test_move_dir_caseinsensitive(self):
1034 # Renames a folder to the same name
1035 # but a different case.
1036
1037 self.src_dir = tempfile.mkdtemp()
1038 dst_dir = os.path.join(
1039 os.path.dirname(self.src_dir),
1040 os.path.basename(self.src_dir).upper())
1041 self.assertNotEqual(self.src_dir, dst_dir)
1042
1043 try:
1044 shutil.move(self.src_dir, dst_dir)
1045 self.assertTrue(os.path.isdir(dst_dir))
1046 finally:
1047 if os.path.exists(dst_dir):
1048 os.rmdir(dst_dir)
1049
1050
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001051
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001052def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001053 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001054
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001055if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +00001056 test_main()