blob: 3faa95e27dd280a3017f23b575a43d2217085eaa [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:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000467 with captured_stdout() as s, check_warnings(quiet=False) as w:
468 _make_tarball(base_name, 'dist', compress='compress')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000469 finally:
470 os.chdir(old_dir)
471 tarball = base_name + '.tar.Z'
472 self.assertTrue(os.path.exists(tarball))
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000473 self.assertEqual(len(w.warnings), 1)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000474
475 # same test with dry_run
476 os.remove(tarball)
477 old_dir = os.getcwd()
478 os.chdir(tmpdir)
479 try:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000480 with captured_stdout() as s, check_warnings(quiet=False) as w:
481 _make_tarball(base_name, 'dist', compress='compress',
482 dry_run=True)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000483 finally:
484 os.chdir(old_dir)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000485 self.assertFalse(os.path.exists(tarball))
486 self.assertEqual(len(w.warnings), 1)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000487
488 @unittest.skipUnless(zlib, "Requires zlib")
489 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
490 def test_make_zipfile(self):
491 # creating something to tar
492 tmpdir = self.mkdtemp()
493 self.write_file([tmpdir, 'file1'], 'xxx')
494 self.write_file([tmpdir, 'file2'], 'xxx')
495
496 tmpdir2 = self.mkdtemp()
497 base_name = os.path.join(tmpdir2, 'archive')
498 _make_zipfile(base_name, tmpdir)
499
500 # check if the compressed tarball was created
501 tarball = base_name + '.zip'
502
503
504 def test_make_archive(self):
505 tmpdir = self.mkdtemp()
506 base_name = os.path.join(tmpdir, 'archive')
507 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
508
509 @unittest.skipUnless(zlib, "Requires zlib")
510 def test_make_archive_owner_group(self):
511 # testing make_archive with owner and group, with various combinations
512 # this works even if there's not gid/uid support
513 if UID_GID_SUPPORT:
514 group = grp.getgrgid(0)[0]
515 owner = pwd.getpwuid(0)[0]
516 else:
517 group = owner = 'root'
518
519 base_dir, root_dir, base_name = self._create_files()
520 base_name = os.path.join(self.mkdtemp() , 'archive')
521 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
522 group=group)
523 self.assertTrue(os.path.exists(res))
524
525 res = make_archive(base_name, 'zip', root_dir, base_dir)
526 self.assertTrue(os.path.exists(res))
527
528 res = make_archive(base_name, 'tar', root_dir, base_dir,
529 owner=owner, group=group)
530 self.assertTrue(os.path.exists(res))
531
532 res = make_archive(base_name, 'tar', root_dir, base_dir,
533 owner='kjhkjhkjg', group='oihohoh')
534 self.assertTrue(os.path.exists(res))
535
536 @unittest.skipUnless(zlib, "Requires zlib")
537 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
538 def test_tarfile_root_owner(self):
539 tmpdir, tmpdir2, base_name = self._create_files()
540 old_dir = os.getcwd()
541 os.chdir(tmpdir)
542 group = grp.getgrgid(0)[0]
543 owner = pwd.getpwuid(0)[0]
544 try:
545 archive_name = _make_tarball(base_name, 'dist', compress=None,
546 owner=owner, group=group)
547 finally:
548 os.chdir(old_dir)
549
550 # check if the compressed tarball was created
551 self.assertTrue(os.path.exists(archive_name))
552
553 # now checks the rights
554 archive = tarfile.open(archive_name)
555 try:
556 for member in archive.getmembers():
557 self.assertEquals(member.uid, 0)
558 self.assertEquals(member.gid, 0)
559 finally:
560 archive.close()
561
562 def test_make_archive_cwd(self):
563 current_dir = os.getcwd()
564 def _breaks(*args, **kw):
565 raise RuntimeError()
566
567 register_archive_format('xxx', _breaks, [], 'xxx file')
568 try:
569 try:
570 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
571 except Exception:
572 pass
573 self.assertEquals(os.getcwd(), current_dir)
574 finally:
575 unregister_archive_format('xxx')
576
577 def test_register_archive_format(self):
578
579 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
580 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
581 1)
582 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
583 [(1, 2), (1, 2, 3)])
584
585 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
586 formats = [name for name, params in get_archive_formats()]
587 self.assertIn('xxx', formats)
588
589 unregister_archive_format('xxx')
590 formats = [name for name, params in get_archive_formats()]
591 self.assertNotIn('xxx', formats)
592
Christian Heimes9bd667a2008-01-20 15:14:11 +0000593
Christian Heimesada8c3b2008-03-18 18:26:33 +0000594class TestMove(unittest.TestCase):
595
596 def setUp(self):
597 filename = "foo"
598 self.src_dir = tempfile.mkdtemp()
599 self.dst_dir = tempfile.mkdtemp()
600 self.src_file = os.path.join(self.src_dir, filename)
601 self.dst_file = os.path.join(self.dst_dir, filename)
602 # Try to create a dir in the current directory, hoping that it is
603 # not located on the same filesystem as the system tmp dir.
604 try:
605 self.dir_other_fs = tempfile.mkdtemp(
606 dir=os.path.dirname(__file__))
607 self.file_other_fs = os.path.join(self.dir_other_fs,
608 filename)
609 except OSError:
610 self.dir_other_fs = None
611 with open(self.src_file, "wb") as f:
612 f.write(b"spam")
613
614 def tearDown(self):
615 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
616 try:
617 if d:
618 shutil.rmtree(d)
619 except:
620 pass
621
622 def _check_move_file(self, src, dst, real_dst):
623 contents = open(src, "rb").read()
624 shutil.move(src, dst)
625 self.assertEqual(contents, open(real_dst, "rb").read())
626 self.assertFalse(os.path.exists(src))
627
628 def _check_move_dir(self, src, dst, real_dst):
629 contents = sorted(os.listdir(src))
630 shutil.move(src, dst)
631 self.assertEqual(contents, sorted(os.listdir(real_dst)))
632 self.assertFalse(os.path.exists(src))
633
634 def test_move_file(self):
635 # Move a file to another location on the same filesystem.
636 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
637
638 def test_move_file_to_dir(self):
639 # Move a file inside an existing dir on the same filesystem.
640 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
641
642 def test_move_file_other_fs(self):
643 # Move a file to an existing dir on another filesystem.
644 if not self.dir_other_fs:
645 # skip
646 return
647 self._check_move_file(self.src_file, self.file_other_fs,
648 self.file_other_fs)
649
650 def test_move_file_to_dir_other_fs(self):
651 # Move a file to another location on another filesystem.
652 if not self.dir_other_fs:
653 # skip
654 return
655 self._check_move_file(self.src_file, self.dir_other_fs,
656 self.file_other_fs)
657
658 def test_move_dir(self):
659 # Move a dir to another location on the same filesystem.
660 dst_dir = tempfile.mktemp()
661 try:
662 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
663 finally:
664 try:
665 shutil.rmtree(dst_dir)
666 except:
667 pass
668
669 def test_move_dir_other_fs(self):
670 # Move a dir to another location on another filesystem.
671 if not self.dir_other_fs:
672 # skip
673 return
674 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
675 try:
676 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
677 finally:
678 try:
679 shutil.rmtree(dst_dir)
680 except:
681 pass
682
683 def test_move_dir_to_dir(self):
684 # Move a dir inside an existing dir on the same filesystem.
685 self._check_move_dir(self.src_dir, self.dst_dir,
686 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
687
688 def test_move_dir_to_dir_other_fs(self):
689 # Move a dir inside an existing dir on another filesystem.
690 if not self.dir_other_fs:
691 # skip
692 return
693 self._check_move_dir(self.src_dir, self.dir_other_fs,
694 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
695
696 def test_existing_file_inside_dest_dir(self):
697 # A file with the same name inside the destination dir already exists.
698 with open(self.dst_file, "wb"):
699 pass
700 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
701
702 def test_dont_move_dir_in_itself(self):
703 # Moving a dir inside itself raises an Error.
704 dst = os.path.join(self.src_dir, "bar")
705 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
706
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000707 def test_destinsrc_false_negative(self):
708 os.mkdir(TESTFN)
709 try:
710 for src, dst in [('srcdir', 'srcdir/dest')]:
711 src = os.path.join(TESTFN, src)
712 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000713 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000714 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000715 'dst (%s) is not in src (%s)' % (dst, src))
716 finally:
717 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000718
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000719 def test_destinsrc_false_positive(self):
720 os.mkdir(TESTFN)
721 try:
722 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
723 src = os.path.join(TESTFN, src)
724 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000725 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000726 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000727 'dst (%s) is in src (%s)' % (dst, src))
728 finally:
729 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000730
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000731def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000732 support.run_unittest(TestShutil, TestMove)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000733
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000734if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000735 test_main()