blob: 8f1abd82d3da4ce093a4c50b4e43ec4e6e6b9cb0 [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
Ned Deilyacdc56d2012-05-10 17:45:49 -070010import errno
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000011from os.path import splitdrive
12from distutils.spawn import find_executable, spawn
13from shutil import (_make_tarball, _make_zipfile, make_archive,
14 register_archive_format, unregister_archive_format,
15 get_archive_formats)
16import tarfile
17import warnings
18
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000019from test import test_support
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000020from test.test_support import TESTFN, check_warnings, captured_stdout
21
Antoine Pitrou1fc02312009-05-01 20:55:35 +000022TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000023
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000024try:
25 import grp
26 import pwd
27 UID_GID_SUPPORT = True
28except ImportError:
29 UID_GID_SUPPORT = False
30
31try:
32 import zlib
33except ImportError:
34 zlib = None
35
36try:
37 import zipfile
38 ZIP_SUPPORT = True
39except ImportError:
40 ZIP_SUPPORT = find_executable('zip')
41
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000042class TestShutil(unittest.TestCase):
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000043
44 def setUp(self):
45 super(TestShutil, self).setUp()
46 self.tempdirs = []
47
48 def tearDown(self):
49 super(TestShutil, self).tearDown()
50 while self.tempdirs:
51 d = self.tempdirs.pop()
52 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
53
54 def write_file(self, path, content='xxx'):
55 """Writes a file in the given path.
56
57
58 path can be a string or a sequence.
59 """
60 if isinstance(path, (list, tuple)):
61 path = os.path.join(*path)
62 f = open(path, 'w')
63 try:
64 f.write(content)
65 finally:
66 f.close()
67
68 def mkdtemp(self):
69 """Create a temporary directory that will be cleaned up.
70
71 Returns the path of the directory.
72 """
73 d = tempfile.mkdtemp()
74 self.tempdirs.append(d)
75 return d
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000076 def test_rmtree_errors(self):
77 # filename is guaranteed not to exist
78 filename = tempfile.mktemp()
79 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000080
Serhiy Storchaka32e23e72013-11-03 23:15:46 +020081 @unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod()')
82 @unittest.skipIf(sys.platform[:6] == 'cygwin',
83 "This test can't be run on Cygwin (issue #1071513).")
84 @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
85 "This test can't be run reliably as root (issue #1076467).")
86 def test_on_error(self):
87 self.errorState = 0
88 os.mkdir(TESTFN)
89 self.childpath = os.path.join(TESTFN, 'a')
90 f = open(self.childpath, 'w')
91 f.close()
92 old_dir_mode = os.stat(TESTFN).st_mode
93 old_child_mode = os.stat(self.childpath).st_mode
94 # Make unwritable.
95 os.chmod(self.childpath, stat.S_IREAD)
96 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000097
Serhiy Storchaka32e23e72013-11-03 23:15:46 +020098 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
99 # Test whether onerror has actually been called.
100 self.assertEqual(self.errorState, 2,
101 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000102
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200103 # Make writable again.
104 os.chmod(TESTFN, old_dir_mode)
105 os.chmod(self.childpath, old_child_mode)
Tim Peters4590c002004-11-01 02:40:52 +0000106
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200107 # Clean up.
108 shutil.rmtree(TESTFN)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000109
110 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson9c6fc512009-04-29 22:43:35 +0000111 # test_rmtree_errors deliberately runs rmtree
112 # on a directory that is chmod 400, which will fail.
113 # This function is run when shutil.rmtree fails.
114 # 99.9% of the time it initially fails to remove
115 # a file in the directory, so the first time through
116 # func is os.remove.
117 # However, some Linux machines running ZFS on
118 # FUSE experienced a failure earlier in the process
119 # at os.listdir. The first failure may legally
120 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000121 if self.errorState == 0:
Benjamin Peterson9c6fc512009-04-29 22:43:35 +0000122 if func is os.remove:
123 self.assertEqual(arg, self.childpath)
124 else:
125 self.assertIs(func, os.listdir,
126 "func must be either os.remove or os.listdir")
127 self.assertEqual(arg, TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000128 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000129 self.errorState = 1
130 else:
131 self.assertEqual(func, os.rmdir)
132 self.assertEqual(arg, TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000133 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000134 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000135
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000136 def test_rmtree_dont_delete_file(self):
137 # When called on a file instead of a directory, don't delete it.
138 handle, path = tempfile.mkstemp()
139 os.fdopen(handle).close()
140 self.assertRaises(OSError, shutil.rmtree, path)
141 os.remove(path)
142
Martin v. Löwis4e678382006-07-30 13:00:31 +0000143 def test_copytree_simple(self):
Tim Petersb2dd1a32006-08-10 03:01:26 +0000144 def write_data(path, data):
145 f = open(path, "w")
146 f.write(data)
147 f.close()
148
149 def read_data(path):
150 f = open(path)
151 data = f.read()
152 f.close()
153 return data
154
Martin v. Löwis4e678382006-07-30 13:00:31 +0000155 src_dir = tempfile.mkdtemp()
156 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tim Petersb2dd1a32006-08-10 03:01:26 +0000157
158 write_data(os.path.join(src_dir, 'test.txt'), '123')
159
Martin v. Löwis4e678382006-07-30 13:00:31 +0000160 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tim Petersb2dd1a32006-08-10 03:01:26 +0000161 write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
162
Martin v. Löwis4e678382006-07-30 13:00:31 +0000163 try:
164 shutil.copytree(src_dir, dst_dir)
165 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
166 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
Tim Petersb2dd1a32006-08-10 03:01:26 +0000167 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
168 'test.txt')))
169 actual = read_data(os.path.join(dst_dir, 'test.txt'))
170 self.assertEqual(actual, '123')
171 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
172 self.assertEqual(actual, '456')
Martin v. Löwis4e678382006-07-30 13:00:31 +0000173 finally:
Tim Petersb2dd1a32006-08-10 03:01:26 +0000174 for path in (
175 os.path.join(src_dir, 'test.txt'),
176 os.path.join(dst_dir, 'test.txt'),
177 os.path.join(src_dir, 'test_dir', 'test.txt'),
178 os.path.join(dst_dir, 'test_dir', 'test.txt'),
179 ):
180 if os.path.exists(path):
181 os.remove(path)
Christian Heimes547867e2007-11-20 03:21:02 +0000182 for path in (src_dir,
Antoine Pitrou4ac6b932009-11-04 00:50:26 +0000183 os.path.dirname(dst_dir)
Christian Heimes547867e2007-11-20 03:21:02 +0000184 ):
Tim Petersb2dd1a32006-08-10 03:01:26 +0000185 if os.path.exists(path):
Christian Heimes044d7092007-11-20 01:48:48 +0000186 shutil.rmtree(path)
Tim Peters64584522006-07-31 01:46:03 +0000187
Georg Brandle78fbcc2008-07-05 10:13:36 +0000188 def test_copytree_with_exclude(self):
189
190 def write_data(path, data):
191 f = open(path, "w")
192 f.write(data)
193 f.close()
194
195 def read_data(path):
196 f = open(path)
197 data = f.read()
198 f.close()
199 return data
200
201 # creating data
202 join = os.path.join
203 exists = os.path.exists
204 src_dir = tempfile.mkdtemp()
Georg Brandle78fbcc2008-07-05 10:13:36 +0000205 try:
Antoine Pitrou4ac6b932009-11-04 00:50:26 +0000206 dst_dir = join(tempfile.mkdtemp(), 'destination')
207 write_data(join(src_dir, 'test.txt'), '123')
208 write_data(join(src_dir, 'test.tmp'), '123')
209 os.mkdir(join(src_dir, 'test_dir'))
210 write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
211 os.mkdir(join(src_dir, 'test_dir2'))
212 write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
213 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
214 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
215 write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
216 write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
217
218
219 # testing glob-like patterns
220 try:
221 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
222 shutil.copytree(src_dir, dst_dir, ignore=patterns)
223 # checking the result: some elements should not be copied
224 self.assertTrue(exists(join(dst_dir, 'test.txt')))
225 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
226 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
227 finally:
228 if os.path.exists(dst_dir):
229 shutil.rmtree(dst_dir)
230 try:
231 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
232 shutil.copytree(src_dir, dst_dir, ignore=patterns)
233 # checking the result: some elements should not be copied
234 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
235 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
236 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
237 finally:
238 if os.path.exists(dst_dir):
239 shutil.rmtree(dst_dir)
240
241 # testing callable-style
242 try:
243 def _filter(src, names):
244 res = []
245 for name in names:
246 path = os.path.join(src, name)
247
248 if (os.path.isdir(path) and
249 path.split()[-1] == 'subdir'):
250 res.append(name)
251 elif os.path.splitext(path)[-1] in ('.py'):
252 res.append(name)
253 return res
254
255 shutil.copytree(src_dir, dst_dir, ignore=_filter)
256
257 # checking the result: some elements should not be copied
258 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
259 'test.py')))
260 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
261
262 finally:
263 if os.path.exists(dst_dir):
264 shutil.rmtree(dst_dir)
Georg Brandle78fbcc2008-07-05 10:13:36 +0000265 finally:
Antoine Pitrou4ac6b932009-11-04 00:50:26 +0000266 shutil.rmtree(src_dir)
267 shutil.rmtree(os.path.dirname(dst_dir))
Tim Peters64584522006-07-31 01:46:03 +0000268
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000269 if hasattr(os, "symlink"):
270 def test_dont_copy_file_onto_link_to_itself(self):
271 # bug 851123.
272 os.mkdir(TESTFN)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000273 src = os.path.join(TESTFN, 'cheese')
274 dst = os.path.join(TESTFN, 'shop')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000275 try:
Johannes Gijsbers68128712004-08-14 13:57:08 +0000276 f = open(src, 'w')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000277 f.write('cheddar')
278 f.close()
Johannes Gijsbers68128712004-08-14 13:57:08 +0000279
280 os.link(src, dst)
281 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou99d848b2010-10-14 22:22:30 +0000282 with open(src, 'r') as f:
283 self.assertEqual(f.read(), 'cheddar')
Johannes Gijsbers68128712004-08-14 13:57:08 +0000284 os.remove(dst)
285
286 # Using `src` here would mean we end up with a symlink pointing
287 # to TESTFN/TESTFN/cheese, while it should point at
288 # TESTFN/cheese.
289 os.symlink('cheese', dst)
290 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
Antoine Pitrou99d848b2010-10-14 22:22:30 +0000291 with open(src, 'r') as f:
292 self.assertEqual(f.read(), 'cheddar')
Johannes Gijsbers68128712004-08-14 13:57:08 +0000293 os.remove(dst)
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000294 finally:
295 try:
296 shutil.rmtree(TESTFN)
297 except OSError:
298 pass
Brett Cannon1c3fa182004-06-19 21:11:35 +0000299
Georg Brandl52353982008-01-20 14:17:42 +0000300 def test_rmtree_on_symlink(self):
301 # bug 1669.
302 os.mkdir(TESTFN)
303 try:
304 src = os.path.join(TESTFN, 'cheese')
305 dst = os.path.join(TESTFN, 'shop')
306 os.mkdir(src)
307 os.symlink(src, dst)
308 self.assertRaises(OSError, shutil.rmtree, dst)
309 finally:
310 shutil.rmtree(TESTFN, ignore_errors=True)
311
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200312 # Issue #3002: copyfile and copytree block indefinitely on named pipes
313 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
314 def test_copyfile_named_pipe(self):
315 os.mkfifo(TESTFN)
316 try:
317 self.assertRaises(shutil.SpecialFileError,
318 shutil.copyfile, TESTFN, TESTFN2)
319 self.assertRaises(shutil.SpecialFileError,
320 shutil.copyfile, __file__, TESTFN)
321 finally:
322 os.remove(TESTFN)
Antoine Pitrou1fc02312009-05-01 20:55:35 +0000323
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200324 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
325 def test_copytree_named_pipe(self):
326 os.mkdir(TESTFN)
327 try:
328 subdir = os.path.join(TESTFN, "subdir")
329 os.mkdir(subdir)
330 pipe = os.path.join(subdir, "mypipe")
331 os.mkfifo(pipe)
Antoine Pitrou1fc02312009-05-01 20:55:35 +0000332 try:
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200333 shutil.copytree(TESTFN, TESTFN2)
334 except shutil.Error as e:
335 errors = e.args[0]
336 self.assertEqual(len(errors), 1)
337 src, dst, error_msg = errors[0]
338 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
339 else:
340 self.fail("shutil.Error should have been raised")
341 finally:
342 shutil.rmtree(TESTFN, ignore_errors=True)
343 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou1fc02312009-05-01 20:55:35 +0000344
Ned Deilyacdc56d2012-05-10 17:45:49 -0700345 @unittest.skipUnless(hasattr(os, 'chflags') and
346 hasattr(errno, 'EOPNOTSUPP') and
347 hasattr(errno, 'ENOTSUP'),
348 "requires os.chflags, EOPNOTSUPP & ENOTSUP")
349 def test_copystat_handles_harmless_chflags_errors(self):
350 tmpdir = self.mkdtemp()
351 file1 = os.path.join(tmpdir, 'file1')
352 file2 = os.path.join(tmpdir, 'file2')
353 self.write_file(file1, 'xxx')
354 self.write_file(file2, 'xxx')
355
356 def make_chflags_raiser(err):
357 ex = OSError()
358
359 def _chflags_raiser(path, flags):
360 ex.errno = err
361 raise ex
362 return _chflags_raiser
363 old_chflags = os.chflags
364 try:
365 for err in errno.EOPNOTSUPP, errno.ENOTSUP:
366 os.chflags = make_chflags_raiser(err)
367 shutil.copystat(file1, file2)
368 # assert others errors break it
369 os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
370 self.assertRaises(OSError, shutil.copystat, file1, file2)
371 finally:
372 os.chflags = old_chflags
373
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000374 @unittest.skipUnless(zlib, "requires zlib")
375 def test_make_tarball(self):
376 # creating something to tar
377 tmpdir = self.mkdtemp()
378 self.write_file([tmpdir, 'file1'], 'xxx')
379 self.write_file([tmpdir, 'file2'], 'xxx')
380 os.mkdir(os.path.join(tmpdir, 'sub'))
381 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
382
383 tmpdir2 = self.mkdtemp()
Éric Araujoe7329f42011-08-19 03:07:39 +0200384 # force shutil to create the directory
385 os.rmdir(tmpdir2)
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000386 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
387 "source and target should be on same drive")
388
389 base_name = os.path.join(tmpdir2, 'archive')
390
391 # working with relative paths to avoid tar warnings
392 old_dir = os.getcwd()
393 os.chdir(tmpdir)
394 try:
395 _make_tarball(splitdrive(base_name)[1], '.')
396 finally:
397 os.chdir(old_dir)
398
399 # check if the compressed tarball was created
400 tarball = base_name + '.tar.gz'
401 self.assertTrue(os.path.exists(tarball))
402
403 # trying an uncompressed one
404 base_name = os.path.join(tmpdir2, 'archive')
405 old_dir = os.getcwd()
406 os.chdir(tmpdir)
407 try:
408 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
409 finally:
410 os.chdir(old_dir)
411 tarball = base_name + '.tar'
412 self.assertTrue(os.path.exists(tarball))
413
414 def _tarinfo(self, path):
415 tar = tarfile.open(path)
416 try:
417 names = tar.getnames()
418 names.sort()
419 return tuple(names)
420 finally:
421 tar.close()
422
423 def _create_files(self):
424 # creating something to tar
425 tmpdir = self.mkdtemp()
426 dist = os.path.join(tmpdir, 'dist')
427 os.mkdir(dist)
428 self.write_file([dist, 'file1'], 'xxx')
429 self.write_file([dist, 'file2'], 'xxx')
430 os.mkdir(os.path.join(dist, 'sub'))
431 self.write_file([dist, 'sub', 'file3'], 'xxx')
432 os.mkdir(os.path.join(dist, 'sub2'))
433 tmpdir2 = self.mkdtemp()
434 base_name = os.path.join(tmpdir2, 'archive')
435 return tmpdir, tmpdir2, base_name
436
437 @unittest.skipUnless(zlib, "Requires zlib")
438 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
439 'Need the tar command to run')
440 def test_tarfile_vs_tar(self):
441 tmpdir, tmpdir2, base_name = self._create_files()
442 old_dir = os.getcwd()
443 os.chdir(tmpdir)
444 try:
445 _make_tarball(base_name, 'dist')
446 finally:
447 os.chdir(old_dir)
448
449 # check if the compressed tarball was created
450 tarball = base_name + '.tar.gz'
451 self.assertTrue(os.path.exists(tarball))
452
453 # now create another tarball using `tar`
454 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
455 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
456 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
457 old_dir = os.getcwd()
458 os.chdir(tmpdir)
459 try:
460 with captured_stdout() as s:
461 spawn(tar_cmd)
462 spawn(gzip_cmd)
463 finally:
464 os.chdir(old_dir)
465
466 self.assertTrue(os.path.exists(tarball2))
467 # let's compare both tarballs
Ezio Melotti2623a372010-11-21 13:34:58 +0000468 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000469
470 # trying an uncompressed one
471 base_name = os.path.join(tmpdir2, 'archive')
472 old_dir = os.getcwd()
473 os.chdir(tmpdir)
474 try:
475 _make_tarball(base_name, 'dist', compress=None)
476 finally:
477 os.chdir(old_dir)
478 tarball = base_name + '.tar'
479 self.assertTrue(os.path.exists(tarball))
480
481 # now for a dry_run
482 base_name = os.path.join(tmpdir2, 'archive')
483 old_dir = os.getcwd()
484 os.chdir(tmpdir)
485 try:
486 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
487 finally:
488 os.chdir(old_dir)
489 tarball = base_name + '.tar'
490 self.assertTrue(os.path.exists(tarball))
491
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000492 @unittest.skipUnless(zlib, "Requires zlib")
493 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
494 def test_make_zipfile(self):
495 # creating something to tar
496 tmpdir = self.mkdtemp()
497 self.write_file([tmpdir, 'file1'], 'xxx')
498 self.write_file([tmpdir, 'file2'], 'xxx')
499
500 tmpdir2 = self.mkdtemp()
Éric Araujoe7329f42011-08-19 03:07:39 +0200501 # force shutil to create the directory
502 os.rmdir(tmpdir2)
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000503 base_name = os.path.join(tmpdir2, 'archive')
504 _make_zipfile(base_name, tmpdir)
505
506 # check if the compressed tarball was created
507 tarball = base_name + '.zip'
Éric Araujo1c4253d2010-11-17 23:11:08 +0000508 self.assertTrue(os.path.exists(tarball))
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000509
510
511 def test_make_archive(self):
512 tmpdir = self.mkdtemp()
513 base_name = os.path.join(tmpdir, 'archive')
514 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
515
516 @unittest.skipUnless(zlib, "Requires zlib")
517 def test_make_archive_owner_group(self):
518 # testing make_archive with owner and group, with various combinations
519 # this works even if there's not gid/uid support
520 if UID_GID_SUPPORT:
521 group = grp.getgrgid(0)[0]
522 owner = pwd.getpwuid(0)[0]
523 else:
524 group = owner = 'root'
525
526 base_dir, root_dir, base_name = self._create_files()
527 base_name = os.path.join(self.mkdtemp() , 'archive')
528 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
529 group=group)
530 self.assertTrue(os.path.exists(res))
531
532 res = make_archive(base_name, 'zip', root_dir, base_dir)
533 self.assertTrue(os.path.exists(res))
534
535 res = make_archive(base_name, 'tar', root_dir, base_dir,
536 owner=owner, group=group)
537 self.assertTrue(os.path.exists(res))
538
539 res = make_archive(base_name, 'tar', root_dir, base_dir,
540 owner='kjhkjhkjg', group='oihohoh')
541 self.assertTrue(os.path.exists(res))
542
543 @unittest.skipUnless(zlib, "Requires zlib")
544 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
545 def test_tarfile_root_owner(self):
546 tmpdir, tmpdir2, base_name = self._create_files()
547 old_dir = os.getcwd()
548 os.chdir(tmpdir)
549 group = grp.getgrgid(0)[0]
550 owner = pwd.getpwuid(0)[0]
551 try:
552 archive_name = _make_tarball(base_name, 'dist', compress=None,
553 owner=owner, group=group)
554 finally:
555 os.chdir(old_dir)
556
557 # check if the compressed tarball was created
558 self.assertTrue(os.path.exists(archive_name))
559
560 # now checks the rights
561 archive = tarfile.open(archive_name)
562 try:
563 for member in archive.getmembers():
Ezio Melotti2623a372010-11-21 13:34:58 +0000564 self.assertEqual(member.uid, 0)
565 self.assertEqual(member.gid, 0)
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000566 finally:
567 archive.close()
568
569 def test_make_archive_cwd(self):
570 current_dir = os.getcwd()
571 def _breaks(*args, **kw):
572 raise RuntimeError()
573
574 register_archive_format('xxx', _breaks, [], 'xxx file')
575 try:
576 try:
577 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
578 except Exception:
579 pass
Ezio Melotti2623a372010-11-21 13:34:58 +0000580 self.assertEqual(os.getcwd(), current_dir)
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000581 finally:
582 unregister_archive_format('xxx')
583
584 def test_register_archive_format(self):
585
586 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
587 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
588 1)
589 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
590 [(1, 2), (1, 2, 3)])
591
592 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
593 formats = [name for name, params in get_archive_formats()]
594 self.assertIn('xxx', formats)
595
596 unregister_archive_format('xxx')
597 formats = [name for name, params in get_archive_formats()]
598 self.assertNotIn('xxx', formats)
599
Georg Brandl52353982008-01-20 14:17:42 +0000600
Sean Reifscheider493894c2008-03-18 17:24:12 +0000601class TestMove(unittest.TestCase):
602
603 def setUp(self):
604 filename = "foo"
605 self.src_dir = tempfile.mkdtemp()
606 self.dst_dir = tempfile.mkdtemp()
607 self.src_file = os.path.join(self.src_dir, filename)
608 self.dst_file = os.path.join(self.dst_dir, filename)
609 # Try to create a dir in the current directory, hoping that it is
610 # not located on the same filesystem as the system tmp dir.
611 try:
612 self.dir_other_fs = tempfile.mkdtemp(
613 dir=os.path.dirname(__file__))
614 self.file_other_fs = os.path.join(self.dir_other_fs,
615 filename)
616 except OSError:
617 self.dir_other_fs = None
618 with open(self.src_file, "wb") as f:
619 f.write("spam")
620
621 def tearDown(self):
622 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
623 try:
624 if d:
625 shutil.rmtree(d)
626 except:
627 pass
628
629 def _check_move_file(self, src, dst, real_dst):
Antoine Pitrou99d848b2010-10-14 22:22:30 +0000630 with open(src, "rb") as f:
631 contents = f.read()
Sean Reifscheider493894c2008-03-18 17:24:12 +0000632 shutil.move(src, dst)
Antoine Pitrou99d848b2010-10-14 22:22:30 +0000633 with open(real_dst, "rb") as f:
634 self.assertEqual(contents, f.read())
Sean Reifscheider493894c2008-03-18 17:24:12 +0000635 self.assertFalse(os.path.exists(src))
636
637 def _check_move_dir(self, src, dst, real_dst):
638 contents = sorted(os.listdir(src))
639 shutil.move(src, dst)
640 self.assertEqual(contents, sorted(os.listdir(real_dst)))
641 self.assertFalse(os.path.exists(src))
642
643 def test_move_file(self):
644 # Move a file to another location on the same filesystem.
645 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
646
647 def test_move_file_to_dir(self):
648 # Move a file inside an existing dir on the same filesystem.
649 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
650
651 def test_move_file_other_fs(self):
652 # Move a file to an existing dir on another filesystem.
653 if not self.dir_other_fs:
654 # skip
655 return
656 self._check_move_file(self.src_file, self.file_other_fs,
657 self.file_other_fs)
658
659 def test_move_file_to_dir_other_fs(self):
660 # Move a file to another location on another filesystem.
661 if not self.dir_other_fs:
662 # skip
663 return
664 self._check_move_file(self.src_file, self.dir_other_fs,
665 self.file_other_fs)
666
667 def test_move_dir(self):
668 # Move a dir to another location on the same filesystem.
669 dst_dir = tempfile.mktemp()
670 try:
671 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
672 finally:
673 try:
674 shutil.rmtree(dst_dir)
675 except:
676 pass
677
678 def test_move_dir_other_fs(self):
679 # Move a dir to another location on another filesystem.
680 if not self.dir_other_fs:
681 # skip
682 return
683 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
684 try:
685 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
686 finally:
687 try:
688 shutil.rmtree(dst_dir)
689 except:
690 pass
691
692 def test_move_dir_to_dir(self):
693 # Move a dir inside an existing dir on the same filesystem.
694 self._check_move_dir(self.src_dir, self.dst_dir,
695 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
696
697 def test_move_dir_to_dir_other_fs(self):
698 # Move a dir inside an existing dir on another filesystem.
699 if not self.dir_other_fs:
700 # skip
701 return
702 self._check_move_dir(self.src_dir, self.dir_other_fs,
703 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
704
705 def test_existing_file_inside_dest_dir(self):
706 # A file with the same name inside the destination dir already exists.
707 with open(self.dst_file, "wb"):
708 pass
709 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
710
711 def test_dont_move_dir_in_itself(self):
712 # Moving a dir inside itself raises an Error.
713 dst = os.path.join(self.src_dir, "bar")
714 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
715
Antoine Pitrou707c5932009-01-29 20:19:34 +0000716 def test_destinsrc_false_negative(self):
717 os.mkdir(TESTFN)
718 try:
719 for src, dst in [('srcdir', 'srcdir/dest')]:
720 src = os.path.join(TESTFN, src)
721 dst = os.path.join(TESTFN, dst)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000722 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000723 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou707c5932009-01-29 20:19:34 +0000724 'dst (%s) is not in src (%s)' % (dst, src))
725 finally:
726 shutil.rmtree(TESTFN, ignore_errors=True)
Sean Reifscheider493894c2008-03-18 17:24:12 +0000727
Antoine Pitrou707c5932009-01-29 20:19:34 +0000728 def test_destinsrc_false_positive(self):
729 os.mkdir(TESTFN)
730 try:
731 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
732 src = os.path.join(TESTFN, src)
733 dst = os.path.join(TESTFN, dst)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000734 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000735 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou707c5932009-01-29 20:19:34 +0000736 'dst (%s) is in src (%s)' % (dst, src))
737 finally:
738 shutil.rmtree(TESTFN, ignore_errors=True)
Georg Brandl52353982008-01-20 14:17:42 +0000739
Tarek Ziadé38f81222010-05-05 22:15:31 +0000740
741class TestCopyFile(unittest.TestCase):
742
743 _delete = False
744
745 class Faux(object):
746 _entered = False
747 _exited_with = None
748 _raised = False
749 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
750 self._raise_in_exit = raise_in_exit
751 self._suppress_at_exit = suppress_at_exit
752 def read(self, *args):
753 return ''
754 def __enter__(self):
755 self._entered = True
756 def __exit__(self, exc_type, exc_val, exc_tb):
757 self._exited_with = exc_type, exc_val, exc_tb
758 if self._raise_in_exit:
759 self._raised = True
760 raise IOError("Cannot close")
761 return self._suppress_at_exit
762
763 def tearDown(self):
764 if self._delete:
765 del shutil.open
766
767 def _set_shutil_open(self, func):
768 shutil.open = func
769 self._delete = True
770
771 def test_w_source_open_fails(self):
772 def _open(filename, mode='r'):
773 if filename == 'srcfile':
774 raise IOError('Cannot open "srcfile"')
775 assert 0 # shouldn't reach here.
776
777 self._set_shutil_open(_open)
778
779 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
780
781 def test_w_dest_open_fails(self):
782
783 srcfile = self.Faux()
784
785 def _open(filename, mode='r'):
786 if filename == 'srcfile':
787 return srcfile
788 if filename == 'destfile':
789 raise IOError('Cannot open "destfile"')
790 assert 0 # shouldn't reach here.
791
792 self._set_shutil_open(_open)
793
794 shutil.copyfile('srcfile', 'destfile')
Ezio Melotti62c3c792010-06-05 22:28:10 +0000795 self.assertTrue(srcfile._entered)
796 self.assertTrue(srcfile._exited_with[0] is IOError)
Tarek Ziadé38f81222010-05-05 22:15:31 +0000797 self.assertEqual(srcfile._exited_with[1].args,
798 ('Cannot open "destfile"',))
799
800 def test_w_dest_close_fails(self):
801
802 srcfile = self.Faux()
803 destfile = self.Faux(True)
804
805 def _open(filename, mode='r'):
806 if filename == 'srcfile':
807 return srcfile
808 if filename == 'destfile':
809 return destfile
810 assert 0 # shouldn't reach here.
811
812 self._set_shutil_open(_open)
813
814 shutil.copyfile('srcfile', 'destfile')
Ezio Melotti62c3c792010-06-05 22:28:10 +0000815 self.assertTrue(srcfile._entered)
816 self.assertTrue(destfile._entered)
817 self.assertTrue(destfile._raised)
818 self.assertTrue(srcfile._exited_with[0] is IOError)
Tarek Ziadé38f81222010-05-05 22:15:31 +0000819 self.assertEqual(srcfile._exited_with[1].args,
820 ('Cannot close',))
821
822 def test_w_source_close_fails(self):
823
824 srcfile = self.Faux(True)
825 destfile = self.Faux()
826
827 def _open(filename, mode='r'):
828 if filename == 'srcfile':
829 return srcfile
830 if filename == 'destfile':
831 return destfile
832 assert 0 # shouldn't reach here.
833
834 self._set_shutil_open(_open)
835
836 self.assertRaises(IOError,
837 shutil.copyfile, 'srcfile', 'destfile')
Ezio Melotti62c3c792010-06-05 22:28:10 +0000838 self.assertTrue(srcfile._entered)
839 self.assertTrue(destfile._entered)
840 self.assertFalse(destfile._raised)
841 self.assertTrue(srcfile._exited_with[0] is None)
842 self.assertTrue(srcfile._raised)
Tarek Ziadé38f81222010-05-05 22:15:31 +0000843
Ronald Oussoren58d6b1b2011-05-06 11:31:33 +0200844 def test_move_dir_caseinsensitive(self):
845 # Renames a folder to the same name
846 # but a different case.
847
848 self.src_dir = tempfile.mkdtemp()
849 dst_dir = os.path.join(
850 os.path.dirname(self.src_dir),
851 os.path.basename(self.src_dir).upper())
852 self.assertNotEqual(self.src_dir, dst_dir)
853
854 try:
855 shutil.move(self.src_dir, dst_dir)
856 self.assertTrue(os.path.isdir(dst_dir))
857 finally:
858 if os.path.exists(dst_dir):
859 os.rmdir(dst_dir)
860
861
Tarek Ziadé38f81222010-05-05 22:15:31 +0000862
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000863def test_main():
Tarek Ziadé38f81222010-05-05 22:15:31 +0000864 test_support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000865
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000866if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000867 test_main()