blob: 18164abb18868179ab04dccb72d0212be9ee9450 [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,
Tarek Ziadéfb437512010-04-20 08:57:33 +000016 get_archive_formats, Error)
Tarek Ziadé396fad72010-02-23 05:30:31 +000017import 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
Tarek Ziadé5340db32010-04-19 22:30:51 +000077
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000078 def test_rmtree_errors(self):
79 # filename is guaranteed not to exist
80 filename = tempfile.mktemp()
81 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000082
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000083 # See bug #1071513 for why we don't run this on cygwin
84 # and bug #1076467 for why we don't run this as root.
85 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000086 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000087 def test_on_error(self):
88 self.errorState = 0
89 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000090 self.childpath = os.path.join(TESTFN, 'a')
91 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000092 f.close()
Tim Peters4590c002004-11-01 02:40:52 +000093 old_dir_mode = os.stat(TESTFN).st_mode
94 old_child_mode = os.stat(self.childpath).st_mode
95 # Make unwritable.
96 os.chmod(self.childpath, stat.S_IREAD)
97 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000098
99 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000100 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000101 self.assertEqual(self.errorState, 2,
102 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000103
Tim Peters4590c002004-11-01 02:40:52 +0000104 # Make writable again.
105 os.chmod(TESTFN, old_dir_mode)
106 os.chmod(self.childpath, old_child_mode)
107
108 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000109 shutil.rmtree(TESTFN)
110
111 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000112 # test_rmtree_errors deliberately runs rmtree
113 # on a directory that is chmod 400, which will fail.
114 # This function is run when shutil.rmtree fails.
115 # 99.9% of the time it initially fails to remove
116 # a file in the directory, so the first time through
117 # func is os.remove.
118 # However, some Linux machines running ZFS on
119 # FUSE experienced a failure earlier in the process
120 # at os.listdir. The first failure may legally
121 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000122 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000123 if func is os.remove:
124 self.assertEqual(arg, self.childpath)
125 else:
126 self.assertIs(func, os.listdir,
127 "func must be either os.remove or os.listdir")
128 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000129 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000130 self.errorState = 1
131 else:
132 self.assertEqual(func, os.rmdir)
133 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000134 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000135 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000136
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000137 def test_rmtree_dont_delete_file(self):
138 # When called on a file instead of a directory, don't delete it.
139 handle, path = tempfile.mkstemp()
140 os.fdopen(handle).close()
141 self.assertRaises(OSError, shutil.rmtree, path)
142 os.remove(path)
143
Tarek Ziadé5340db32010-04-19 22:30:51 +0000144 def _write_data(self, path, data):
145 f = open(path, "w")
146 f.write(data)
147 f.close()
148
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000149 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150
151 def read_data(path):
152 f = open(path)
153 data = f.read()
154 f.close()
155 return data
156
157 src_dir = tempfile.mkdtemp()
158 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000159 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000161 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162
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
Georg Brandl2ee470f2008-07-16 12:55:28 +0000190 def read_data(path):
191 f = open(path)
192 data = f.read()
193 f.close()
194 return data
195
196 # creating data
197 join = os.path.join
198 exists = os.path.exists
199 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000200 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000201 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000202 self._write_data(join(src_dir, 'test.txt'), '123')
203 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000204 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000205 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000206 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000207 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000208 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
209 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000210 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
211 '456')
212 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
213 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000214
215
216 # testing glob-like patterns
217 try:
218 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
219 shutil.copytree(src_dir, dst_dir, ignore=patterns)
220 # checking the result: some elements should not be copied
221 self.assertTrue(exists(join(dst_dir, 'test.txt')))
222 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
223 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
224 finally:
225 if os.path.exists(dst_dir):
226 shutil.rmtree(dst_dir)
227 try:
228 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
229 shutil.copytree(src_dir, dst_dir, ignore=patterns)
230 # checking the result: some elements should not be copied
231 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
232 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
233 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
234 finally:
235 if os.path.exists(dst_dir):
236 shutil.rmtree(dst_dir)
237
238 # testing callable-style
239 try:
240 def _filter(src, names):
241 res = []
242 for name in names:
243 path = os.path.join(src, name)
244
245 if (os.path.isdir(path) and
246 path.split()[-1] == 'subdir'):
247 res.append(name)
248 elif os.path.splitext(path)[-1] in ('.py'):
249 res.append(name)
250 return res
251
252 shutil.copytree(src_dir, dst_dir, ignore=_filter)
253
254 # checking the result: some elements should not be copied
255 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
256 'test.py')))
257 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
258
259 finally:
260 if os.path.exists(dst_dir):
261 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000262 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000263 shutil.rmtree(src_dir)
264 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000265
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000266 @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
267 def test_dont_copy_file_onto_link_to_itself(self):
268 # bug 851123.
269 os.mkdir(TESTFN)
270 src = os.path.join(TESTFN, 'cheese')
271 dst = os.path.join(TESTFN, 'shop')
272 try:
273 f = open(src, 'w')
274 f.write('cheddar')
275 f.close()
276
277 os.link(src, dst)
278 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
279 self.assertEqual(open(src,'r').read(), 'cheddar')
280 os.remove(dst)
281
282 # Using `src` here would mean we end up with a symlink pointing
283 # to TESTFN/TESTFN/cheese, while it should point at
284 # TESTFN/cheese.
285 os.symlink('cheese', dst)
286 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
287 self.assertEqual(open(src,'r').read(), 'cheddar')
288 os.remove(dst)
289 finally:
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000290 try:
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000291 shutil.rmtree(TESTFN)
292 except OSError:
293 pass
Johannes Gijsbers68128712004-08-14 13:57:08 +0000294
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000295 @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
Christian Heimes9bd667a2008-01-20 15:14:11 +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
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000308 @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires 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)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000319
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000320 @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo')
321 def test_copytree_named_pipe(self):
322 os.mkdir(TESTFN)
323 try:
324 subdir = os.path.join(TESTFN, "subdir")
325 os.mkdir(subdir)
326 pipe = os.path.join(subdir, "mypipe")
327 os.mkfifo(pipe)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000328 try:
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000329 shutil.copytree(TESTFN, TESTFN2)
330 except shutil.Error as e:
331 errors = e.args[0]
332 self.assertEqual(len(errors), 1)
333 src, dst, error_msg = errors[0]
334 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
335 else:
336 self.fail("shutil.Error should have been raised")
337 finally:
338 shutil.rmtree(TESTFN, ignore_errors=True)
339 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000340
Tarek Ziadé5340db32010-04-19 22:30:51 +0000341 def test_copytree_special_func(self):
342
343 src_dir = self.mkdtemp()
344 dst_dir = os.path.join(self.mkdtemp(), 'destination')
345 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
346 os.mkdir(os.path.join(src_dir, 'test_dir'))
347 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
348
349 copied = []
350 def _copy(src, dst):
351 copied.append((src, dst))
352
353 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
354 self.assertEquals(len(copied), 2)
355
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000356 @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
Tarek Ziadéfb437512010-04-20 08:57:33 +0000357 def test_copytree_dangling_symlinks(self):
358
359 # a dangling symlink raises an error at the end
360 src_dir = self.mkdtemp()
361 dst_dir = os.path.join(self.mkdtemp(), 'destination')
362 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
363 os.mkdir(os.path.join(src_dir, 'test_dir'))
364 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
365 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
366
367 # a dangling symlink is ignored with the proper flag
368 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
369 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
370 self.assertNotIn('test.txt', os.listdir(dst_dir))
371
372 # a dangling symlink is copied if symlinks=True
373 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
374 shutil.copytree(src_dir, dst_dir, symlinks=True)
375 self.assertIn('test.txt', os.listdir(dst_dir))
376
Tarek Ziadé396fad72010-02-23 05:30:31 +0000377 @unittest.skipUnless(zlib, "requires zlib")
378 def test_make_tarball(self):
379 # creating something to tar
380 tmpdir = self.mkdtemp()
381 self.write_file([tmpdir, 'file1'], 'xxx')
382 self.write_file([tmpdir, 'file2'], 'xxx')
383 os.mkdir(os.path.join(tmpdir, 'sub'))
384 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
385
386 tmpdir2 = self.mkdtemp()
387 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
388 "source and target should be on same drive")
389
390 base_name = os.path.join(tmpdir2, 'archive')
391
392 # working with relative paths to avoid tar warnings
393 old_dir = os.getcwd()
394 os.chdir(tmpdir)
395 try:
396 _make_tarball(splitdrive(base_name)[1], '.')
397 finally:
398 os.chdir(old_dir)
399
400 # check if the compressed tarball was created
401 tarball = base_name + '.tar.gz'
402 self.assertTrue(os.path.exists(tarball))
403
404 # trying an uncompressed one
405 base_name = os.path.join(tmpdir2, 'archive')
406 old_dir = os.getcwd()
407 os.chdir(tmpdir)
408 try:
409 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
410 finally:
411 os.chdir(old_dir)
412 tarball = base_name + '.tar'
413 self.assertTrue(os.path.exists(tarball))
414
415 def _tarinfo(self, path):
416 tar = tarfile.open(path)
417 try:
418 names = tar.getnames()
419 names.sort()
420 return tuple(names)
421 finally:
422 tar.close()
423
424 def _create_files(self):
425 # creating something to tar
426 tmpdir = self.mkdtemp()
427 dist = os.path.join(tmpdir, 'dist')
428 os.mkdir(dist)
429 self.write_file([dist, 'file1'], 'xxx')
430 self.write_file([dist, 'file2'], 'xxx')
431 os.mkdir(os.path.join(dist, 'sub'))
432 self.write_file([dist, 'sub', 'file3'], 'xxx')
433 os.mkdir(os.path.join(dist, 'sub2'))
434 tmpdir2 = self.mkdtemp()
435 base_name = os.path.join(tmpdir2, 'archive')
436 return tmpdir, tmpdir2, base_name
437
438 @unittest.skipUnless(zlib, "Requires zlib")
439 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
440 'Need the tar command to run')
441 def test_tarfile_vs_tar(self):
442 tmpdir, tmpdir2, base_name = self._create_files()
443 old_dir = os.getcwd()
444 os.chdir(tmpdir)
445 try:
446 _make_tarball(base_name, 'dist')
447 finally:
448 os.chdir(old_dir)
449
450 # check if the compressed tarball was created
451 tarball = base_name + '.tar.gz'
452 self.assertTrue(os.path.exists(tarball))
453
454 # now create another tarball using `tar`
455 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
456 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
457 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
458 old_dir = os.getcwd()
459 os.chdir(tmpdir)
460 try:
461 with captured_stdout() as s:
462 spawn(tar_cmd)
463 spawn(gzip_cmd)
464 finally:
465 os.chdir(old_dir)
466
467 self.assertTrue(os.path.exists(tarball2))
468 # let's compare both tarballs
469 self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2))
470
471 # trying an uncompressed one
472 base_name = os.path.join(tmpdir2, 'archive')
473 old_dir = os.getcwd()
474 os.chdir(tmpdir)
475 try:
476 _make_tarball(base_name, 'dist', compress=None)
477 finally:
478 os.chdir(old_dir)
479 tarball = base_name + '.tar'
480 self.assertTrue(os.path.exists(tarball))
481
482 # now for a dry_run
483 base_name = os.path.join(tmpdir2, 'archive')
484 old_dir = os.getcwd()
485 os.chdir(tmpdir)
486 try:
487 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
488 finally:
489 os.chdir(old_dir)
490 tarball = base_name + '.tar'
491 self.assertTrue(os.path.exists(tarball))
492
Tarek Ziadé396fad72010-02-23 05:30:31 +0000493 @unittest.skipUnless(zlib, "Requires zlib")
494 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
495 def test_make_zipfile(self):
496 # creating something to tar
497 tmpdir = self.mkdtemp()
498 self.write_file([tmpdir, 'file1'], 'xxx')
499 self.write_file([tmpdir, 'file2'], 'xxx')
500
501 tmpdir2 = self.mkdtemp()
502 base_name = os.path.join(tmpdir2, 'archive')
503 _make_zipfile(base_name, tmpdir)
504
505 # check if the compressed tarball was created
506 tarball = base_name + '.zip'
507
508
509 def test_make_archive(self):
510 tmpdir = self.mkdtemp()
511 base_name = os.path.join(tmpdir, 'archive')
512 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
513
514 @unittest.skipUnless(zlib, "Requires zlib")
515 def test_make_archive_owner_group(self):
516 # testing make_archive with owner and group, with various combinations
517 # this works even if there's not gid/uid support
518 if UID_GID_SUPPORT:
519 group = grp.getgrgid(0)[0]
520 owner = pwd.getpwuid(0)[0]
521 else:
522 group = owner = 'root'
523
524 base_dir, root_dir, base_name = self._create_files()
525 base_name = os.path.join(self.mkdtemp() , 'archive')
526 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
527 group=group)
528 self.assertTrue(os.path.exists(res))
529
530 res = make_archive(base_name, 'zip', root_dir, base_dir)
531 self.assertTrue(os.path.exists(res))
532
533 res = make_archive(base_name, 'tar', root_dir, base_dir,
534 owner=owner, group=group)
535 self.assertTrue(os.path.exists(res))
536
537 res = make_archive(base_name, 'tar', root_dir, base_dir,
538 owner='kjhkjhkjg', group='oihohoh')
539 self.assertTrue(os.path.exists(res))
540
541 @unittest.skipUnless(zlib, "Requires zlib")
542 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
543 def test_tarfile_root_owner(self):
544 tmpdir, tmpdir2, base_name = self._create_files()
545 old_dir = os.getcwd()
546 os.chdir(tmpdir)
547 group = grp.getgrgid(0)[0]
548 owner = pwd.getpwuid(0)[0]
549 try:
550 archive_name = _make_tarball(base_name, 'dist', compress=None,
551 owner=owner, group=group)
552 finally:
553 os.chdir(old_dir)
554
555 # check if the compressed tarball was created
556 self.assertTrue(os.path.exists(archive_name))
557
558 # now checks the rights
559 archive = tarfile.open(archive_name)
560 try:
561 for member in archive.getmembers():
562 self.assertEquals(member.uid, 0)
563 self.assertEquals(member.gid, 0)
564 finally:
565 archive.close()
566
567 def test_make_archive_cwd(self):
568 current_dir = os.getcwd()
569 def _breaks(*args, **kw):
570 raise RuntimeError()
571
572 register_archive_format('xxx', _breaks, [], 'xxx file')
573 try:
574 try:
575 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
576 except Exception:
577 pass
578 self.assertEquals(os.getcwd(), current_dir)
579 finally:
580 unregister_archive_format('xxx')
581
582 def test_register_archive_format(self):
583
584 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
585 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
586 1)
587 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
588 [(1, 2), (1, 2, 3)])
589
590 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
591 formats = [name for name, params in get_archive_formats()]
592 self.assertIn('xxx', formats)
593
594 unregister_archive_format('xxx')
595 formats = [name for name, params in get_archive_formats()]
596 self.assertNotIn('xxx', formats)
597
Christian Heimes9bd667a2008-01-20 15:14:11 +0000598
Christian Heimesada8c3b2008-03-18 18:26:33 +0000599class TestMove(unittest.TestCase):
600
601 def setUp(self):
602 filename = "foo"
603 self.src_dir = tempfile.mkdtemp()
604 self.dst_dir = tempfile.mkdtemp()
605 self.src_file = os.path.join(self.src_dir, filename)
606 self.dst_file = os.path.join(self.dst_dir, filename)
607 # Try to create a dir in the current directory, hoping that it is
608 # not located on the same filesystem as the system tmp dir.
609 try:
610 self.dir_other_fs = tempfile.mkdtemp(
611 dir=os.path.dirname(__file__))
612 self.file_other_fs = os.path.join(self.dir_other_fs,
613 filename)
614 except OSError:
615 self.dir_other_fs = None
616 with open(self.src_file, "wb") as f:
617 f.write(b"spam")
618
619 def tearDown(self):
620 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
621 try:
622 if d:
623 shutil.rmtree(d)
624 except:
625 pass
626
627 def _check_move_file(self, src, dst, real_dst):
628 contents = open(src, "rb").read()
629 shutil.move(src, dst)
630 self.assertEqual(contents, open(real_dst, "rb").read())
631 self.assertFalse(os.path.exists(src))
632
633 def _check_move_dir(self, src, dst, real_dst):
634 contents = sorted(os.listdir(src))
635 shutil.move(src, dst)
636 self.assertEqual(contents, sorted(os.listdir(real_dst)))
637 self.assertFalse(os.path.exists(src))
638
639 def test_move_file(self):
640 # Move a file to another location on the same filesystem.
641 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
642
643 def test_move_file_to_dir(self):
644 # Move a file inside an existing dir on the same filesystem.
645 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
646
647 def test_move_file_other_fs(self):
648 # Move a file to an existing dir on another filesystem.
649 if not self.dir_other_fs:
650 # skip
651 return
652 self._check_move_file(self.src_file, self.file_other_fs,
653 self.file_other_fs)
654
655 def test_move_file_to_dir_other_fs(self):
656 # Move a file to another location on another filesystem.
657 if not self.dir_other_fs:
658 # skip
659 return
660 self._check_move_file(self.src_file, self.dir_other_fs,
661 self.file_other_fs)
662
663 def test_move_dir(self):
664 # Move a dir to another location on the same filesystem.
665 dst_dir = tempfile.mktemp()
666 try:
667 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
668 finally:
669 try:
670 shutil.rmtree(dst_dir)
671 except:
672 pass
673
674 def test_move_dir_other_fs(self):
675 # Move a dir to another location on another filesystem.
676 if not self.dir_other_fs:
677 # skip
678 return
679 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
680 try:
681 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
682 finally:
683 try:
684 shutil.rmtree(dst_dir)
685 except:
686 pass
687
688 def test_move_dir_to_dir(self):
689 # Move a dir inside an existing dir on the same filesystem.
690 self._check_move_dir(self.src_dir, self.dst_dir,
691 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
692
693 def test_move_dir_to_dir_other_fs(self):
694 # Move a dir inside an existing dir on another filesystem.
695 if not self.dir_other_fs:
696 # skip
697 return
698 self._check_move_dir(self.src_dir, self.dir_other_fs,
699 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
700
701 def test_existing_file_inside_dest_dir(self):
702 # A file with the same name inside the destination dir already exists.
703 with open(self.dst_file, "wb"):
704 pass
705 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
706
707 def test_dont_move_dir_in_itself(self):
708 # Moving a dir inside itself raises an Error.
709 dst = os.path.join(self.src_dir, "bar")
710 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
711
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000712 def test_destinsrc_false_negative(self):
713 os.mkdir(TESTFN)
714 try:
715 for src, dst in [('srcdir', 'srcdir/dest')]:
716 src = os.path.join(TESTFN, src)
717 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000718 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000719 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000720 'dst (%s) is not in src (%s)' % (dst, src))
721 finally:
722 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000723
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000724 def test_destinsrc_false_positive(self):
725 os.mkdir(TESTFN)
726 try:
727 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
728 src = os.path.join(TESTFN, src)
729 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000730 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000731 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000732 'dst (%s) is in src (%s)' % (dst, src))
733 finally:
734 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000735
Tarek Ziadé5340db32010-04-19 22:30:51 +0000736
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000737def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000738 support.run_unittest(TestShutil, TestMove)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000739
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000740if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000741 test_main()