blob: b16980393ce7858445a4f11994ecd155990bbf53 [file] [log] [blame]
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001# Copyright (C) 2003 Python Software Foundation
2
3import unittest
4import shutil
5import tempfile
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +00006import sys
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +00007import stat
Brett Cannon1c3fa182004-06-19 21:11:35 +00008import os
9import os.path
Nick Coghlan8ed3cf32011-03-16 14:05:35 -040010import functools
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
12from test.support import TESTFN
Tarek Ziadé396fad72010-02-23 05:30:31 +000013from os.path import splitdrive
14from distutils.spawn import find_executable, spawn
15from shutil import (_make_tarball, _make_zipfile, make_archive,
16 register_archive_format, unregister_archive_format,
Tarek Ziadé6ac91722010-04-28 17:51:36 +000017 get_archive_formats, Error, unpack_archive,
18 register_unpack_format, RegistryError,
19 unregister_unpack_format, get_unpack_formats)
Tarek Ziadé396fad72010-02-23 05:30:31 +000020import tarfile
21import warnings
22
23from test import support
Ezio Melotti975077a2011-05-19 22:03:22 +030024from test.support import TESTFN, check_warnings, captured_stdout, requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +000025
Tarek Ziadéffa155a2010-04-29 13:34:35 +000026try:
27 import bz2
28 BZ2_SUPPORTED = True
29except ImportError:
30 BZ2_SUPPORTED = False
31
Antoine Pitrou7fff0962009-05-01 21:09:44 +000032TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000033
Tarek Ziadé396fad72010-02-23 05:30:31 +000034try:
35 import grp
36 import pwd
37 UID_GID_SUPPORT = True
38except ImportError:
39 UID_GID_SUPPORT = False
40
41try:
Tarek Ziadé396fad72010-02-23 05:30:31 +000042 import zipfile
43 ZIP_SUPPORT = True
44except ImportError:
45 ZIP_SUPPORT = find_executable('zip')
46
Nick Coghlan8ed3cf32011-03-16 14:05:35 -040047def _fake_rename(*args, **kwargs):
48 # Pretend the destination path is on a different filesystem.
49 raise OSError()
50
51def mock_rename(func):
52 @functools.wraps(func)
53 def wrap(*args, **kwargs):
54 try:
55 builtin_rename = os.rename
56 os.rename = _fake_rename
57 return func(*args, **kwargs)
58 finally:
59 os.rename = builtin_rename
60 return wrap
61
Éric Araujoa7e33a12011-08-12 19:51:35 +020062def write_file(path, content, binary=False):
63 """Write *content* to a file located at *path*.
64
65 If *path* is a tuple instead of a string, os.path.join will be used to
66 make a path. If *binary* is true, the file will be opened in binary
67 mode.
68 """
69 if isinstance(path, tuple):
70 path = os.path.join(*path)
71 with open(path, 'wb' if binary else 'w') as fp:
72 fp.write(content)
73
74def read_file(path, binary=False):
75 """Return contents from a file located at *path*.
76
77 If *path* is a tuple instead of a string, os.path.join will be used to
78 make a path. If *binary* is true, the file will be opened in binary
79 mode.
80 """
81 if isinstance(path, tuple):
82 path = os.path.join(*path)
83 with open(path, 'rb' if binary else 'r') as fp:
84 return fp.read()
85
86
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000087class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000088
89 def setUp(self):
90 super(TestShutil, self).setUp()
91 self.tempdirs = []
92
93 def tearDown(self):
94 super(TestShutil, self).tearDown()
95 while self.tempdirs:
96 d = self.tempdirs.pop()
97 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
98
Tarek Ziadé396fad72010-02-23 05:30:31 +000099
100 def mkdtemp(self):
101 """Create a temporary directory that will be cleaned up.
102
103 Returns the path of the directory.
104 """
105 d = tempfile.mkdtemp()
106 self.tempdirs.append(d)
107 return d
Tarek Ziadé5340db32010-04-19 22:30:51 +0000108
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000109 def test_rmtree_errors(self):
110 # filename is guaranteed not to exist
111 filename = tempfile.mktemp()
112 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000113
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000114 # See bug #1071513 for why we don't run this on cygwin
115 # and bug #1076467 for why we don't run this as root.
116 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +0000117 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000118 def test_on_error(self):
119 self.errorState = 0
120 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +0000121 self.childpath = os.path.join(TESTFN, 'a')
Victor Stinnerbf816222011-06-30 23:25:47 +0200122 support.create_empty_file(self.childpath)
Tim Peters4590c002004-11-01 02:40:52 +0000123 old_dir_mode = os.stat(TESTFN).st_mode
124 old_child_mode = os.stat(self.childpath).st_mode
125 # Make unwritable.
126 os.chmod(self.childpath, stat.S_IREAD)
127 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000128
129 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000130 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000131 self.assertEqual(self.errorState, 2,
132 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000133
Tim Peters4590c002004-11-01 02:40:52 +0000134 # Make writable again.
135 os.chmod(TESTFN, old_dir_mode)
136 os.chmod(self.childpath, old_child_mode)
137
138 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000139 shutil.rmtree(TESTFN)
140
141 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000142 # test_rmtree_errors deliberately runs rmtree
143 # on a directory that is chmod 400, which will fail.
144 # This function is run when shutil.rmtree fails.
145 # 99.9% of the time it initially fails to remove
146 # a file in the directory, so the first time through
147 # func is os.remove.
148 # However, some Linux machines running ZFS on
149 # FUSE experienced a failure earlier in the process
150 # at os.listdir. The first failure may legally
151 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000152 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000153 if func is os.remove:
154 self.assertEqual(arg, self.childpath)
155 else:
156 self.assertIs(func, os.listdir,
157 "func must be either os.remove or os.listdir")
158 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000159 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000160 self.errorState = 1
161 else:
162 self.assertEqual(func, os.rmdir)
163 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000164 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000165 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000166
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000167 def test_rmtree_dont_delete_file(self):
168 # When called on a file instead of a directory, don't delete it.
169 handle, path = tempfile.mkstemp()
Victor Stinnerbf816222011-06-30 23:25:47 +0200170 os.close(handle)
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000171 self.assertRaises(OSError, shutil.rmtree, path)
172 os.remove(path)
173
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000174 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000175 src_dir = tempfile.mkdtemp()
176 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Éric Araujoa7e33a12011-08-12 19:51:35 +0200177 self.addCleanup(shutil.rmtree, src_dir)
178 self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
179 write_file((src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000180 os.mkdir(os.path.join(src_dir, 'test_dir'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200181 write_file((src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000182
Éric Araujoa7e33a12011-08-12 19:51:35 +0200183 shutil.copytree(src_dir, dst_dir)
184 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
185 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
186 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
187 'test.txt')))
188 actual = read_file((dst_dir, 'test.txt'))
189 self.assertEqual(actual, '123')
190 actual = read_file((dst_dir, 'test_dir', 'test.txt'))
191 self.assertEqual(actual, '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000192
Georg Brandl2ee470f2008-07-16 12:55:28 +0000193 def test_copytree_with_exclude(self):
Georg Brandl2ee470f2008-07-16 12:55:28 +0000194 # creating data
195 join = os.path.join
196 exists = os.path.exists
197 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000198 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000199 dst_dir = join(tempfile.mkdtemp(), 'destination')
Éric Araujoa7e33a12011-08-12 19:51:35 +0200200 write_file((src_dir, 'test.txt'), '123')
201 write_file((src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000202 os.mkdir(join(src_dir, 'test_dir'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200203 write_file((src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000204 os.mkdir(join(src_dir, 'test_dir2'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200205 write_file((src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000206 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
207 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200208 write_file((src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
209 write_file((src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000210
211 # testing glob-like patterns
212 try:
213 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
214 shutil.copytree(src_dir, dst_dir, ignore=patterns)
215 # checking the result: some elements should not be copied
216 self.assertTrue(exists(join(dst_dir, 'test.txt')))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200217 self.assertFalse(exists(join(dst_dir, 'test.tmp')))
218 self.assertFalse(exists(join(dst_dir, 'test_dir2')))
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000219 finally:
Éric Araujoa7e33a12011-08-12 19:51:35 +0200220 shutil.rmtree(dst_dir)
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000221 try:
222 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
223 shutil.copytree(src_dir, dst_dir, ignore=patterns)
224 # checking the result: some elements should not be copied
Éric Araujoa7e33a12011-08-12 19:51:35 +0200225 self.assertFalse(exists(join(dst_dir, 'test.tmp')))
226 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2')))
227 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000228 finally:
Éric Araujoa7e33a12011-08-12 19:51:35 +0200229 shutil.rmtree(dst_dir)
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000230
231 # testing callable-style
232 try:
233 def _filter(src, names):
234 res = []
235 for name in names:
236 path = os.path.join(src, name)
237
238 if (os.path.isdir(path) and
239 path.split()[-1] == 'subdir'):
240 res.append(name)
241 elif os.path.splitext(path)[-1] in ('.py'):
242 res.append(name)
243 return res
244
245 shutil.copytree(src_dir, dst_dir, ignore=_filter)
246
247 # checking the result: some elements should not be copied
Éric Araujoa7e33a12011-08-12 19:51:35 +0200248 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2',
249 'test.py')))
250 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000251
252 finally:
Éric Araujoa7e33a12011-08-12 19:51:35 +0200253 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000254 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000255 shutil.rmtree(src_dir)
256 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000257
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000258 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000259 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000260 # Temporarily disable test on Windows.
261 if os.name == 'nt':
262 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000263 # bug 851123.
264 os.mkdir(TESTFN)
265 src = os.path.join(TESTFN, 'cheese')
266 dst = os.path.join(TESTFN, 'shop')
267 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000268 with open(src, 'w') as f:
269 f.write('cheddar')
270 os.link(src, dst)
271 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
272 with open(src, 'r') as f:
273 self.assertEqual(f.read(), 'cheddar')
274 os.remove(dst)
275 finally:
276 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000277
Brian Curtin3b4499c2010-12-28 14:31:47 +0000278 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000279 def test_dont_copy_file_onto_symlink_to_itself(self):
280 # bug 851123.
281 os.mkdir(TESTFN)
282 src = os.path.join(TESTFN, 'cheese')
283 dst = os.path.join(TESTFN, 'shop')
284 try:
285 with open(src, 'w') as f:
286 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000287 # Using `src` here would mean we end up with a symlink pointing
288 # to TESTFN/TESTFN/cheese, while it should point at
289 # TESTFN/cheese.
290 os.symlink('cheese', dst)
291 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000292 with open(src, 'r') as f:
293 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000294 os.remove(dst)
295 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000296 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000297
Brian Curtin3b4499c2010-12-28 14:31:47 +0000298 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000299 def test_rmtree_on_symlink(self):
300 # bug 1669.
301 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000302 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000303 src = os.path.join(TESTFN, 'cheese')
304 dst = os.path.join(TESTFN, 'shop')
305 os.mkdir(src)
306 os.symlink(src, dst)
307 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000308 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000309 shutil.rmtree(TESTFN, ignore_errors=True)
310
311 if hasattr(os, "mkfifo"):
312 # Issue #3002: copyfile and copytree block indefinitely on named pipes
313 def test_copyfile_named_pipe(self):
314 os.mkfifo(TESTFN)
315 try:
316 self.assertRaises(shutil.SpecialFileError,
317 shutil.copyfile, TESTFN, TESTFN2)
318 self.assertRaises(shutil.SpecialFileError,
319 shutil.copyfile, __file__, TESTFN)
320 finally:
321 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000322
Brian Curtin3b4499c2010-12-28 14:31:47 +0000323 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000324 def test_copytree_named_pipe(self):
325 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000326 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000327 subdir = os.path.join(TESTFN, "subdir")
328 os.mkdir(subdir)
329 pipe = os.path.join(subdir, "mypipe")
330 os.mkfifo(pipe)
331 try:
332 shutil.copytree(TESTFN, TESTFN2)
333 except shutil.Error as e:
334 errors = e.args[0]
335 self.assertEqual(len(errors), 1)
336 src, dst, error_msg = errors[0]
337 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
338 else:
339 self.fail("shutil.Error should have been raised")
340 finally:
341 shutil.rmtree(TESTFN, ignore_errors=True)
342 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000343
Tarek Ziadé5340db32010-04-19 22:30:51 +0000344 def test_copytree_special_func(self):
345
346 src_dir = self.mkdtemp()
347 dst_dir = os.path.join(self.mkdtemp(), 'destination')
Éric Araujoa7e33a12011-08-12 19:51:35 +0200348 write_file((src_dir, 'test.txt'), '123')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000349 os.mkdir(os.path.join(src_dir, 'test_dir'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200350 write_file((src_dir, 'test_dir', 'test.txt'), '456')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000351
352 copied = []
353 def _copy(src, dst):
354 copied.append((src, dst))
355
356 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000357 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000358
Brian Curtin3b4499c2010-12-28 14:31:47 +0000359 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000360 def test_copytree_dangling_symlinks(self):
361
362 # a dangling symlink raises an error at the end
363 src_dir = self.mkdtemp()
364 dst_dir = os.path.join(self.mkdtemp(), 'destination')
365 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
366 os.mkdir(os.path.join(src_dir, 'test_dir'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200367 write_file((src_dir, 'test_dir', 'test.txt'), '456')
Tarek Ziadéfb437512010-04-20 08:57:33 +0000368 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
369
370 # a dangling symlink is ignored with the proper flag
371 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
372 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
373 self.assertNotIn('test.txt', os.listdir(dst_dir))
374
375 # a dangling symlink is copied if symlinks=True
376 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
377 shutil.copytree(src_dir, dst_dir, symlinks=True)
378 self.assertIn('test.txt', os.listdir(dst_dir))
379
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400380 def _copy_file(self, method):
381 fname = 'test.txt'
382 tmpdir = self.mkdtemp()
Éric Araujoa7e33a12011-08-12 19:51:35 +0200383 write_file((tmpdir, fname), 'xxx')
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400384 file1 = os.path.join(tmpdir, fname)
385 tmpdir2 = self.mkdtemp()
386 method(file1, tmpdir2)
387 file2 = os.path.join(tmpdir2, fname)
388 return (file1, file2)
389
390 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
391 def test_copy(self):
392 # Ensure that the copied file exists and has the same mode bits.
393 file1, file2 = self._copy_file(shutil.copy)
394 self.assertTrue(os.path.exists(file2))
395 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
396
397 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
Senthil Kumaran0c2dba52011-07-03 18:21:38 -0700398 @unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400399 def test_copy2(self):
400 # Ensure that the copied file exists and has the same mode and
401 # modification time bits.
402 file1, file2 = self._copy_file(shutil.copy2)
403 self.assertTrue(os.path.exists(file2))
404 file1_stat = os.stat(file1)
405 file2_stat = os.stat(file2)
406 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
407 for attr in 'st_atime', 'st_mtime':
408 # The modification times may be truncated in the new file.
409 self.assertLessEqual(getattr(file1_stat, attr),
410 getattr(file2_stat, attr) + 1)
411 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
412 self.assertEqual(getattr(file1_stat, 'st_flags'),
413 getattr(file2_stat, 'st_flags'))
414
Ezio Melotti975077a2011-05-19 22:03:22 +0300415 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000416 def test_make_tarball(self):
417 # creating something to tar
418 tmpdir = self.mkdtemp()
Éric Araujoa7e33a12011-08-12 19:51:35 +0200419 write_file((tmpdir, 'file1'), 'xxx')
420 write_file((tmpdir, 'file2'), 'xxx')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000421 os.mkdir(os.path.join(tmpdir, 'sub'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200422 write_file((tmpdir, 'sub', 'file3'), 'xxx')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000423
424 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400425 # force shutil to create the directory
426 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000427 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
428 "source and target should be on same drive")
429
430 base_name = os.path.join(tmpdir2, 'archive')
431
432 # working with relative paths to avoid tar warnings
433 old_dir = os.getcwd()
434 os.chdir(tmpdir)
435 try:
436 _make_tarball(splitdrive(base_name)[1], '.')
437 finally:
438 os.chdir(old_dir)
439
440 # check if the compressed tarball was created
441 tarball = base_name + '.tar.gz'
442 self.assertTrue(os.path.exists(tarball))
443
444 # trying an uncompressed one
445 base_name = os.path.join(tmpdir2, 'archive')
446 old_dir = os.getcwd()
447 os.chdir(tmpdir)
448 try:
449 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
450 finally:
451 os.chdir(old_dir)
452 tarball = base_name + '.tar'
453 self.assertTrue(os.path.exists(tarball))
454
455 def _tarinfo(self, path):
456 tar = tarfile.open(path)
457 try:
458 names = tar.getnames()
459 names.sort()
460 return tuple(names)
461 finally:
462 tar.close()
463
464 def _create_files(self):
465 # creating something to tar
466 tmpdir = self.mkdtemp()
467 dist = os.path.join(tmpdir, 'dist')
468 os.mkdir(dist)
Éric Araujoa7e33a12011-08-12 19:51:35 +0200469 write_file((dist, 'file1'), 'xxx')
470 write_file((dist, 'file2'), 'xxx')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000471 os.mkdir(os.path.join(dist, 'sub'))
Éric Araujoa7e33a12011-08-12 19:51:35 +0200472 write_file((dist, 'sub', 'file3'), 'xxx')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000473 os.mkdir(os.path.join(dist, 'sub2'))
474 tmpdir2 = self.mkdtemp()
475 base_name = os.path.join(tmpdir2, 'archive')
476 return tmpdir, tmpdir2, base_name
477
Ezio Melotti975077a2011-05-19 22:03:22 +0300478 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000479 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
480 'Need the tar command to run')
481 def test_tarfile_vs_tar(self):
482 tmpdir, tmpdir2, base_name = self._create_files()
483 old_dir = os.getcwd()
484 os.chdir(tmpdir)
485 try:
486 _make_tarball(base_name, 'dist')
487 finally:
488 os.chdir(old_dir)
489
490 # check if the compressed tarball was created
491 tarball = base_name + '.tar.gz'
492 self.assertTrue(os.path.exists(tarball))
493
494 # now create another tarball using `tar`
495 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
496 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
497 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
498 old_dir = os.getcwd()
499 os.chdir(tmpdir)
500 try:
501 with captured_stdout() as s:
502 spawn(tar_cmd)
503 spawn(gzip_cmd)
504 finally:
505 os.chdir(old_dir)
506
507 self.assertTrue(os.path.exists(tarball2))
508 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000509 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000510
511 # trying an uncompressed one
512 base_name = os.path.join(tmpdir2, 'archive')
513 old_dir = os.getcwd()
514 os.chdir(tmpdir)
515 try:
516 _make_tarball(base_name, 'dist', compress=None)
517 finally:
518 os.chdir(old_dir)
519 tarball = base_name + '.tar'
520 self.assertTrue(os.path.exists(tarball))
521
522 # now for a dry_run
523 base_name = os.path.join(tmpdir2, 'archive')
524 old_dir = os.getcwd()
525 os.chdir(tmpdir)
526 try:
527 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
528 finally:
529 os.chdir(old_dir)
530 tarball = base_name + '.tar'
531 self.assertTrue(os.path.exists(tarball))
532
Ezio Melotti975077a2011-05-19 22:03:22 +0300533 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000534 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
535 def test_make_zipfile(self):
536 # creating something to tar
537 tmpdir = self.mkdtemp()
Éric Araujoa7e33a12011-08-12 19:51:35 +0200538 write_file((tmpdir, 'file1'), 'xxx')
539 write_file((tmpdir, 'file2'), 'xxx')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000540
541 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400542 # force shutil to create the directory
543 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000544 base_name = os.path.join(tmpdir2, 'archive')
545 _make_zipfile(base_name, tmpdir)
546
547 # check if the compressed tarball was created
548 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000549 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000550
551
552 def test_make_archive(self):
553 tmpdir = self.mkdtemp()
554 base_name = os.path.join(tmpdir, 'archive')
555 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
556
Ezio Melotti975077a2011-05-19 22:03:22 +0300557 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000558 def test_make_archive_owner_group(self):
559 # testing make_archive with owner and group, with various combinations
560 # this works even if there's not gid/uid support
561 if UID_GID_SUPPORT:
562 group = grp.getgrgid(0)[0]
563 owner = pwd.getpwuid(0)[0]
564 else:
565 group = owner = 'root'
566
567 base_dir, root_dir, base_name = self._create_files()
568 base_name = os.path.join(self.mkdtemp() , 'archive')
569 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
570 group=group)
571 self.assertTrue(os.path.exists(res))
572
573 res = make_archive(base_name, 'zip', root_dir, base_dir)
574 self.assertTrue(os.path.exists(res))
575
576 res = make_archive(base_name, 'tar', root_dir, base_dir,
577 owner=owner, group=group)
578 self.assertTrue(os.path.exists(res))
579
580 res = make_archive(base_name, 'tar', root_dir, base_dir,
581 owner='kjhkjhkjg', group='oihohoh')
582 self.assertTrue(os.path.exists(res))
583
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000584
Ezio Melotti975077a2011-05-19 22:03:22 +0300585 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000586 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
587 def test_tarfile_root_owner(self):
588 tmpdir, tmpdir2, base_name = self._create_files()
589 old_dir = os.getcwd()
590 os.chdir(tmpdir)
591 group = grp.getgrgid(0)[0]
592 owner = pwd.getpwuid(0)[0]
593 try:
594 archive_name = _make_tarball(base_name, 'dist', compress=None,
595 owner=owner, group=group)
596 finally:
597 os.chdir(old_dir)
598
599 # check if the compressed tarball was created
600 self.assertTrue(os.path.exists(archive_name))
601
602 # now checks the rights
603 archive = tarfile.open(archive_name)
604 try:
605 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000606 self.assertEqual(member.uid, 0)
607 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000608 finally:
609 archive.close()
610
611 def test_make_archive_cwd(self):
612 current_dir = os.getcwd()
613 def _breaks(*args, **kw):
614 raise RuntimeError()
615
616 register_archive_format('xxx', _breaks, [], 'xxx file')
617 try:
618 try:
619 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
620 except Exception:
621 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000622 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000623 finally:
624 unregister_archive_format('xxx')
625
626 def test_register_archive_format(self):
627
628 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
629 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
630 1)
631 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
632 [(1, 2), (1, 2, 3)])
633
634 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
635 formats = [name for name, params in get_archive_formats()]
636 self.assertIn('xxx', formats)
637
638 unregister_archive_format('xxx')
639 formats = [name for name, params in get_archive_formats()]
640 self.assertNotIn('xxx', formats)
641
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000642 def _compare_dirs(self, dir1, dir2):
643 # check that dir1 and dir2 are equivalent,
644 # return the diff
645 diff = []
646 for root, dirs, files in os.walk(dir1):
647 for file_ in files:
648 path = os.path.join(root, file_)
649 target_path = os.path.join(dir2, os.path.split(path)[-1])
650 if not os.path.exists(target_path):
651 diff.append(file_)
652 return diff
653
Ezio Melotti975077a2011-05-19 22:03:22 +0300654 @requires_zlib
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000655 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000656 formats = ['tar', 'gztar', 'zip']
657 if BZ2_SUPPORTED:
658 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000659
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000660 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000661 tmpdir = self.mkdtemp()
662 base_dir, root_dir, base_name = self._create_files()
663 tmpdir2 = self.mkdtemp()
664 filename = make_archive(base_name, format, root_dir, base_dir)
665
666 # let's try to unpack it now
667 unpack_archive(filename, tmpdir2)
668 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000669 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000670
Nick Coghlanabf202d2011-03-16 13:52:20 -0400671 # and again, this time with the format specified
672 tmpdir3 = self.mkdtemp()
673 unpack_archive(filename, tmpdir3, format=format)
674 diff = self._compare_dirs(tmpdir, tmpdir3)
675 self.assertEqual(diff, [])
676 self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
677 self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
678
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000679 def test_unpack_registery(self):
680
681 formats = get_unpack_formats()
682
683 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000684 self.assertEqual(extra, 1)
685 self.assertEqual(filename, 'stuff.boo')
686 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000687
688 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
689 unpack_archive('stuff.boo', 'xx')
690
691 # trying to register a .boo unpacker again
692 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
693 ['.boo'], _boo)
694
695 # should work now
696 unregister_unpack_format('Boo')
697 register_unpack_format('Boo2', ['.boo'], _boo)
698 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
699 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
700
701 # let's leave a clean state
702 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000703 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000704
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200705 @unittest.skipUnless(hasattr(shutil, 'disk_usage'),
706 "disk_usage not available on this platform")
707 def test_disk_usage(self):
708 usage = shutil.disk_usage(os.getcwd())
Éric Araujo2ee61882011-07-02 16:45:45 +0200709 self.assertGreater(usage.total, 0)
710 self.assertGreater(usage.used, 0)
711 self.assertGreaterEqual(usage.free, 0)
712 self.assertGreaterEqual(usage.total, usage.used)
713 self.assertGreater(usage.total, usage.free)
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200714
Sandro Tosid902a142011-08-22 23:28:27 +0200715 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
716 @unittest.skipUnless(hasattr(os, 'chown'), 'requires os.chown')
717 def test_chown(self):
718
719 # cleaned-up automatically by TestShutil.tearDown method
720 dirname = self.mkdtemp()
721 filename = tempfile.mktemp(dir=dirname)
722 write_file(filename, 'testing chown function')
723
724 with self.assertRaises(ValueError):
725 shutil.chown(filename)
726
727 with self.assertRaises(LookupError):
728 shutil.chown(filename, user='non-exising username')
729
730 with self.assertRaises(LookupError):
731 shutil.chown(filename, group='non-exising groupname')
732
733 with self.assertRaises(TypeError):
734 shutil.chown(filename, b'spam')
735
736 with self.assertRaises(TypeError):
737 shutil.chown(filename, 3.14)
738
739 uid = os.getuid()
740 gid = os.getgid()
741
742 def check_chown(path, uid=None, gid=None):
743 s = os.stat(filename)
744 if uid is not None:
745 self.assertEqual(uid, s.st_uid)
746 if gid is not None:
747 self.assertEqual(gid, s.st_gid)
748
749 shutil.chown(filename, uid, gid)
750 check_chown(filename, uid, gid)
751 shutil.chown(filename, uid)
752 check_chown(filename, uid)
753 shutil.chown(filename, user=uid)
754 check_chown(filename, uid)
755 shutil.chown(filename, group=gid)
Sandro Tosi91f948a2011-08-22 23:55:39 +0200756 check_chown(filename, gid=gid)
Sandro Tosid902a142011-08-22 23:28:27 +0200757
758 shutil.chown(dirname, uid, gid)
759 check_chown(dirname, uid, gid)
760 shutil.chown(dirname, uid)
761 check_chown(dirname, uid)
762 shutil.chown(dirname, user=uid)
763 check_chown(dirname, uid)
764 shutil.chown(dirname, group=gid)
Sandro Tosi91f948a2011-08-22 23:55:39 +0200765 check_chown(dirname, gid=gid)
Sandro Tosid902a142011-08-22 23:28:27 +0200766
767 user = pwd.getpwuid(uid)[0]
768 group = grp.getgrgid(gid)[0]
769 shutil.chown(filename, user, group)
770 check_chown(filename, uid, gid)
771 shutil.chown(dirname, user, group)
772 check_chown(dirname, uid, gid)
773
Christian Heimes9bd667a2008-01-20 15:14:11 +0000774
Christian Heimesada8c3b2008-03-18 18:26:33 +0000775class TestMove(unittest.TestCase):
776
777 def setUp(self):
778 filename = "foo"
779 self.src_dir = tempfile.mkdtemp()
780 self.dst_dir = tempfile.mkdtemp()
781 self.src_file = os.path.join(self.src_dir, filename)
782 self.dst_file = os.path.join(self.dst_dir, filename)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000783 with open(self.src_file, "wb") as f:
784 f.write(b"spam")
785
786 def tearDown(self):
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400787 for d in (self.src_dir, self.dst_dir):
Christian Heimesada8c3b2008-03-18 18:26:33 +0000788 try:
789 if d:
790 shutil.rmtree(d)
791 except:
792 pass
793
794 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000795 with open(src, "rb") as f:
796 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000797 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000798 with open(real_dst, "rb") as f:
799 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000800 self.assertFalse(os.path.exists(src))
801
802 def _check_move_dir(self, src, dst, real_dst):
803 contents = sorted(os.listdir(src))
804 shutil.move(src, dst)
805 self.assertEqual(contents, sorted(os.listdir(real_dst)))
806 self.assertFalse(os.path.exists(src))
807
808 def test_move_file(self):
809 # Move a file to another location on the same filesystem.
810 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
811
812 def test_move_file_to_dir(self):
813 # Move a file inside an existing dir on the same filesystem.
814 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
815
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400816 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000817 def test_move_file_other_fs(self):
818 # Move a file to an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400819 self.test_move_file()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000820
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400821 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000822 def test_move_file_to_dir_other_fs(self):
823 # Move a file to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400824 self.test_move_file_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000825
826 def test_move_dir(self):
827 # Move a dir to another location on the same filesystem.
828 dst_dir = tempfile.mktemp()
829 try:
830 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
831 finally:
832 try:
833 shutil.rmtree(dst_dir)
834 except:
835 pass
836
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400837 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000838 def test_move_dir_other_fs(self):
839 # Move a dir to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400840 self.test_move_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000841
842 def test_move_dir_to_dir(self):
843 # Move a dir inside an existing dir on the same filesystem.
844 self._check_move_dir(self.src_dir, self.dst_dir,
845 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
846
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400847 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000848 def test_move_dir_to_dir_other_fs(self):
849 # Move a dir inside an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400850 self.test_move_dir_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000851
852 def test_existing_file_inside_dest_dir(self):
853 # A file with the same name inside the destination dir already exists.
854 with open(self.dst_file, "wb"):
855 pass
856 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
857
858 def test_dont_move_dir_in_itself(self):
859 # Moving a dir inside itself raises an Error.
860 dst = os.path.join(self.src_dir, "bar")
861 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
862
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000863 def test_destinsrc_false_negative(self):
864 os.mkdir(TESTFN)
865 try:
866 for src, dst in [('srcdir', 'srcdir/dest')]:
867 src = os.path.join(TESTFN, src)
868 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000869 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000870 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000871 'dst (%s) is not in src (%s)' % (dst, src))
872 finally:
873 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000874
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000875 def test_destinsrc_false_positive(self):
876 os.mkdir(TESTFN)
877 try:
878 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
879 src = os.path.join(TESTFN, src)
880 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000881 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000882 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000883 'dst (%s) is in src (%s)' % (dst, src))
884 finally:
885 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000886
Tarek Ziadé5340db32010-04-19 22:30:51 +0000887
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000888class TestCopyFile(unittest.TestCase):
889
890 _delete = False
891
892 class Faux(object):
893 _entered = False
894 _exited_with = None
895 _raised = False
896 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
897 self._raise_in_exit = raise_in_exit
898 self._suppress_at_exit = suppress_at_exit
899 def read(self, *args):
900 return ''
901 def __enter__(self):
902 self._entered = True
903 def __exit__(self, exc_type, exc_val, exc_tb):
904 self._exited_with = exc_type, exc_val, exc_tb
905 if self._raise_in_exit:
906 self._raised = True
907 raise IOError("Cannot close")
908 return self._suppress_at_exit
909
910 def tearDown(self):
911 if self._delete:
912 del shutil.open
913
914 def _set_shutil_open(self, func):
915 shutil.open = func
916 self._delete = True
917
918 def test_w_source_open_fails(self):
919 def _open(filename, mode='r'):
920 if filename == 'srcfile':
921 raise IOError('Cannot open "srcfile"')
922 assert 0 # shouldn't reach here.
923
924 self._set_shutil_open(_open)
925
926 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
927
928 def test_w_dest_open_fails(self):
929
930 srcfile = self.Faux()
931
932 def _open(filename, mode='r'):
933 if filename == 'srcfile':
934 return srcfile
935 if filename == 'destfile':
936 raise IOError('Cannot open "destfile"')
937 assert 0 # shouldn't reach here.
938
939 self._set_shutil_open(_open)
940
941 shutil.copyfile('srcfile', 'destfile')
942 self.assertTrue(srcfile._entered)
943 self.assertTrue(srcfile._exited_with[0] is IOError)
944 self.assertEqual(srcfile._exited_with[1].args,
945 ('Cannot open "destfile"',))
946
947 def test_w_dest_close_fails(self):
948
949 srcfile = self.Faux()
950 destfile = self.Faux(True)
951
952 def _open(filename, mode='r'):
953 if filename == 'srcfile':
954 return srcfile
955 if filename == 'destfile':
956 return destfile
957 assert 0 # shouldn't reach here.
958
959 self._set_shutil_open(_open)
960
961 shutil.copyfile('srcfile', 'destfile')
962 self.assertTrue(srcfile._entered)
963 self.assertTrue(destfile._entered)
964 self.assertTrue(destfile._raised)
965 self.assertTrue(srcfile._exited_with[0] is IOError)
966 self.assertEqual(srcfile._exited_with[1].args,
967 ('Cannot close',))
968
969 def test_w_source_close_fails(self):
970
971 srcfile = self.Faux(True)
972 destfile = self.Faux()
973
974 def _open(filename, mode='r'):
975 if filename == 'srcfile':
976 return srcfile
977 if filename == 'destfile':
978 return destfile
979 assert 0 # shouldn't reach here.
980
981 self._set_shutil_open(_open)
982
983 self.assertRaises(IOError,
984 shutil.copyfile, 'srcfile', 'destfile')
985 self.assertTrue(srcfile._entered)
986 self.assertTrue(destfile._entered)
987 self.assertFalse(destfile._raised)
988 self.assertTrue(srcfile._exited_with[0] is None)
989 self.assertTrue(srcfile._raised)
990
Ronald Oussorenf51738b2011-05-06 10:23:04 +0200991 def test_move_dir_caseinsensitive(self):
992 # Renames a folder to the same name
993 # but a different case.
994
995 self.src_dir = tempfile.mkdtemp()
996 dst_dir = os.path.join(
997 os.path.dirname(self.src_dir),
998 os.path.basename(self.src_dir).upper())
999 self.assertNotEqual(self.src_dir, dst_dir)
1000
1001 try:
1002 shutil.move(self.src_dir, dst_dir)
1003 self.assertTrue(os.path.isdir(dst_dir))
1004 finally:
Éric Araujoa7e33a12011-08-12 19:51:35 +02001005 os.rmdir(dst_dir)
Ronald Oussorenf51738b2011-05-06 10:23:04 +02001006
1007
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001008
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001009def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +00001010 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001011
Barry Warsaw7fc2cca2003-01-24 17:34:13 +00001012if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +00001013 test_main()