blob: 871541f20d5c5f8222e2b6d4a868abfb3dda8fb2 [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
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000010from os.path import splitdrive
11from distutils.spawn import find_executable, spawn
12from shutil import (_make_tarball, _make_zipfile, make_archive,
13 register_archive_format, unregister_archive_format,
14 get_archive_formats)
15import tarfile
16import warnings
17
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000018from test import test_support
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000019from test.test_support import TESTFN, check_warnings, captured_stdout
20
Antoine Pitrou1fc02312009-05-01 20:55:35 +000021TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000022
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000023try:
24 import grp
25 import pwd
26 UID_GID_SUPPORT = True
27except ImportError:
28 UID_GID_SUPPORT = False
29
30try:
31 import zlib
32except ImportError:
33 zlib = None
34
35try:
36 import zipfile
37 ZIP_SUPPORT = True
38except ImportError:
39 ZIP_SUPPORT = find_executable('zip')
40
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000041class TestShutil(unittest.TestCase):
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000042
43 def setUp(self):
44 super(TestShutil, self).setUp()
45 self.tempdirs = []
46
47 def tearDown(self):
48 super(TestShutil, self).tearDown()
49 while self.tempdirs:
50 d = self.tempdirs.pop()
51 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
52
53 def write_file(self, path, content='xxx'):
54 """Writes a file in the given path.
55
56
57 path can be a string or a sequence.
58 """
59 if isinstance(path, (list, tuple)):
60 path = os.path.join(*path)
61 f = open(path, 'w')
62 try:
63 f.write(content)
64 finally:
65 f.close()
66
67 def mkdtemp(self):
68 """Create a temporary directory that will be cleaned up.
69
70 Returns the path of the directory.
71 """
72 d = tempfile.mkdtemp()
73 self.tempdirs.append(d)
74 return d
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000075 def test_rmtree_errors(self):
76 # filename is guaranteed not to exist
77 filename = tempfile.mktemp()
78 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000079
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000080 # See bug #1071513 for why we don't run this on cygwin
81 # and bug #1076467 for why we don't run this as root.
82 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000083 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000084 def test_on_error(self):
85 self.errorState = 0
86 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000087 self.childpath = os.path.join(TESTFN, 'a')
88 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000089 f.close()
Tim Peters4590c002004-11-01 02:40:52 +000090 old_dir_mode = os.stat(TESTFN).st_mode
91 old_child_mode = os.stat(self.childpath).st_mode
92 # Make unwritable.
93 os.chmod(self.childpath, stat.S_IREAD)
94 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000095
96 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +000097 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000098 self.assertEqual(self.errorState, 2,
99 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000100
Tim Peters4590c002004-11-01 02:40:52 +0000101 # Make writable again.
102 os.chmod(TESTFN, old_dir_mode)
103 os.chmod(self.childpath, old_child_mode)
104
105 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000106 shutil.rmtree(TESTFN)
107
108 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson9c6fc512009-04-29 22:43:35 +0000109 # test_rmtree_errors deliberately runs rmtree
110 # on a directory that is chmod 400, which will fail.
111 # This function is run when shutil.rmtree fails.
112 # 99.9% of the time it initially fails to remove
113 # a file in the directory, so the first time through
114 # func is os.remove.
115 # However, some Linux machines running ZFS on
116 # FUSE experienced a failure earlier in the process
117 # at os.listdir. The first failure may legally
118 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000119 if self.errorState == 0:
Benjamin Peterson9c6fc512009-04-29 22:43:35 +0000120 if func is os.remove:
121 self.assertEqual(arg, self.childpath)
122 else:
123 self.assertIs(func, os.listdir,
124 "func must be either os.remove or os.listdir")
125 self.assertEqual(arg, TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000126 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000127 self.errorState = 1
128 else:
129 self.assertEqual(func, os.rmdir)
130 self.assertEqual(arg, TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000131 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000132 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000133
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000134 def test_rmtree_dont_delete_file(self):
135 # When called on a file instead of a directory, don't delete it.
136 handle, path = tempfile.mkstemp()
137 os.fdopen(handle).close()
138 self.assertRaises(OSError, shutil.rmtree, path)
139 os.remove(path)
140
Martin v. Löwis4e678382006-07-30 13:00:31 +0000141 def test_copytree_simple(self):
Tim Petersb2dd1a32006-08-10 03:01:26 +0000142 def write_data(path, data):
143 f = open(path, "w")
144 f.write(data)
145 f.close()
146
147 def read_data(path):
148 f = open(path)
149 data = f.read()
150 f.close()
151 return data
152
Martin v. Löwis4e678382006-07-30 13:00:31 +0000153 src_dir = tempfile.mkdtemp()
154 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tim Petersb2dd1a32006-08-10 03:01:26 +0000155
156 write_data(os.path.join(src_dir, 'test.txt'), '123')
157
Martin v. Löwis4e678382006-07-30 13:00:31 +0000158 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tim Petersb2dd1a32006-08-10 03:01:26 +0000159 write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
160
Martin v. Löwis4e678382006-07-30 13:00:31 +0000161 try:
162 shutil.copytree(src_dir, dst_dir)
163 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
164 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
Tim Petersb2dd1a32006-08-10 03:01:26 +0000165 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
166 'test.txt')))
167 actual = read_data(os.path.join(dst_dir, 'test.txt'))
168 self.assertEqual(actual, '123')
169 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
170 self.assertEqual(actual, '456')
Martin v. Löwis4e678382006-07-30 13:00:31 +0000171 finally:
Tim Petersb2dd1a32006-08-10 03:01:26 +0000172 for path in (
173 os.path.join(src_dir, 'test.txt'),
174 os.path.join(dst_dir, 'test.txt'),
175 os.path.join(src_dir, 'test_dir', 'test.txt'),
176 os.path.join(dst_dir, 'test_dir', 'test.txt'),
177 ):
178 if os.path.exists(path):
179 os.remove(path)
Christian Heimes547867e2007-11-20 03:21:02 +0000180 for path in (src_dir,
Antoine Pitrou4ac6b932009-11-04 00:50:26 +0000181 os.path.dirname(dst_dir)
Christian Heimes547867e2007-11-20 03:21:02 +0000182 ):
Tim Petersb2dd1a32006-08-10 03:01:26 +0000183 if os.path.exists(path):
Christian Heimes044d7092007-11-20 01:48:48 +0000184 shutil.rmtree(path)
Tim Peters64584522006-07-31 01:46:03 +0000185
Georg Brandle78fbcc2008-07-05 10:13:36 +0000186 def test_copytree_with_exclude(self):
187
188 def write_data(path, data):
189 f = open(path, "w")
190 f.write(data)
191 f.close()
192
193 def read_data(path):
194 f = open(path)
195 data = f.read()
196 f.close()
197 return data
198
199 # creating data
200 join = os.path.join
201 exists = os.path.exists
202 src_dir = tempfile.mkdtemp()
Georg Brandle78fbcc2008-07-05 10:13:36 +0000203 try:
Antoine Pitrou4ac6b932009-11-04 00:50:26 +0000204 dst_dir = join(tempfile.mkdtemp(), 'destination')
205 write_data(join(src_dir, 'test.txt'), '123')
206 write_data(join(src_dir, 'test.tmp'), '123')
207 os.mkdir(join(src_dir, 'test_dir'))
208 write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
209 os.mkdir(join(src_dir, 'test_dir2'))
210 write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
211 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
212 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
213 write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
214 write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
215
216
217 # testing glob-like patterns
218 try:
219 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
220 shutil.copytree(src_dir, dst_dir, ignore=patterns)
221 # checking the result: some elements should not be copied
222 self.assertTrue(exists(join(dst_dir, 'test.txt')))
223 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
224 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
225 finally:
226 if os.path.exists(dst_dir):
227 shutil.rmtree(dst_dir)
228 try:
229 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
230 shutil.copytree(src_dir, dst_dir, ignore=patterns)
231 # checking the result: some elements should not be copied
232 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
233 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
234 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
235 finally:
236 if os.path.exists(dst_dir):
237 shutil.rmtree(dst_dir)
238
239 # testing callable-style
240 try:
241 def _filter(src, names):
242 res = []
243 for name in names:
244 path = os.path.join(src, name)
245
246 if (os.path.isdir(path) and
247 path.split()[-1] == 'subdir'):
248 res.append(name)
249 elif os.path.splitext(path)[-1] in ('.py'):
250 res.append(name)
251 return res
252
253 shutil.copytree(src_dir, dst_dir, ignore=_filter)
254
255 # checking the result: some elements should not be copied
256 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
257 'test.py')))
258 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
259
260 finally:
261 if os.path.exists(dst_dir):
262 shutil.rmtree(dst_dir)
Georg Brandle78fbcc2008-07-05 10:13:36 +0000263 finally:
Antoine Pitrou4ac6b932009-11-04 00:50:26 +0000264 shutil.rmtree(src_dir)
265 shutil.rmtree(os.path.dirname(dst_dir))
Tim Peters64584522006-07-31 01:46:03 +0000266
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000267 if hasattr(os, "symlink"):
268 def test_dont_copy_file_onto_link_to_itself(self):
269 # bug 851123.
270 os.mkdir(TESTFN)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000271 src = os.path.join(TESTFN, 'cheese')
272 dst = os.path.join(TESTFN, 'shop')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000273 try:
Johannes Gijsbers68128712004-08-14 13:57:08 +0000274 f = open(src, 'w')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000275 f.write('cheddar')
276 f.close()
Johannes Gijsbers68128712004-08-14 13:57:08 +0000277
278 os.link(src, dst)
279 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
280 self.assertEqual(open(src,'r').read(), 'cheddar')
281 os.remove(dst)
282
283 # Using `src` here would mean we end up with a symlink pointing
284 # to TESTFN/TESTFN/cheese, while it should point at
285 # TESTFN/cheese.
286 os.symlink('cheese', dst)
287 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
288 self.assertEqual(open(src,'r').read(), 'cheddar')
289 os.remove(dst)
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000290 finally:
291 try:
292 shutil.rmtree(TESTFN)
293 except OSError:
294 pass
Brett Cannon1c3fa182004-06-19 21:11:35 +0000295
Georg Brandl52353982008-01-20 14:17:42 +0000296 def test_rmtree_on_symlink(self):
297 # bug 1669.
298 os.mkdir(TESTFN)
299 try:
300 src = os.path.join(TESTFN, 'cheese')
301 dst = os.path.join(TESTFN, 'shop')
302 os.mkdir(src)
303 os.symlink(src, dst)
304 self.assertRaises(OSError, shutil.rmtree, dst)
305 finally:
306 shutil.rmtree(TESTFN, ignore_errors=True)
307
Antoine Pitrou1fc02312009-05-01 20:55:35 +0000308 if hasattr(os, "mkfifo"):
309 # Issue #3002: copyfile and copytree block indefinitely on named pipes
310 def test_copyfile_named_pipe(self):
311 os.mkfifo(TESTFN)
312 try:
313 self.assertRaises(shutil.SpecialFileError,
314 shutil.copyfile, TESTFN, TESTFN2)
315 self.assertRaises(shutil.SpecialFileError,
316 shutil.copyfile, __file__, TESTFN)
317 finally:
318 os.remove(TESTFN)
319
320 def test_copytree_named_pipe(self):
321 os.mkdir(TESTFN)
322 try:
323 subdir = os.path.join(TESTFN, "subdir")
324 os.mkdir(subdir)
325 pipe = os.path.join(subdir, "mypipe")
326 os.mkfifo(pipe)
327 try:
328 shutil.copytree(TESTFN, TESTFN2)
329 except shutil.Error as e:
330 errors = e.args[0]
331 self.assertEqual(len(errors), 1)
332 src, dst, error_msg = errors[0]
333 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
334 else:
335 self.fail("shutil.Error should have been raised")
336 finally:
337 shutil.rmtree(TESTFN, ignore_errors=True)
338 shutil.rmtree(TESTFN2, ignore_errors=True)
339
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000340 @unittest.skipUnless(zlib, "requires zlib")
341 def test_make_tarball(self):
342 # creating something to tar
343 tmpdir = self.mkdtemp()
344 self.write_file([tmpdir, 'file1'], 'xxx')
345 self.write_file([tmpdir, 'file2'], 'xxx')
346 os.mkdir(os.path.join(tmpdir, 'sub'))
347 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
348
349 tmpdir2 = self.mkdtemp()
350 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
351 "source and target should be on same drive")
352
353 base_name = os.path.join(tmpdir2, 'archive')
354
355 # working with relative paths to avoid tar warnings
356 old_dir = os.getcwd()
357 os.chdir(tmpdir)
358 try:
359 _make_tarball(splitdrive(base_name)[1], '.')
360 finally:
361 os.chdir(old_dir)
362
363 # check if the compressed tarball was created
364 tarball = base_name + '.tar.gz'
365 self.assertTrue(os.path.exists(tarball))
366
367 # trying an uncompressed one
368 base_name = os.path.join(tmpdir2, 'archive')
369 old_dir = os.getcwd()
370 os.chdir(tmpdir)
371 try:
372 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
373 finally:
374 os.chdir(old_dir)
375 tarball = base_name + '.tar'
376 self.assertTrue(os.path.exists(tarball))
377
378 def _tarinfo(self, path):
379 tar = tarfile.open(path)
380 try:
381 names = tar.getnames()
382 names.sort()
383 return tuple(names)
384 finally:
385 tar.close()
386
387 def _create_files(self):
388 # creating something to tar
389 tmpdir = self.mkdtemp()
390 dist = os.path.join(tmpdir, 'dist')
391 os.mkdir(dist)
392 self.write_file([dist, 'file1'], 'xxx')
393 self.write_file([dist, 'file2'], 'xxx')
394 os.mkdir(os.path.join(dist, 'sub'))
395 self.write_file([dist, 'sub', 'file3'], 'xxx')
396 os.mkdir(os.path.join(dist, 'sub2'))
397 tmpdir2 = self.mkdtemp()
398 base_name = os.path.join(tmpdir2, 'archive')
399 return tmpdir, tmpdir2, base_name
400
401 @unittest.skipUnless(zlib, "Requires zlib")
402 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
403 'Need the tar command to run')
404 def test_tarfile_vs_tar(self):
405 tmpdir, tmpdir2, base_name = self._create_files()
406 old_dir = os.getcwd()
407 os.chdir(tmpdir)
408 try:
409 _make_tarball(base_name, 'dist')
410 finally:
411 os.chdir(old_dir)
412
413 # check if the compressed tarball was created
414 tarball = base_name + '.tar.gz'
415 self.assertTrue(os.path.exists(tarball))
416
417 # now create another tarball using `tar`
418 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
419 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
420 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
421 old_dir = os.getcwd()
422 os.chdir(tmpdir)
423 try:
424 with captured_stdout() as s:
425 spawn(tar_cmd)
426 spawn(gzip_cmd)
427 finally:
428 os.chdir(old_dir)
429
430 self.assertTrue(os.path.exists(tarball2))
431 # let's compare both tarballs
432 self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2))
433
434 # trying an uncompressed one
435 base_name = os.path.join(tmpdir2, 'archive')
436 old_dir = os.getcwd()
437 os.chdir(tmpdir)
438 try:
439 _make_tarball(base_name, 'dist', compress=None)
440 finally:
441 os.chdir(old_dir)
442 tarball = base_name + '.tar'
443 self.assertTrue(os.path.exists(tarball))
444
445 # now for a dry_run
446 base_name = os.path.join(tmpdir2, 'archive')
447 old_dir = os.getcwd()
448 os.chdir(tmpdir)
449 try:
450 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
451 finally:
452 os.chdir(old_dir)
453 tarball = base_name + '.tar'
454 self.assertTrue(os.path.exists(tarball))
455
456 @unittest.skipUnless(find_executable('compress'),
457 'The compress program is required')
458 def test_compress_deprecated(self):
459 tmpdir, tmpdir2, base_name = self._create_files()
460
461 # using compress and testing the PendingDeprecationWarning
462 old_dir = os.getcwd()
463 os.chdir(tmpdir)
464 try:
465 with captured_stdout() as s:
466 with check_warnings() as w:
467 warnings.simplefilter("always")
468 _make_tarball(base_name, 'dist', compress='compress')
469 finally:
470 os.chdir(old_dir)
471 tarball = base_name + '.tar.Z'
472 self.assertTrue(os.path.exists(tarball))
473 self.assertEquals(len(w.warnings), 1)
474
475 # same test with dry_run
476 os.remove(tarball)
477 old_dir = os.getcwd()
478 os.chdir(tmpdir)
479 try:
480 with captured_stdout() as s:
481 with check_warnings() as w:
482 warnings.simplefilter("always")
483 _make_tarball(base_name, 'dist', compress='compress',
484 dry_run=True)
485 finally:
486 os.chdir(old_dir)
487 self.assertTrue(not os.path.exists(tarball))
488 self.assertEquals(len(w.warnings), 1)
489
490 @unittest.skipUnless(zlib, "Requires zlib")
491 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
492 def test_make_zipfile(self):
493 # creating something to tar
494 tmpdir = self.mkdtemp()
495 self.write_file([tmpdir, 'file1'], 'xxx')
496 self.write_file([tmpdir, 'file2'], 'xxx')
497
498 tmpdir2 = self.mkdtemp()
499 base_name = os.path.join(tmpdir2, 'archive')
500 _make_zipfile(base_name, tmpdir)
501
502 # check if the compressed tarball was created
503 tarball = base_name + '.zip'
504
505
506 def test_make_archive(self):
507 tmpdir = self.mkdtemp()
508 base_name = os.path.join(tmpdir, 'archive')
509 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
510
511 @unittest.skipUnless(zlib, "Requires zlib")
512 def test_make_archive_owner_group(self):
513 # testing make_archive with owner and group, with various combinations
514 # this works even if there's not gid/uid support
515 if UID_GID_SUPPORT:
516 group = grp.getgrgid(0)[0]
517 owner = pwd.getpwuid(0)[0]
518 else:
519 group = owner = 'root'
520
521 base_dir, root_dir, base_name = self._create_files()
522 base_name = os.path.join(self.mkdtemp() , 'archive')
523 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
524 group=group)
525 self.assertTrue(os.path.exists(res))
526
527 res = make_archive(base_name, 'zip', root_dir, base_dir)
528 self.assertTrue(os.path.exists(res))
529
530 res = make_archive(base_name, 'tar', root_dir, base_dir,
531 owner=owner, group=group)
532 self.assertTrue(os.path.exists(res))
533
534 res = make_archive(base_name, 'tar', root_dir, base_dir,
535 owner='kjhkjhkjg', group='oihohoh')
536 self.assertTrue(os.path.exists(res))
537
538 @unittest.skipUnless(zlib, "Requires zlib")
539 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
540 def test_tarfile_root_owner(self):
541 tmpdir, tmpdir2, base_name = self._create_files()
542 old_dir = os.getcwd()
543 os.chdir(tmpdir)
544 group = grp.getgrgid(0)[0]
545 owner = pwd.getpwuid(0)[0]
546 try:
547 archive_name = _make_tarball(base_name, 'dist', compress=None,
548 owner=owner, group=group)
549 finally:
550 os.chdir(old_dir)
551
552 # check if the compressed tarball was created
553 self.assertTrue(os.path.exists(archive_name))
554
555 # now checks the rights
556 archive = tarfile.open(archive_name)
557 try:
558 for member in archive.getmembers():
559 self.assertEquals(member.uid, 0)
560 self.assertEquals(member.gid, 0)
561 finally:
562 archive.close()
563
564 def test_make_archive_cwd(self):
565 current_dir = os.getcwd()
566 def _breaks(*args, **kw):
567 raise RuntimeError()
568
569 register_archive_format('xxx', _breaks, [], 'xxx file')
570 try:
571 try:
572 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
573 except Exception:
574 pass
575 self.assertEquals(os.getcwd(), current_dir)
576 finally:
577 unregister_archive_format('xxx')
578
579 def test_register_archive_format(self):
580
581 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
582 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
583 1)
584 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
585 [(1, 2), (1, 2, 3)])
586
587 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
588 formats = [name for name, params in get_archive_formats()]
589 self.assertIn('xxx', formats)
590
591 unregister_archive_format('xxx')
592 formats = [name for name, params in get_archive_formats()]
593 self.assertNotIn('xxx', formats)
594
Georg Brandl52353982008-01-20 14:17:42 +0000595
Sean Reifscheider493894c2008-03-18 17:24:12 +0000596class TestMove(unittest.TestCase):
597
598 def setUp(self):
599 filename = "foo"
600 self.src_dir = tempfile.mkdtemp()
601 self.dst_dir = tempfile.mkdtemp()
602 self.src_file = os.path.join(self.src_dir, filename)
603 self.dst_file = os.path.join(self.dst_dir, filename)
604 # Try to create a dir in the current directory, hoping that it is
605 # not located on the same filesystem as the system tmp dir.
606 try:
607 self.dir_other_fs = tempfile.mkdtemp(
608 dir=os.path.dirname(__file__))
609 self.file_other_fs = os.path.join(self.dir_other_fs,
610 filename)
611 except OSError:
612 self.dir_other_fs = None
613 with open(self.src_file, "wb") as f:
614 f.write("spam")
615
616 def tearDown(self):
617 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
618 try:
619 if d:
620 shutil.rmtree(d)
621 except:
622 pass
623
624 def _check_move_file(self, src, dst, real_dst):
625 contents = open(src, "rb").read()
626 shutil.move(src, dst)
627 self.assertEqual(contents, open(real_dst, "rb").read())
628 self.assertFalse(os.path.exists(src))
629
630 def _check_move_dir(self, src, dst, real_dst):
631 contents = sorted(os.listdir(src))
632 shutil.move(src, dst)
633 self.assertEqual(contents, sorted(os.listdir(real_dst)))
634 self.assertFalse(os.path.exists(src))
635
636 def test_move_file(self):
637 # Move a file to another location on the same filesystem.
638 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
639
640 def test_move_file_to_dir(self):
641 # Move a file inside an existing dir on the same filesystem.
642 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
643
644 def test_move_file_other_fs(self):
645 # Move a file to an existing dir on another filesystem.
646 if not self.dir_other_fs:
647 # skip
648 return
649 self._check_move_file(self.src_file, self.file_other_fs,
650 self.file_other_fs)
651
652 def test_move_file_to_dir_other_fs(self):
653 # Move a file to another location on another filesystem.
654 if not self.dir_other_fs:
655 # skip
656 return
657 self._check_move_file(self.src_file, self.dir_other_fs,
658 self.file_other_fs)
659
660 def test_move_dir(self):
661 # Move a dir to another location on the same filesystem.
662 dst_dir = tempfile.mktemp()
663 try:
664 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
665 finally:
666 try:
667 shutil.rmtree(dst_dir)
668 except:
669 pass
670
671 def test_move_dir_other_fs(self):
672 # Move a dir to another location on another filesystem.
673 if not self.dir_other_fs:
674 # skip
675 return
676 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
677 try:
678 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
679 finally:
680 try:
681 shutil.rmtree(dst_dir)
682 except:
683 pass
684
685 def test_move_dir_to_dir(self):
686 # Move a dir inside an existing dir on the same filesystem.
687 self._check_move_dir(self.src_dir, self.dst_dir,
688 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
689
690 def test_move_dir_to_dir_other_fs(self):
691 # Move a dir inside an existing dir on another filesystem.
692 if not self.dir_other_fs:
693 # skip
694 return
695 self._check_move_dir(self.src_dir, self.dir_other_fs,
696 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
697
698 def test_existing_file_inside_dest_dir(self):
699 # A file with the same name inside the destination dir already exists.
700 with open(self.dst_file, "wb"):
701 pass
702 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
703
704 def test_dont_move_dir_in_itself(self):
705 # Moving a dir inside itself raises an Error.
706 dst = os.path.join(self.src_dir, "bar")
707 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
708
Antoine Pitrou707c5932009-01-29 20:19:34 +0000709 def test_destinsrc_false_negative(self):
710 os.mkdir(TESTFN)
711 try:
712 for src, dst in [('srcdir', 'srcdir/dest')]:
713 src = os.path.join(TESTFN, src)
714 dst = os.path.join(TESTFN, dst)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000715 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000716 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou707c5932009-01-29 20:19:34 +0000717 'dst (%s) is not in src (%s)' % (dst, src))
718 finally:
719 shutil.rmtree(TESTFN, ignore_errors=True)
Sean Reifscheider493894c2008-03-18 17:24:12 +0000720
Antoine Pitrou707c5932009-01-29 20:19:34 +0000721 def test_destinsrc_false_positive(self):
722 os.mkdir(TESTFN)
723 try:
724 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
725 src = os.path.join(TESTFN, src)
726 dst = os.path.join(TESTFN, dst)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000727 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000728 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou707c5932009-01-29 20:19:34 +0000729 'dst (%s) is in src (%s)' % (dst, src))
730 finally:
731 shutil.rmtree(TESTFN, ignore_errors=True)
Georg Brandl52353982008-01-20 14:17:42 +0000732
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000733def test_main():
Sean Reifscheider493894c2008-03-18 17:24:12 +0000734 test_support.run_unittest(TestShutil, TestMove)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000735
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000736if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000737 test_main()