blob: f2e5d9b9affdd9d1f5a3313e36bf81dae9dbb8e6 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
11from test.support import TESTFN
Tarek Ziadé396fad72010-02-23 05:30:31 +000012from os.path import splitdrive
13from distutils.spawn import find_executable, spawn
14from shutil import (_make_tarball, _make_zipfile, make_archive,
15 register_archive_format, unregister_archive_format,
16 get_archive_formats)
17import tarfile
18import warnings
19
20from test import support
21from test.support import TESTFN, check_warnings, captured_stdout
22
Antoine Pitrou7fff0962009-05-01 21:09:44 +000023TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000024
Tarek Ziadé396fad72010-02-23 05:30:31 +000025try:
26 import grp
27 import pwd
28 UID_GID_SUPPORT = True
29except ImportError:
30 UID_GID_SUPPORT = False
31
32try:
33 import zlib
34except ImportError:
35 zlib = None
36
37try:
38 import zipfile
39 ZIP_SUPPORT = True
40except ImportError:
41 ZIP_SUPPORT = find_executable('zip')
42
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000043class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000044
45 def setUp(self):
46 super(TestShutil, self).setUp()
47 self.tempdirs = []
48
49 def tearDown(self):
50 super(TestShutil, self).tearDown()
51 while self.tempdirs:
52 d = self.tempdirs.pop()
53 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
54
55 def write_file(self, path, content='xxx'):
56 """Writes a file in the given path.
57
58
59 path can be a string or a sequence.
60 """
61 if isinstance(path, (list, tuple)):
62 path = os.path.join(*path)
63 f = open(path, 'w')
64 try:
65 f.write(content)
66 finally:
67 f.close()
68
69 def mkdtemp(self):
70 """Create a temporary directory that will be cleaned up.
71
72 Returns the path of the directory.
73 """
74 d = tempfile.mkdtemp()
75 self.tempdirs.append(d)
76 return d
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000077 def test_rmtree_errors(self):
78 # filename is guaranteed not to exist
79 filename = tempfile.mktemp()
80 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000081
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000082 # See bug #1071513 for why we don't run this on cygwin
83 # and bug #1076467 for why we don't run this as root.
84 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000085 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000086 def test_on_error(self):
87 self.errorState = 0
88 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000089 self.childpath = os.path.join(TESTFN, 'a')
90 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000091 f.close()
Tim Peters4590c002004-11-01 02:40:52 +000092 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
98 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +000099 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000100 self.assertEqual(self.errorState, 2,
101 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000102
Tim Peters4590c002004-11-01 02:40:52 +0000103 # Make writable again.
104 os.chmod(TESTFN, old_dir_mode)
105 os.chmod(self.childpath, old_child_mode)
106
107 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000108 shutil.rmtree(TESTFN)
109
110 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +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 Peterson25c95f12009-05-08 20:42:26 +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 Petersonc9c0f202009-06-30 23:06:06 +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 Petersonc9c0f202009-06-30 23:06:06 +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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 def test_copytree_simple(self):
144 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
155 src_dir = tempfile.mkdtemp()
156 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
157
158 write_data(os.path.join(src_dir, 'test.txt'), '123')
159
160 os.mkdir(os.path.join(src_dir, 'test_dir'))
161 write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
162
163 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')))
167 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')
173 finally:
174 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 Heimese052dd82007-11-20 03:20:04 +0000182 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000183 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000184 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000186 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187
Georg Brandl2ee470f2008-07-16 12:55:28 +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 Brandl2ee470f2008-07-16 12:55:28 +0000205 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +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 Brandl2ee470f2008-07-16 12:55:28 +0000265 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000266 shutil.rmtree(src_dir)
267 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +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)
282 self.assertEqual(open(src,'r').read(), 'cheddar')
283 os.remove(dst)
284
285 # Using `src` here would mean we end up with a symlink pointing
286 # to TESTFN/TESTFN/cheese, while it should point at
287 # TESTFN/cheese.
288 os.symlink('cheese', dst)
289 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
290 self.assertEqual(open(src,'r').read(), 'cheddar')
291 os.remove(dst)
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000292 finally:
293 try:
294 shutil.rmtree(TESTFN)
295 except OSError:
296 pass
Brett Cannon1c3fa182004-06-19 21:11:35 +0000297
Christian Heimes9bd667a2008-01-20 15:14:11 +0000298 def test_rmtree_on_symlink(self):
299 # bug 1669.
300 os.mkdir(TESTFN)
301 try:
302 src = os.path.join(TESTFN, 'cheese')
303 dst = os.path.join(TESTFN, 'shop')
304 os.mkdir(src)
305 os.symlink(src, dst)
306 self.assertRaises(OSError, shutil.rmtree, dst)
307 finally:
308 shutil.rmtree(TESTFN, ignore_errors=True)
309
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000310 if hasattr(os, "mkfifo"):
311 # Issue #3002: copyfile and copytree block indefinitely on named pipes
312 def test_copyfile_named_pipe(self):
313 os.mkfifo(TESTFN)
314 try:
315 self.assertRaises(shutil.SpecialFileError,
316 shutil.copyfile, TESTFN, TESTFN2)
317 self.assertRaises(shutil.SpecialFileError,
318 shutil.copyfile, __file__, TESTFN)
319 finally:
320 os.remove(TESTFN)
321
322 def test_copytree_named_pipe(self):
323 os.mkdir(TESTFN)
324 try:
325 subdir = os.path.join(TESTFN, "subdir")
326 os.mkdir(subdir)
327 pipe = os.path.join(subdir, "mypipe")
328 os.mkfifo(pipe)
329 try:
330 shutil.copytree(TESTFN, TESTFN2)
331 except shutil.Error as e:
332 errors = e.args[0]
333 self.assertEqual(len(errors), 1)
334 src, dst, error_msg = errors[0]
335 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
336 else:
337 self.fail("shutil.Error should have been raised")
338 finally:
339 shutil.rmtree(TESTFN, ignore_errors=True)
340 shutil.rmtree(TESTFN2, ignore_errors=True)
341
Tarek Ziadé396fad72010-02-23 05:30:31 +0000342 @unittest.skipUnless(zlib, "requires zlib")
343 def test_make_tarball(self):
344 # creating something to tar
345 tmpdir = self.mkdtemp()
346 self.write_file([tmpdir, 'file1'], 'xxx')
347 self.write_file([tmpdir, 'file2'], 'xxx')
348 os.mkdir(os.path.join(tmpdir, 'sub'))
349 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
350
351 tmpdir2 = self.mkdtemp()
352 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
353 "source and target should be on same drive")
354
355 base_name = os.path.join(tmpdir2, 'archive')
356
357 # working with relative paths to avoid tar warnings
358 old_dir = os.getcwd()
359 os.chdir(tmpdir)
360 try:
361 _make_tarball(splitdrive(base_name)[1], '.')
362 finally:
363 os.chdir(old_dir)
364
365 # check if the compressed tarball was created
366 tarball = base_name + '.tar.gz'
367 self.assertTrue(os.path.exists(tarball))
368
369 # trying an uncompressed one
370 base_name = os.path.join(tmpdir2, 'archive')
371 old_dir = os.getcwd()
372 os.chdir(tmpdir)
373 try:
374 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
375 finally:
376 os.chdir(old_dir)
377 tarball = base_name + '.tar'
378 self.assertTrue(os.path.exists(tarball))
379
380 def _tarinfo(self, path):
381 tar = tarfile.open(path)
382 try:
383 names = tar.getnames()
384 names.sort()
385 return tuple(names)
386 finally:
387 tar.close()
388
389 def _create_files(self):
390 # creating something to tar
391 tmpdir = self.mkdtemp()
392 dist = os.path.join(tmpdir, 'dist')
393 os.mkdir(dist)
394 self.write_file([dist, 'file1'], 'xxx')
395 self.write_file([dist, 'file2'], 'xxx')
396 os.mkdir(os.path.join(dist, 'sub'))
397 self.write_file([dist, 'sub', 'file3'], 'xxx')
398 os.mkdir(os.path.join(dist, 'sub2'))
399 tmpdir2 = self.mkdtemp()
400 base_name = os.path.join(tmpdir2, 'archive')
401 return tmpdir, tmpdir2, base_name
402
403 @unittest.skipUnless(zlib, "Requires zlib")
404 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
405 'Need the tar command to run')
406 def test_tarfile_vs_tar(self):
407 tmpdir, tmpdir2, base_name = self._create_files()
408 old_dir = os.getcwd()
409 os.chdir(tmpdir)
410 try:
411 _make_tarball(base_name, 'dist')
412 finally:
413 os.chdir(old_dir)
414
415 # check if the compressed tarball was created
416 tarball = base_name + '.tar.gz'
417 self.assertTrue(os.path.exists(tarball))
418
419 # now create another tarball using `tar`
420 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
421 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
422 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
423 old_dir = os.getcwd()
424 os.chdir(tmpdir)
425 try:
426 with captured_stdout() as s:
427 spawn(tar_cmd)
428 spawn(gzip_cmd)
429 finally:
430 os.chdir(old_dir)
431
432 self.assertTrue(os.path.exists(tarball2))
433 # let's compare both tarballs
434 self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2))
435
436 # trying an uncompressed one
437 base_name = os.path.join(tmpdir2, 'archive')
438 old_dir = os.getcwd()
439 os.chdir(tmpdir)
440 try:
441 _make_tarball(base_name, 'dist', compress=None)
442 finally:
443 os.chdir(old_dir)
444 tarball = base_name + '.tar'
445 self.assertTrue(os.path.exists(tarball))
446
447 # now for a dry_run
448 base_name = os.path.join(tmpdir2, 'archive')
449 old_dir = os.getcwd()
450 os.chdir(tmpdir)
451 try:
452 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
453 finally:
454 os.chdir(old_dir)
455 tarball = base_name + '.tar'
456 self.assertTrue(os.path.exists(tarball))
457
458 @unittest.skipUnless(find_executable('compress'),
459 'The compress program is required')
460 def test_compress_deprecated(self):
461 tmpdir, tmpdir2, base_name = self._create_files()
462
463 # using compress and testing the PendingDeprecationWarning
464 old_dir = os.getcwd()
465 os.chdir(tmpdir)
466 try:
467 with captured_stdout() as s:
468 with check_warnings() as w:
469 warnings.simplefilter("always")
470 _make_tarball(base_name, 'dist', compress='compress')
471 finally:
472 os.chdir(old_dir)
473 tarball = base_name + '.tar.Z'
474 self.assertTrue(os.path.exists(tarball))
475 self.assertEquals(len(w.warnings), 1)
476
477 # same test with dry_run
478 os.remove(tarball)
479 old_dir = os.getcwd()
480 os.chdir(tmpdir)
481 try:
482 with captured_stdout() as s:
483 with check_warnings() as w:
484 warnings.simplefilter("always")
485 _make_tarball(base_name, 'dist', compress='compress',
486 dry_run=True)
487 finally:
488 os.chdir(old_dir)
489 self.assertTrue(not os.path.exists(tarball))
490 self.assertEquals(len(w.warnings), 1)
491
492 @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()
501 base_name = os.path.join(tmpdir2, 'archive')
502 _make_zipfile(base_name, tmpdir)
503
504 # check if the compressed tarball was created
505 tarball = base_name + '.zip'
506
507
508 def test_make_archive(self):
509 tmpdir = self.mkdtemp()
510 base_name = os.path.join(tmpdir, 'archive')
511 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
512
513 @unittest.skipUnless(zlib, "Requires zlib")
514 def test_make_archive_owner_group(self):
515 # testing make_archive with owner and group, with various combinations
516 # this works even if there's not gid/uid support
517 if UID_GID_SUPPORT:
518 group = grp.getgrgid(0)[0]
519 owner = pwd.getpwuid(0)[0]
520 else:
521 group = owner = 'root'
522
523 base_dir, root_dir, base_name = self._create_files()
524 base_name = os.path.join(self.mkdtemp() , 'archive')
525 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
526 group=group)
527 self.assertTrue(os.path.exists(res))
528
529 res = make_archive(base_name, 'zip', root_dir, base_dir)
530 self.assertTrue(os.path.exists(res))
531
532 res = make_archive(base_name, 'tar', root_dir, base_dir,
533 owner=owner, group=group)
534 self.assertTrue(os.path.exists(res))
535
536 res = make_archive(base_name, 'tar', root_dir, base_dir,
537 owner='kjhkjhkjg', group='oihohoh')
538 self.assertTrue(os.path.exists(res))
539
540 @unittest.skipUnless(zlib, "Requires zlib")
541 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
542 def test_tarfile_root_owner(self):
543 tmpdir, tmpdir2, base_name = self._create_files()
544 old_dir = os.getcwd()
545 os.chdir(tmpdir)
546 group = grp.getgrgid(0)[0]
547 owner = pwd.getpwuid(0)[0]
548 try:
549 archive_name = _make_tarball(base_name, 'dist', compress=None,
550 owner=owner, group=group)
551 finally:
552 os.chdir(old_dir)
553
554 # check if the compressed tarball was created
555 self.assertTrue(os.path.exists(archive_name))
556
557 # now checks the rights
558 archive = tarfile.open(archive_name)
559 try:
560 for member in archive.getmembers():
561 self.assertEquals(member.uid, 0)
562 self.assertEquals(member.gid, 0)
563 finally:
564 archive.close()
565
566 def test_make_archive_cwd(self):
567 current_dir = os.getcwd()
568 def _breaks(*args, **kw):
569 raise RuntimeError()
570
571 register_archive_format('xxx', _breaks, [], 'xxx file')
572 try:
573 try:
574 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
575 except Exception:
576 pass
577 self.assertEquals(os.getcwd(), current_dir)
578 finally:
579 unregister_archive_format('xxx')
580
581 def test_register_archive_format(self):
582
583 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
584 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
585 1)
586 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
587 [(1, 2), (1, 2, 3)])
588
589 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
590 formats = [name for name, params in get_archive_formats()]
591 self.assertIn('xxx', formats)
592
593 unregister_archive_format('xxx')
594 formats = [name for name, params in get_archive_formats()]
595 self.assertNotIn('xxx', formats)
596
Christian Heimes9bd667a2008-01-20 15:14:11 +0000597
Christian Heimesada8c3b2008-03-18 18:26:33 +0000598class TestMove(unittest.TestCase):
599
600 def setUp(self):
601 filename = "foo"
602 self.src_dir = tempfile.mkdtemp()
603 self.dst_dir = tempfile.mkdtemp()
604 self.src_file = os.path.join(self.src_dir, filename)
605 self.dst_file = os.path.join(self.dst_dir, filename)
606 # Try to create a dir in the current directory, hoping that it is
607 # not located on the same filesystem as the system tmp dir.
608 try:
609 self.dir_other_fs = tempfile.mkdtemp(
610 dir=os.path.dirname(__file__))
611 self.file_other_fs = os.path.join(self.dir_other_fs,
612 filename)
613 except OSError:
614 self.dir_other_fs = None
615 with open(self.src_file, "wb") as f:
616 f.write(b"spam")
617
618 def tearDown(self):
619 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
620 try:
621 if d:
622 shutil.rmtree(d)
623 except:
624 pass
625
626 def _check_move_file(self, src, dst, real_dst):
627 contents = open(src, "rb").read()
628 shutil.move(src, dst)
629 self.assertEqual(contents, open(real_dst, "rb").read())
630 self.assertFalse(os.path.exists(src))
631
632 def _check_move_dir(self, src, dst, real_dst):
633 contents = sorted(os.listdir(src))
634 shutil.move(src, dst)
635 self.assertEqual(contents, sorted(os.listdir(real_dst)))
636 self.assertFalse(os.path.exists(src))
637
638 def test_move_file(self):
639 # Move a file to another location on the same filesystem.
640 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
641
642 def test_move_file_to_dir(self):
643 # Move a file inside an existing dir on the same filesystem.
644 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
645
646 def test_move_file_other_fs(self):
647 # Move a file to an existing dir on another filesystem.
648 if not self.dir_other_fs:
649 # skip
650 return
651 self._check_move_file(self.src_file, self.file_other_fs,
652 self.file_other_fs)
653
654 def test_move_file_to_dir_other_fs(self):
655 # Move a file to another location on another filesystem.
656 if not self.dir_other_fs:
657 # skip
658 return
659 self._check_move_file(self.src_file, self.dir_other_fs,
660 self.file_other_fs)
661
662 def test_move_dir(self):
663 # Move a dir to another location on the same filesystem.
664 dst_dir = tempfile.mktemp()
665 try:
666 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
667 finally:
668 try:
669 shutil.rmtree(dst_dir)
670 except:
671 pass
672
673 def test_move_dir_other_fs(self):
674 # Move a dir to another location on another filesystem.
675 if not self.dir_other_fs:
676 # skip
677 return
678 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
679 try:
680 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
681 finally:
682 try:
683 shutil.rmtree(dst_dir)
684 except:
685 pass
686
687 def test_move_dir_to_dir(self):
688 # Move a dir inside an existing dir on the same filesystem.
689 self._check_move_dir(self.src_dir, self.dst_dir,
690 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
691
692 def test_move_dir_to_dir_other_fs(self):
693 # Move a dir inside an existing dir on another filesystem.
694 if not self.dir_other_fs:
695 # skip
696 return
697 self._check_move_dir(self.src_dir, self.dir_other_fs,
698 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
699
700 def test_existing_file_inside_dest_dir(self):
701 # A file with the same name inside the destination dir already exists.
702 with open(self.dst_file, "wb"):
703 pass
704 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
705
706 def test_dont_move_dir_in_itself(self):
707 # Moving a dir inside itself raises an Error.
708 dst = os.path.join(self.src_dir, "bar")
709 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
710
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000711 def test_destinsrc_false_negative(self):
712 os.mkdir(TESTFN)
713 try:
714 for src, dst in [('srcdir', 'srcdir/dest')]:
715 src = os.path.join(TESTFN, src)
716 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000717 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000718 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000719 'dst (%s) is not in src (%s)' % (dst, src))
720 finally:
721 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000722
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000723 def test_destinsrc_false_positive(self):
724 os.mkdir(TESTFN)
725 try:
726 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
727 src = os.path.join(TESTFN, src)
728 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000729 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000730 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000731 'dst (%s) is in src (%s)' % (dst, src))
732 finally:
733 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000734
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000735def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000736 support.run_unittest(TestShutil, TestMove)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000737
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000738if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000739 test_main()