blob: 839f7428142b7745fb21ed50e56231e269652a49 [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
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000062class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000063
64 def setUp(self):
65 super(TestShutil, self).setUp()
66 self.tempdirs = []
67
68 def tearDown(self):
69 super(TestShutil, self).tearDown()
70 while self.tempdirs:
71 d = self.tempdirs.pop()
72 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
73
74 def write_file(self, path, content='xxx'):
75 """Writes a file in the given path.
76
77
78 path can be a string or a sequence.
79 """
80 if isinstance(path, (list, tuple)):
81 path = os.path.join(*path)
82 f = open(path, 'w')
83 try:
84 f.write(content)
85 finally:
86 f.close()
87
88 def mkdtemp(self):
89 """Create a temporary directory that will be cleaned up.
90
91 Returns the path of the directory.
92 """
93 d = tempfile.mkdtemp()
94 self.tempdirs.append(d)
95 return d
Tarek Ziadé5340db32010-04-19 22:30:51 +000096
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000097 def test_rmtree_errors(self):
98 # filename is guaranteed not to exist
99 filename = tempfile.mktemp()
100 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000101
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000102 # See bug #1071513 for why we don't run this on cygwin
103 # and bug #1076467 for why we don't run this as root.
104 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +0000105 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000106 def test_on_error(self):
107 self.errorState = 0
108 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +0000109 self.childpath = os.path.join(TESTFN, 'a')
110 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000111 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000112 old_dir_mode = os.stat(TESTFN).st_mode
113 old_child_mode = os.stat(self.childpath).st_mode
114 # Make unwritable.
115 os.chmod(self.childpath, stat.S_IREAD)
116 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000117
118 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000119 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000120 self.assertEqual(self.errorState, 2,
121 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000122
Tim Peters4590c002004-11-01 02:40:52 +0000123 # Make writable again.
124 os.chmod(TESTFN, old_dir_mode)
125 os.chmod(self.childpath, old_child_mode)
126
127 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000128 shutil.rmtree(TESTFN)
129
130 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000131 # test_rmtree_errors deliberately runs rmtree
132 # on a directory that is chmod 400, which will fail.
133 # This function is run when shutil.rmtree fails.
134 # 99.9% of the time it initially fails to remove
135 # a file in the directory, so the first time through
136 # func is os.remove.
137 # However, some Linux machines running ZFS on
138 # FUSE experienced a failure earlier in the process
139 # at os.listdir. The first failure may legally
140 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000141 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000142 if func is os.remove:
143 self.assertEqual(arg, self.childpath)
144 else:
145 self.assertIs(func, os.listdir,
146 "func must be either os.remove or os.listdir")
147 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000148 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000149 self.errorState = 1
150 else:
151 self.assertEqual(func, os.rmdir)
152 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000153 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000154 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000155
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000156 def test_rmtree_dont_delete_file(self):
157 # When called on a file instead of a directory, don't delete it.
158 handle, path = tempfile.mkstemp()
159 os.fdopen(handle).close()
160 self.assertRaises(OSError, shutil.rmtree, path)
161 os.remove(path)
162
Tarek Ziadé5340db32010-04-19 22:30:51 +0000163 def _write_data(self, path, data):
164 f = open(path, "w")
165 f.write(data)
166 f.close()
167
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000168 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000169
170 def read_data(path):
171 f = open(path)
172 data = f.read()
173 f.close()
174 return data
175
176 src_dir = tempfile.mkdtemp()
177 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000178 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000179 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000180 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000181
182 try:
183 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_data(os.path.join(dst_dir, 'test.txt'))
189 self.assertEqual(actual, '123')
190 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
191 self.assertEqual(actual, '456')
192 finally:
193 for path in (
194 os.path.join(src_dir, 'test.txt'),
195 os.path.join(dst_dir, 'test.txt'),
196 os.path.join(src_dir, 'test_dir', 'test.txt'),
197 os.path.join(dst_dir, 'test_dir', 'test.txt'),
198 ):
199 if os.path.exists(path):
200 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000201 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000202 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000203 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000204 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000205 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000206
Georg Brandl2ee470f2008-07-16 12:55:28 +0000207 def test_copytree_with_exclude(self):
208
Georg Brandl2ee470f2008-07-16 12:55:28 +0000209 def read_data(path):
210 f = open(path)
211 data = f.read()
212 f.close()
213 return data
214
215 # creating data
216 join = os.path.join
217 exists = os.path.exists
218 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000219 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000220 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000221 self._write_data(join(src_dir, 'test.txt'), '123')
222 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000223 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000224 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000225 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000226 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000227 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
228 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000229 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
230 '456')
231 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
232 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000233
234
235 # testing glob-like patterns
236 try:
237 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
238 shutil.copytree(src_dir, dst_dir, ignore=patterns)
239 # checking the result: some elements should not be copied
240 self.assertTrue(exists(join(dst_dir, 'test.txt')))
241 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
242 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
243 finally:
244 if os.path.exists(dst_dir):
245 shutil.rmtree(dst_dir)
246 try:
247 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
248 shutil.copytree(src_dir, dst_dir, ignore=patterns)
249 # checking the result: some elements should not be copied
250 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
251 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
252 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
253 finally:
254 if os.path.exists(dst_dir):
255 shutil.rmtree(dst_dir)
256
257 # testing callable-style
258 try:
259 def _filter(src, names):
260 res = []
261 for name in names:
262 path = os.path.join(src, name)
263
264 if (os.path.isdir(path) and
265 path.split()[-1] == 'subdir'):
266 res.append(name)
267 elif os.path.splitext(path)[-1] in ('.py'):
268 res.append(name)
269 return res
270
271 shutil.copytree(src_dir, dst_dir, ignore=_filter)
272
273 # checking the result: some elements should not be copied
274 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
275 'test.py')))
276 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
277
278 finally:
279 if os.path.exists(dst_dir):
280 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000281 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000282 shutil.rmtree(src_dir)
283 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000284
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000285 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000286 def test_dont_copy_file_onto_link_to_itself(self):
Georg Brandl724d0892010-12-05 07:51:39 +0000287 # Temporarily disable test on Windows.
288 if os.name == 'nt':
289 return
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000290 # bug 851123.
291 os.mkdir(TESTFN)
292 src = os.path.join(TESTFN, 'cheese')
293 dst = os.path.join(TESTFN, 'shop')
294 try:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000295 with open(src, 'w') as f:
296 f.write('cheddar')
297 os.link(src, dst)
298 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
299 with open(src, 'r') as f:
300 self.assertEqual(f.read(), 'cheddar')
301 os.remove(dst)
302 finally:
303 shutil.rmtree(TESTFN, ignore_errors=True)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000304
Brian Curtin3b4499c2010-12-28 14:31:47 +0000305 @support.skip_unless_symlink
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000306 def test_dont_copy_file_onto_symlink_to_itself(self):
307 # bug 851123.
308 os.mkdir(TESTFN)
309 src = os.path.join(TESTFN, 'cheese')
310 dst = os.path.join(TESTFN, 'shop')
311 try:
312 with open(src, 'w') as f:
313 f.write('cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000314 # Using `src` here would mean we end up with a symlink pointing
315 # to TESTFN/TESTFN/cheese, while it should point at
316 # TESTFN/cheese.
317 os.symlink('cheese', dst)
318 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000319 with open(src, 'r') as f:
320 self.assertEqual(f.read(), 'cheddar')
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000321 os.remove(dst)
322 finally:
Hirokazu Yamamoto26681452010-12-05 02:04:16 +0000323 shutil.rmtree(TESTFN, ignore_errors=True)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000324
Brian Curtin3b4499c2010-12-28 14:31:47 +0000325 @support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +0000326 def test_rmtree_on_symlink(self):
327 # bug 1669.
328 os.mkdir(TESTFN)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000329 try:
Brian Curtind40e6f72010-07-08 21:39:08 +0000330 src = os.path.join(TESTFN, 'cheese')
331 dst = os.path.join(TESTFN, 'shop')
332 os.mkdir(src)
333 os.symlink(src, dst)
334 self.assertRaises(OSError, shutil.rmtree, dst)
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000335 finally:
Brian Curtind40e6f72010-07-08 21:39:08 +0000336 shutil.rmtree(TESTFN, ignore_errors=True)
337
338 if hasattr(os, "mkfifo"):
339 # Issue #3002: copyfile and copytree block indefinitely on named pipes
340 def test_copyfile_named_pipe(self):
341 os.mkfifo(TESTFN)
342 try:
343 self.assertRaises(shutil.SpecialFileError,
344 shutil.copyfile, TESTFN, TESTFN2)
345 self.assertRaises(shutil.SpecialFileError,
346 shutil.copyfile, __file__, TESTFN)
347 finally:
348 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000349
Brian Curtin3b4499c2010-12-28 14:31:47 +0000350 @support.skip_unless_symlink
Brian Curtin52173d42010-12-02 18:29:18 +0000351 def test_copytree_named_pipe(self):
352 os.mkdir(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000353 try:
Brian Curtin52173d42010-12-02 18:29:18 +0000354 subdir = os.path.join(TESTFN, "subdir")
355 os.mkdir(subdir)
356 pipe = os.path.join(subdir, "mypipe")
357 os.mkfifo(pipe)
358 try:
359 shutil.copytree(TESTFN, TESTFN2)
360 except shutil.Error as e:
361 errors = e.args[0]
362 self.assertEqual(len(errors), 1)
363 src, dst, error_msg = errors[0]
364 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
365 else:
366 self.fail("shutil.Error should have been raised")
367 finally:
368 shutil.rmtree(TESTFN, ignore_errors=True)
369 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000370
Tarek Ziadé5340db32010-04-19 22:30:51 +0000371 def test_copytree_special_func(self):
372
373 src_dir = self.mkdtemp()
374 dst_dir = os.path.join(self.mkdtemp(), 'destination')
375 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
376 os.mkdir(os.path.join(src_dir, 'test_dir'))
377 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
378
379 copied = []
380 def _copy(src, dst):
381 copied.append((src, dst))
382
383 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000384 self.assertEqual(len(copied), 2)
Tarek Ziadé5340db32010-04-19 22:30:51 +0000385
Brian Curtin3b4499c2010-12-28 14:31:47 +0000386 @support.skip_unless_symlink
Tarek Ziadéfb437512010-04-20 08:57:33 +0000387 def test_copytree_dangling_symlinks(self):
388
389 # a dangling symlink raises an error at the end
390 src_dir = self.mkdtemp()
391 dst_dir = os.path.join(self.mkdtemp(), 'destination')
392 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
393 os.mkdir(os.path.join(src_dir, 'test_dir'))
394 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
395 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
396
397 # a dangling symlink is ignored with the proper flag
398 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
399 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
400 self.assertNotIn('test.txt', os.listdir(dst_dir))
401
402 # a dangling symlink is copied if symlinks=True
403 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
404 shutil.copytree(src_dir, dst_dir, symlinks=True)
405 self.assertIn('test.txt', os.listdir(dst_dir))
406
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400407 def _copy_file(self, method):
408 fname = 'test.txt'
409 tmpdir = self.mkdtemp()
410 self.write_file([tmpdir, fname])
411 file1 = os.path.join(tmpdir, fname)
412 tmpdir2 = self.mkdtemp()
413 method(file1, tmpdir2)
414 file2 = os.path.join(tmpdir2, fname)
415 return (file1, file2)
416
417 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
418 def test_copy(self):
419 # Ensure that the copied file exists and has the same mode bits.
420 file1, file2 = self._copy_file(shutil.copy)
421 self.assertTrue(os.path.exists(file2))
422 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
423
424 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
425 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.utime')
426 def test_copy2(self):
427 # Ensure that the copied file exists and has the same mode and
428 # modification time bits.
429 file1, file2 = self._copy_file(shutil.copy2)
430 self.assertTrue(os.path.exists(file2))
431 file1_stat = os.stat(file1)
432 file2_stat = os.stat(file2)
433 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
434 for attr in 'st_atime', 'st_mtime':
435 # The modification times may be truncated in the new file.
436 self.assertLessEqual(getattr(file1_stat, attr),
437 getattr(file2_stat, attr) + 1)
438 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
439 self.assertEqual(getattr(file1_stat, 'st_flags'),
440 getattr(file2_stat, 'st_flags'))
441
Ezio Melotti975077a2011-05-19 22:03:22 +0300442 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000443 def test_make_tarball(self):
444 # creating something to tar
445 tmpdir = self.mkdtemp()
446 self.write_file([tmpdir, 'file1'], 'xxx')
447 self.write_file([tmpdir, 'file2'], 'xxx')
448 os.mkdir(os.path.join(tmpdir, 'sub'))
449 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
450
451 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400452 # force shutil to create the directory
453 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000454 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
455 "source and target should be on same drive")
456
457 base_name = os.path.join(tmpdir2, 'archive')
458
459 # working with relative paths to avoid tar warnings
460 old_dir = os.getcwd()
461 os.chdir(tmpdir)
462 try:
463 _make_tarball(splitdrive(base_name)[1], '.')
464 finally:
465 os.chdir(old_dir)
466
467 # check if the compressed tarball was created
468 tarball = base_name + '.tar.gz'
469 self.assertTrue(os.path.exists(tarball))
470
471 # trying an uncompressed one
472 base_name = os.path.join(tmpdir2, 'archive')
473 old_dir = os.getcwd()
474 os.chdir(tmpdir)
475 try:
476 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
477 finally:
478 os.chdir(old_dir)
479 tarball = base_name + '.tar'
480 self.assertTrue(os.path.exists(tarball))
481
482 def _tarinfo(self, path):
483 tar = tarfile.open(path)
484 try:
485 names = tar.getnames()
486 names.sort()
487 return tuple(names)
488 finally:
489 tar.close()
490
491 def _create_files(self):
492 # creating something to tar
493 tmpdir = self.mkdtemp()
494 dist = os.path.join(tmpdir, 'dist')
495 os.mkdir(dist)
496 self.write_file([dist, 'file1'], 'xxx')
497 self.write_file([dist, 'file2'], 'xxx')
498 os.mkdir(os.path.join(dist, 'sub'))
499 self.write_file([dist, 'sub', 'file3'], 'xxx')
500 os.mkdir(os.path.join(dist, 'sub2'))
501 tmpdir2 = self.mkdtemp()
502 base_name = os.path.join(tmpdir2, 'archive')
503 return tmpdir, tmpdir2, base_name
504
Ezio Melotti975077a2011-05-19 22:03:22 +0300505 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000506 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
507 'Need the tar command to run')
508 def test_tarfile_vs_tar(self):
509 tmpdir, tmpdir2, base_name = self._create_files()
510 old_dir = os.getcwd()
511 os.chdir(tmpdir)
512 try:
513 _make_tarball(base_name, 'dist')
514 finally:
515 os.chdir(old_dir)
516
517 # check if the compressed tarball was created
518 tarball = base_name + '.tar.gz'
519 self.assertTrue(os.path.exists(tarball))
520
521 # now create another tarball using `tar`
522 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
523 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
524 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
525 old_dir = os.getcwd()
526 os.chdir(tmpdir)
527 try:
528 with captured_stdout() as s:
529 spawn(tar_cmd)
530 spawn(gzip_cmd)
531 finally:
532 os.chdir(old_dir)
533
534 self.assertTrue(os.path.exists(tarball2))
535 # let's compare both tarballs
Ezio Melottib3aedd42010-11-20 19:04:17 +0000536 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000537
538 # trying an uncompressed one
539 base_name = os.path.join(tmpdir2, 'archive')
540 old_dir = os.getcwd()
541 os.chdir(tmpdir)
542 try:
543 _make_tarball(base_name, 'dist', compress=None)
544 finally:
545 os.chdir(old_dir)
546 tarball = base_name + '.tar'
547 self.assertTrue(os.path.exists(tarball))
548
549 # now for a dry_run
550 base_name = os.path.join(tmpdir2, 'archive')
551 old_dir = os.getcwd()
552 os.chdir(tmpdir)
553 try:
554 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
555 finally:
556 os.chdir(old_dir)
557 tarball = base_name + '.tar'
558 self.assertTrue(os.path.exists(tarball))
559
Ezio Melotti975077a2011-05-19 22:03:22 +0300560 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000561 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
562 def test_make_zipfile(self):
563 # creating something to tar
564 tmpdir = self.mkdtemp()
565 self.write_file([tmpdir, 'file1'], 'xxx')
566 self.write_file([tmpdir, 'file2'], 'xxx')
567
568 tmpdir2 = self.mkdtemp()
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400569 # force shutil to create the directory
570 os.rmdir(tmpdir2)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000571 base_name = os.path.join(tmpdir2, 'archive')
572 _make_zipfile(base_name, tmpdir)
573
574 # check if the compressed tarball was created
575 tarball = base_name + '.zip'
Éric Araujo1c505492010-11-06 02:12:51 +0000576 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000577
578
579 def test_make_archive(self):
580 tmpdir = self.mkdtemp()
581 base_name = os.path.join(tmpdir, 'archive')
582 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
583
Ezio Melotti975077a2011-05-19 22:03:22 +0300584 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000585 def test_make_archive_owner_group(self):
586 # testing make_archive with owner and group, with various combinations
587 # this works even if there's not gid/uid support
588 if UID_GID_SUPPORT:
589 group = grp.getgrgid(0)[0]
590 owner = pwd.getpwuid(0)[0]
591 else:
592 group = owner = 'root'
593
594 base_dir, root_dir, base_name = self._create_files()
595 base_name = os.path.join(self.mkdtemp() , 'archive')
596 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
597 group=group)
598 self.assertTrue(os.path.exists(res))
599
600 res = make_archive(base_name, 'zip', root_dir, base_dir)
601 self.assertTrue(os.path.exists(res))
602
603 res = make_archive(base_name, 'tar', root_dir, base_dir,
604 owner=owner, group=group)
605 self.assertTrue(os.path.exists(res))
606
607 res = make_archive(base_name, 'tar', root_dir, base_dir,
608 owner='kjhkjhkjg', group='oihohoh')
609 self.assertTrue(os.path.exists(res))
610
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000611
Ezio Melotti975077a2011-05-19 22:03:22 +0300612 @requires_zlib
Tarek Ziadé396fad72010-02-23 05:30:31 +0000613 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
614 def test_tarfile_root_owner(self):
615 tmpdir, tmpdir2, base_name = self._create_files()
616 old_dir = os.getcwd()
617 os.chdir(tmpdir)
618 group = grp.getgrgid(0)[0]
619 owner = pwd.getpwuid(0)[0]
620 try:
621 archive_name = _make_tarball(base_name, 'dist', compress=None,
622 owner=owner, group=group)
623 finally:
624 os.chdir(old_dir)
625
626 # check if the compressed tarball was created
627 self.assertTrue(os.path.exists(archive_name))
628
629 # now checks the rights
630 archive = tarfile.open(archive_name)
631 try:
632 for member in archive.getmembers():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000633 self.assertEqual(member.uid, 0)
634 self.assertEqual(member.gid, 0)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000635 finally:
636 archive.close()
637
638 def test_make_archive_cwd(self):
639 current_dir = os.getcwd()
640 def _breaks(*args, **kw):
641 raise RuntimeError()
642
643 register_archive_format('xxx', _breaks, [], 'xxx file')
644 try:
645 try:
646 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
647 except Exception:
648 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000649 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000650 finally:
651 unregister_archive_format('xxx')
652
653 def test_register_archive_format(self):
654
655 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
656 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
657 1)
658 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
659 [(1, 2), (1, 2, 3)])
660
661 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
662 formats = [name for name, params in get_archive_formats()]
663 self.assertIn('xxx', formats)
664
665 unregister_archive_format('xxx')
666 formats = [name for name, params in get_archive_formats()]
667 self.assertNotIn('xxx', formats)
668
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000669 def _compare_dirs(self, dir1, dir2):
670 # check that dir1 and dir2 are equivalent,
671 # return the diff
672 diff = []
673 for root, dirs, files in os.walk(dir1):
674 for file_ in files:
675 path = os.path.join(root, file_)
676 target_path = os.path.join(dir2, os.path.split(path)[-1])
677 if not os.path.exists(target_path):
678 diff.append(file_)
679 return diff
680
Ezio Melotti975077a2011-05-19 22:03:22 +0300681 @requires_zlib
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000682 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000683 formats = ['tar', 'gztar', 'zip']
684 if BZ2_SUPPORTED:
685 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000686
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000687 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000688 tmpdir = self.mkdtemp()
689 base_dir, root_dir, base_name = self._create_files()
690 tmpdir2 = self.mkdtemp()
691 filename = make_archive(base_name, format, root_dir, base_dir)
692
693 # let's try to unpack it now
694 unpack_archive(filename, tmpdir2)
695 diff = self._compare_dirs(tmpdir, tmpdir2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000696 self.assertEqual(diff, [])
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000697
Nick Coghlanabf202d2011-03-16 13:52:20 -0400698 # and again, this time with the format specified
699 tmpdir3 = self.mkdtemp()
700 unpack_archive(filename, tmpdir3, format=format)
701 diff = self._compare_dirs(tmpdir, tmpdir3)
702 self.assertEqual(diff, [])
703 self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
704 self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
705
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000706 def test_unpack_registery(self):
707
708 formats = get_unpack_formats()
709
710 def _boo(filename, extract_dir, extra):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000711 self.assertEqual(extra, 1)
712 self.assertEqual(filename, 'stuff.boo')
713 self.assertEqual(extract_dir, 'xx')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000714
715 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
716 unpack_archive('stuff.boo', 'xx')
717
718 # trying to register a .boo unpacker again
719 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
720 ['.boo'], _boo)
721
722 # should work now
723 unregister_unpack_format('Boo')
724 register_unpack_format('Boo2', ['.boo'], _boo)
725 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
726 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
727
728 # let's leave a clean state
729 unregister_unpack_format('Boo2')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000730 self.assertEqual(get_unpack_formats(), formats)
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000731
Christian Heimes9bd667a2008-01-20 15:14:11 +0000732
Christian Heimesada8c3b2008-03-18 18:26:33 +0000733class TestMove(unittest.TestCase):
734
735 def setUp(self):
736 filename = "foo"
737 self.src_dir = tempfile.mkdtemp()
738 self.dst_dir = tempfile.mkdtemp()
739 self.src_file = os.path.join(self.src_dir, filename)
740 self.dst_file = os.path.join(self.dst_dir, filename)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000741 with open(self.src_file, "wb") as f:
742 f.write(b"spam")
743
744 def tearDown(self):
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400745 for d in (self.src_dir, self.dst_dir):
Christian Heimesada8c3b2008-03-18 18:26:33 +0000746 try:
747 if d:
748 shutil.rmtree(d)
749 except:
750 pass
751
752 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000753 with open(src, "rb") as f:
754 contents = f.read()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000755 shutil.move(src, dst)
Antoine Pitrou92f60ed2010-10-14 22:11:44 +0000756 with open(real_dst, "rb") as f:
757 self.assertEqual(contents, f.read())
Christian Heimesada8c3b2008-03-18 18:26:33 +0000758 self.assertFalse(os.path.exists(src))
759
760 def _check_move_dir(self, src, dst, real_dst):
761 contents = sorted(os.listdir(src))
762 shutil.move(src, dst)
763 self.assertEqual(contents, sorted(os.listdir(real_dst)))
764 self.assertFalse(os.path.exists(src))
765
766 def test_move_file(self):
767 # Move a file to another location on the same filesystem.
768 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
769
770 def test_move_file_to_dir(self):
771 # Move a file inside an existing dir on the same filesystem.
772 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
773
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400774 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000775 def test_move_file_other_fs(self):
776 # Move a file to an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400777 self.test_move_file()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000778
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400779 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000780 def test_move_file_to_dir_other_fs(self):
781 # Move a file to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400782 self.test_move_file_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000783
784 def test_move_dir(self):
785 # Move a dir to another location on the same filesystem.
786 dst_dir = tempfile.mktemp()
787 try:
788 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
789 finally:
790 try:
791 shutil.rmtree(dst_dir)
792 except:
793 pass
794
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400795 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000796 def test_move_dir_other_fs(self):
797 # Move a dir to another location on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400798 self.test_move_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000799
800 def test_move_dir_to_dir(self):
801 # Move a dir inside an existing dir on the same filesystem.
802 self._check_move_dir(self.src_dir, self.dst_dir,
803 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
804
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400805 @mock_rename
Christian Heimesada8c3b2008-03-18 18:26:33 +0000806 def test_move_dir_to_dir_other_fs(self):
807 # Move a dir inside an existing dir on another filesystem.
Nick Coghlan8ed3cf32011-03-16 14:05:35 -0400808 self.test_move_dir_to_dir()
Christian Heimesada8c3b2008-03-18 18:26:33 +0000809
810 def test_existing_file_inside_dest_dir(self):
811 # A file with the same name inside the destination dir already exists.
812 with open(self.dst_file, "wb"):
813 pass
814 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
815
816 def test_dont_move_dir_in_itself(self):
817 # Moving a dir inside itself raises an Error.
818 dst = os.path.join(self.src_dir, "bar")
819 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
820
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000821 def test_destinsrc_false_negative(self):
822 os.mkdir(TESTFN)
823 try:
824 for src, dst in [('srcdir', 'srcdir/dest')]:
825 src = os.path.join(TESTFN, src)
826 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000827 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000828 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000829 'dst (%s) is not in src (%s)' % (dst, src))
830 finally:
831 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000832
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000833 def test_destinsrc_false_positive(self):
834 os.mkdir(TESTFN)
835 try:
836 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
837 src = os.path.join(TESTFN, src)
838 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000839 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000840 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000841 'dst (%s) is in src (%s)' % (dst, src))
842 finally:
843 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000844
Tarek Ziadé5340db32010-04-19 22:30:51 +0000845
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000846class TestCopyFile(unittest.TestCase):
847
848 _delete = False
849
850 class Faux(object):
851 _entered = False
852 _exited_with = None
853 _raised = False
854 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
855 self._raise_in_exit = raise_in_exit
856 self._suppress_at_exit = suppress_at_exit
857 def read(self, *args):
858 return ''
859 def __enter__(self):
860 self._entered = True
861 def __exit__(self, exc_type, exc_val, exc_tb):
862 self._exited_with = exc_type, exc_val, exc_tb
863 if self._raise_in_exit:
864 self._raised = True
865 raise IOError("Cannot close")
866 return self._suppress_at_exit
867
868 def tearDown(self):
869 if self._delete:
870 del shutil.open
871
872 def _set_shutil_open(self, func):
873 shutil.open = func
874 self._delete = True
875
876 def test_w_source_open_fails(self):
877 def _open(filename, mode='r'):
878 if filename == 'srcfile':
879 raise IOError('Cannot open "srcfile"')
880 assert 0 # shouldn't reach here.
881
882 self._set_shutil_open(_open)
883
884 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
885
886 def test_w_dest_open_fails(self):
887
888 srcfile = self.Faux()
889
890 def _open(filename, mode='r'):
891 if filename == 'srcfile':
892 return srcfile
893 if filename == 'destfile':
894 raise IOError('Cannot open "destfile"')
895 assert 0 # shouldn't reach here.
896
897 self._set_shutil_open(_open)
898
899 shutil.copyfile('srcfile', 'destfile')
900 self.assertTrue(srcfile._entered)
901 self.assertTrue(srcfile._exited_with[0] is IOError)
902 self.assertEqual(srcfile._exited_with[1].args,
903 ('Cannot open "destfile"',))
904
905 def test_w_dest_close_fails(self):
906
907 srcfile = self.Faux()
908 destfile = self.Faux(True)
909
910 def _open(filename, mode='r'):
911 if filename == 'srcfile':
912 return srcfile
913 if filename == 'destfile':
914 return destfile
915 assert 0 # shouldn't reach here.
916
917 self._set_shutil_open(_open)
918
919 shutil.copyfile('srcfile', 'destfile')
920 self.assertTrue(srcfile._entered)
921 self.assertTrue(destfile._entered)
922 self.assertTrue(destfile._raised)
923 self.assertTrue(srcfile._exited_with[0] is IOError)
924 self.assertEqual(srcfile._exited_with[1].args,
925 ('Cannot close',))
926
927 def test_w_source_close_fails(self):
928
929 srcfile = self.Faux(True)
930 destfile = self.Faux()
931
932 def _open(filename, mode='r'):
933 if filename == 'srcfile':
934 return srcfile
935 if filename == 'destfile':
936 return destfile
937 assert 0 # shouldn't reach here.
938
939 self._set_shutil_open(_open)
940
941 self.assertRaises(IOError,
942 shutil.copyfile, 'srcfile', 'destfile')
943 self.assertTrue(srcfile._entered)
944 self.assertTrue(destfile._entered)
945 self.assertFalse(destfile._raised)
946 self.assertTrue(srcfile._exited_with[0] is None)
947 self.assertTrue(srcfile._raised)
948
Ronald Oussorenf51738b2011-05-06 10:23:04 +0200949 def test_move_dir_caseinsensitive(self):
950 # Renames a folder to the same name
951 # but a different case.
952
953 self.src_dir = tempfile.mkdtemp()
954 dst_dir = os.path.join(
955 os.path.dirname(self.src_dir),
956 os.path.basename(self.src_dir).upper())
957 self.assertNotEqual(self.src_dir, dst_dir)
958
959 try:
960 shutil.move(self.src_dir, dst_dir)
961 self.assertTrue(os.path.isdir(dst_dir))
962 finally:
963 if os.path.exists(dst_dir):
964 os.rmdir(dst_dir)
965
966
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000967
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000968def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000969 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000970
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000971if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000972 test_main()