blob: 9f4871bd23817acaa46476c54477d271f0c472cb [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é6ac91722010-04-28 17:51:36 +000016 get_archive_formats, Error, unpack_archive,
17 register_unpack_format, RegistryError,
18 unregister_unpack_format, get_unpack_formats)
Tarek Ziadé396fad72010-02-23 05:30:31 +000019import tarfile
20import warnings
21
22from test import support
23from test.support import TESTFN, check_warnings, captured_stdout
24
Tarek Ziadéffa155a2010-04-29 13:34:35 +000025try:
26 import bz2
27 BZ2_SUPPORTED = True
28except ImportError:
29 BZ2_SUPPORTED = False
30
Antoine Pitrou7fff0962009-05-01 21:09:44 +000031TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000032
Tarek Ziadé396fad72010-02-23 05:30:31 +000033try:
34 import grp
35 import pwd
36 UID_GID_SUPPORT = True
37except ImportError:
38 UID_GID_SUPPORT = False
39
40try:
41 import zlib
42except ImportError:
43 zlib = None
44
45try:
46 import zipfile
47 ZIP_SUPPORT = True
48except ImportError:
49 ZIP_SUPPORT = find_executable('zip')
50
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000051class TestShutil(unittest.TestCase):
Tarek Ziadé396fad72010-02-23 05:30:31 +000052
53 def setUp(self):
54 super(TestShutil, self).setUp()
55 self.tempdirs = []
56
57 def tearDown(self):
58 super(TestShutil, self).tearDown()
59 while self.tempdirs:
60 d = self.tempdirs.pop()
61 shutil.rmtree(d, os.name in ('nt', 'cygwin'))
62
63 def write_file(self, path, content='xxx'):
64 """Writes a file in the given path.
65
66
67 path can be a string or a sequence.
68 """
69 if isinstance(path, (list, tuple)):
70 path = os.path.join(*path)
71 f = open(path, 'w')
72 try:
73 f.write(content)
74 finally:
75 f.close()
76
77 def mkdtemp(self):
78 """Create a temporary directory that will be cleaned up.
79
80 Returns the path of the directory.
81 """
82 d = tempfile.mkdtemp()
83 self.tempdirs.append(d)
84 return d
Tarek Ziadé5340db32010-04-19 22:30:51 +000085
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000086 def test_rmtree_errors(self):
87 # filename is guaranteed not to exist
88 filename = tempfile.mktemp()
89 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000090
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000091 # See bug #1071513 for why we don't run this on cygwin
92 # and bug #1076467 for why we don't run this as root.
93 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000094 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000095 def test_on_error(self):
96 self.errorState = 0
97 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000098 self.childpath = os.path.join(TESTFN, 'a')
99 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000100 f.close()
Tim Peters4590c002004-11-01 02:40:52 +0000101 old_dir_mode = os.stat(TESTFN).st_mode
102 old_child_mode = os.stat(self.childpath).st_mode
103 # Make unwritable.
104 os.chmod(self.childpath, stat.S_IREAD)
105 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000106
107 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000108 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +0000109 self.assertEqual(self.errorState, 2,
110 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000111
Tim Peters4590c002004-11-01 02:40:52 +0000112 # Make writable again.
113 os.chmod(TESTFN, old_dir_mode)
114 os.chmod(self.childpath, old_child_mode)
115
116 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000117 shutil.rmtree(TESTFN)
118
119 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000120 # test_rmtree_errors deliberately runs rmtree
121 # on a directory that is chmod 400, which will fail.
122 # This function is run when shutil.rmtree fails.
123 # 99.9% of the time it initially fails to remove
124 # a file in the directory, so the first time through
125 # func is os.remove.
126 # However, some Linux machines running ZFS on
127 # FUSE experienced a failure earlier in the process
128 # at os.listdir. The first failure may legally
129 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000130 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000131 if func is os.remove:
132 self.assertEqual(arg, self.childpath)
133 else:
134 self.assertIs(func, os.listdir,
135 "func must be either os.remove or os.listdir")
136 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000137 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000138 self.errorState = 1
139 else:
140 self.assertEqual(func, os.rmdir)
141 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000142 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +0000143 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000144
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +0000145 def test_rmtree_dont_delete_file(self):
146 # When called on a file instead of a directory, don't delete it.
147 handle, path = tempfile.mkstemp()
148 os.fdopen(handle).close()
149 self.assertRaises(OSError, shutil.rmtree, path)
150 os.remove(path)
151
Tarek Ziadé5340db32010-04-19 22:30:51 +0000152 def _write_data(self, path, data):
153 f = open(path, "w")
154 f.write(data)
155 f.close()
156
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157 def test_copytree_simple(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158
159 def read_data(path):
160 f = open(path)
161 data = f.read()
162 f.close()
163 return data
164
165 src_dir = tempfile.mkdtemp()
166 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000167 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000168 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000169 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000170
171 try:
172 shutil.copytree(src_dir, dst_dir)
173 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
174 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
175 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
176 'test.txt')))
177 actual = read_data(os.path.join(dst_dir, 'test.txt'))
178 self.assertEqual(actual, '123')
179 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
180 self.assertEqual(actual, '456')
181 finally:
182 for path in (
183 os.path.join(src_dir, 'test.txt'),
184 os.path.join(dst_dir, 'test.txt'),
185 os.path.join(src_dir, 'test_dir', 'test.txt'),
186 os.path.join(dst_dir, 'test_dir', 'test.txt'),
187 ):
188 if os.path.exists(path):
189 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000190 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000191 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000192 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000194 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000195
Georg Brandl2ee470f2008-07-16 12:55:28 +0000196 def test_copytree_with_exclude(self):
197
Georg Brandl2ee470f2008-07-16 12:55:28 +0000198 def read_data(path):
199 f = open(path)
200 data = f.read()
201 f.close()
202 return data
203
204 # creating data
205 join = os.path.join
206 exists = os.path.exists
207 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000208 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000209 dst_dir = join(tempfile.mkdtemp(), 'destination')
Tarek Ziadé5340db32010-04-19 22:30:51 +0000210 self._write_data(join(src_dir, 'test.txt'), '123')
211 self._write_data(join(src_dir, 'test.tmp'), '123')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000212 os.mkdir(join(src_dir, 'test_dir'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000213 self._write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000214 os.mkdir(join(src_dir, 'test_dir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000215 self._write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000216 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
217 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
Tarek Ziadé5340db32010-04-19 22:30:51 +0000218 self._write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'),
219 '456')
220 self._write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'),
221 '456')
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000222
223
224 # testing glob-like patterns
225 try:
226 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
227 shutil.copytree(src_dir, dst_dir, ignore=patterns)
228 # checking the result: some elements should not be copied
229 self.assertTrue(exists(join(dst_dir, 'test.txt')))
230 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
231 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
232 finally:
233 if os.path.exists(dst_dir):
234 shutil.rmtree(dst_dir)
235 try:
236 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
237 shutil.copytree(src_dir, dst_dir, ignore=patterns)
238 # checking the result: some elements should not be copied
239 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
240 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
241 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
242 finally:
243 if os.path.exists(dst_dir):
244 shutil.rmtree(dst_dir)
245
246 # testing callable-style
247 try:
248 def _filter(src, names):
249 res = []
250 for name in names:
251 path = os.path.join(src, name)
252
253 if (os.path.isdir(path) and
254 path.split()[-1] == 'subdir'):
255 res.append(name)
256 elif os.path.splitext(path)[-1] in ('.py'):
257 res.append(name)
258 return res
259
260 shutil.copytree(src_dir, dst_dir, ignore=_filter)
261
262 # checking the result: some elements should not be copied
263 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
264 'test.py')))
265 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
266
267 finally:
268 if os.path.exists(dst_dir):
269 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000270 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000271 shutil.rmtree(src_dir)
272 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000273
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000274 @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
275 def test_dont_copy_file_onto_link_to_itself(self):
276 # bug 851123.
277 os.mkdir(TESTFN)
278 src = os.path.join(TESTFN, 'cheese')
279 dst = os.path.join(TESTFN, 'shop')
280 try:
281 f = open(src, 'w')
282 f.write('cheddar')
283 f.close()
284
285 os.link(src, dst)
286 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
287 self.assertEqual(open(src,'r').read(), 'cheddar')
288 os.remove(dst)
289
290 # Using `src` here would mean we end up with a symlink pointing
291 # to TESTFN/TESTFN/cheese, while it should point at
292 # TESTFN/cheese.
293 os.symlink('cheese', dst)
294 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
295 self.assertEqual(open(src,'r').read(), 'cheddar')
296 os.remove(dst)
297 finally:
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000298 try:
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000299 shutil.rmtree(TESTFN)
300 except OSError:
301 pass
Johannes Gijsbers68128712004-08-14 13:57:08 +0000302
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000303 @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
Christian Heimes9bd667a2008-01-20 15:14:11 +0000304 def test_rmtree_on_symlink(self):
305 # bug 1669.
306 os.mkdir(TESTFN)
307 try:
308 src = os.path.join(TESTFN, 'cheese')
309 dst = os.path.join(TESTFN, 'shop')
310 os.mkdir(src)
311 os.symlink(src, dst)
312 self.assertRaises(OSError, shutil.rmtree, dst)
313 finally:
314 shutil.rmtree(TESTFN, ignore_errors=True)
315
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000316 @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo')
317 # Issue #3002: copyfile and copytree block indefinitely on named pipes
318 def test_copyfile_named_pipe(self):
319 os.mkfifo(TESTFN)
320 try:
321 self.assertRaises(shutil.SpecialFileError,
322 shutil.copyfile, TESTFN, TESTFN2)
323 self.assertRaises(shutil.SpecialFileError,
324 shutil.copyfile, __file__, TESTFN)
325 finally:
326 os.remove(TESTFN)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000327
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000328 @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo')
329 def test_copytree_named_pipe(self):
330 os.mkdir(TESTFN)
331 try:
332 subdir = os.path.join(TESTFN, "subdir")
333 os.mkdir(subdir)
334 pipe = os.path.join(subdir, "mypipe")
335 os.mkfifo(pipe)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000336 try:
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000337 shutil.copytree(TESTFN, TESTFN2)
338 except shutil.Error as e:
339 errors = e.args[0]
340 self.assertEqual(len(errors), 1)
341 src, dst, error_msg = errors[0]
342 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
343 else:
344 self.fail("shutil.Error should have been raised")
345 finally:
346 shutil.rmtree(TESTFN, ignore_errors=True)
347 shutil.rmtree(TESTFN2, ignore_errors=True)
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000348
Tarek Ziadé5340db32010-04-19 22:30:51 +0000349 def test_copytree_special_func(self):
350
351 src_dir = self.mkdtemp()
352 dst_dir = os.path.join(self.mkdtemp(), 'destination')
353 self._write_data(os.path.join(src_dir, 'test.txt'), '123')
354 os.mkdir(os.path.join(src_dir, 'test_dir'))
355 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
356
357 copied = []
358 def _copy(src, dst):
359 copied.append((src, dst))
360
361 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
362 self.assertEquals(len(copied), 2)
363
Tarek Ziadé51a6f722010-04-23 13:03:09 +0000364 @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
Tarek Ziadéfb437512010-04-20 08:57:33 +0000365 def test_copytree_dangling_symlinks(self):
366
367 # a dangling symlink raises an error at the end
368 src_dir = self.mkdtemp()
369 dst_dir = os.path.join(self.mkdtemp(), 'destination')
370 os.symlink('IDONTEXIST', os.path.join(src_dir, 'test.txt'))
371 os.mkdir(os.path.join(src_dir, 'test_dir'))
372 self._write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
373 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
374
375 # a dangling symlink is ignored with the proper flag
376 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
377 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
378 self.assertNotIn('test.txt', os.listdir(dst_dir))
379
380 # a dangling symlink is copied if symlinks=True
381 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
382 shutil.copytree(src_dir, dst_dir, symlinks=True)
383 self.assertIn('test.txt', os.listdir(dst_dir))
384
Tarek Ziadé396fad72010-02-23 05:30:31 +0000385 @unittest.skipUnless(zlib, "requires zlib")
386 def test_make_tarball(self):
387 # creating something to tar
388 tmpdir = self.mkdtemp()
389 self.write_file([tmpdir, 'file1'], 'xxx')
390 self.write_file([tmpdir, 'file2'], 'xxx')
391 os.mkdir(os.path.join(tmpdir, 'sub'))
392 self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
393
394 tmpdir2 = self.mkdtemp()
395 unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
396 "source and target should be on same drive")
397
398 base_name = os.path.join(tmpdir2, 'archive')
399
400 # working with relative paths to avoid tar warnings
401 old_dir = os.getcwd()
402 os.chdir(tmpdir)
403 try:
404 _make_tarball(splitdrive(base_name)[1], '.')
405 finally:
406 os.chdir(old_dir)
407
408 # check if the compressed tarball was created
409 tarball = base_name + '.tar.gz'
410 self.assertTrue(os.path.exists(tarball))
411
412 # trying an uncompressed one
413 base_name = os.path.join(tmpdir2, 'archive')
414 old_dir = os.getcwd()
415 os.chdir(tmpdir)
416 try:
417 _make_tarball(splitdrive(base_name)[1], '.', compress=None)
418 finally:
419 os.chdir(old_dir)
420 tarball = base_name + '.tar'
421 self.assertTrue(os.path.exists(tarball))
422
423 def _tarinfo(self, path):
424 tar = tarfile.open(path)
425 try:
426 names = tar.getnames()
427 names.sort()
428 return tuple(names)
429 finally:
430 tar.close()
431
432 def _create_files(self):
433 # creating something to tar
434 tmpdir = self.mkdtemp()
435 dist = os.path.join(tmpdir, 'dist')
436 os.mkdir(dist)
437 self.write_file([dist, 'file1'], 'xxx')
438 self.write_file([dist, 'file2'], 'xxx')
439 os.mkdir(os.path.join(dist, 'sub'))
440 self.write_file([dist, 'sub', 'file3'], 'xxx')
441 os.mkdir(os.path.join(dist, 'sub2'))
442 tmpdir2 = self.mkdtemp()
443 base_name = os.path.join(tmpdir2, 'archive')
444 return tmpdir, tmpdir2, base_name
445
446 @unittest.skipUnless(zlib, "Requires zlib")
447 @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
448 'Need the tar command to run')
449 def test_tarfile_vs_tar(self):
450 tmpdir, tmpdir2, base_name = self._create_files()
451 old_dir = os.getcwd()
452 os.chdir(tmpdir)
453 try:
454 _make_tarball(base_name, 'dist')
455 finally:
456 os.chdir(old_dir)
457
458 # check if the compressed tarball was created
459 tarball = base_name + '.tar.gz'
460 self.assertTrue(os.path.exists(tarball))
461
462 # now create another tarball using `tar`
463 tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
464 tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
465 gzip_cmd = ['gzip', '-f9', 'archive2.tar']
466 old_dir = os.getcwd()
467 os.chdir(tmpdir)
468 try:
469 with captured_stdout() as s:
470 spawn(tar_cmd)
471 spawn(gzip_cmd)
472 finally:
473 os.chdir(old_dir)
474
475 self.assertTrue(os.path.exists(tarball2))
476 # let's compare both tarballs
477 self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2))
478
479 # trying an uncompressed one
480 base_name = os.path.join(tmpdir2, 'archive')
481 old_dir = os.getcwd()
482 os.chdir(tmpdir)
483 try:
484 _make_tarball(base_name, 'dist', compress=None)
485 finally:
486 os.chdir(old_dir)
487 tarball = base_name + '.tar'
488 self.assertTrue(os.path.exists(tarball))
489
490 # now for a dry_run
491 base_name = os.path.join(tmpdir2, 'archive')
492 old_dir = os.getcwd()
493 os.chdir(tmpdir)
494 try:
495 _make_tarball(base_name, 'dist', compress=None, dry_run=True)
496 finally:
497 os.chdir(old_dir)
498 tarball = base_name + '.tar'
499 self.assertTrue(os.path.exists(tarball))
500
Tarek Ziadé396fad72010-02-23 05:30:31 +0000501 @unittest.skipUnless(zlib, "Requires zlib")
502 @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
503 def test_make_zipfile(self):
504 # creating something to tar
505 tmpdir = self.mkdtemp()
506 self.write_file([tmpdir, 'file1'], 'xxx')
507 self.write_file([tmpdir, 'file2'], 'xxx')
508
509 tmpdir2 = self.mkdtemp()
510 base_name = os.path.join(tmpdir2, 'archive')
511 _make_zipfile(base_name, tmpdir)
512
513 # check if the compressed tarball was created
514 tarball = base_name + '.zip'
515
516
517 def test_make_archive(self):
518 tmpdir = self.mkdtemp()
519 base_name = os.path.join(tmpdir, 'archive')
520 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
521
522 @unittest.skipUnless(zlib, "Requires zlib")
523 def test_make_archive_owner_group(self):
524 # testing make_archive with owner and group, with various combinations
525 # this works even if there's not gid/uid support
526 if UID_GID_SUPPORT:
527 group = grp.getgrgid(0)[0]
528 owner = pwd.getpwuid(0)[0]
529 else:
530 group = owner = 'root'
531
532 base_dir, root_dir, base_name = self._create_files()
533 base_name = os.path.join(self.mkdtemp() , 'archive')
534 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
535 group=group)
536 self.assertTrue(os.path.exists(res))
537
538 res = make_archive(base_name, 'zip', root_dir, base_dir)
539 self.assertTrue(os.path.exists(res))
540
541 res = make_archive(base_name, 'tar', root_dir, base_dir,
542 owner=owner, group=group)
543 self.assertTrue(os.path.exists(res))
544
545 res = make_archive(base_name, 'tar', root_dir, base_dir,
546 owner='kjhkjhkjg', group='oihohoh')
547 self.assertTrue(os.path.exists(res))
548
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000549
Tarek Ziadé396fad72010-02-23 05:30:31 +0000550 @unittest.skipUnless(zlib, "Requires zlib")
551 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
552 def test_tarfile_root_owner(self):
553 tmpdir, tmpdir2, base_name = self._create_files()
554 old_dir = os.getcwd()
555 os.chdir(tmpdir)
556 group = grp.getgrgid(0)[0]
557 owner = pwd.getpwuid(0)[0]
558 try:
559 archive_name = _make_tarball(base_name, 'dist', compress=None,
560 owner=owner, group=group)
561 finally:
562 os.chdir(old_dir)
563
564 # check if the compressed tarball was created
565 self.assertTrue(os.path.exists(archive_name))
566
567 # now checks the rights
568 archive = tarfile.open(archive_name)
569 try:
570 for member in archive.getmembers():
571 self.assertEquals(member.uid, 0)
572 self.assertEquals(member.gid, 0)
573 finally:
574 archive.close()
575
576 def test_make_archive_cwd(self):
577 current_dir = os.getcwd()
578 def _breaks(*args, **kw):
579 raise RuntimeError()
580
581 register_archive_format('xxx', _breaks, [], 'xxx file')
582 try:
583 try:
584 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
585 except Exception:
586 pass
587 self.assertEquals(os.getcwd(), current_dir)
588 finally:
589 unregister_archive_format('xxx')
590
591 def test_register_archive_format(self):
592
593 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
594 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
595 1)
596 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
597 [(1, 2), (1, 2, 3)])
598
599 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
600 formats = [name for name, params in get_archive_formats()]
601 self.assertIn('xxx', formats)
602
603 unregister_archive_format('xxx')
604 formats = [name for name, params in get_archive_formats()]
605 self.assertNotIn('xxx', formats)
606
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000607 def _compare_dirs(self, dir1, dir2):
608 # check that dir1 and dir2 are equivalent,
609 # return the diff
610 diff = []
611 for root, dirs, files in os.walk(dir1):
612 for file_ in files:
613 path = os.path.join(root, file_)
614 target_path = os.path.join(dir2, os.path.split(path)[-1])
615 if not os.path.exists(target_path):
616 diff.append(file_)
617 return diff
618
619 @unittest.skipUnless(zlib, "Requires zlib")
620 def test_unpack_archive(self):
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000621 formats = ['tar', 'gztar', 'zip']
622 if BZ2_SUPPORTED:
623 formats.append('bztar')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000624
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000625 for format in formats:
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000626 tmpdir = self.mkdtemp()
627 base_dir, root_dir, base_name = self._create_files()
628 tmpdir2 = self.mkdtemp()
629 filename = make_archive(base_name, format, root_dir, base_dir)
630
631 # let's try to unpack it now
632 unpack_archive(filename, tmpdir2)
633 diff = self._compare_dirs(tmpdir, tmpdir2)
634 self.assertEquals(diff, [])
635
636 def test_unpack_registery(self):
637
638 formats = get_unpack_formats()
639
640 def _boo(filename, extract_dir, extra):
641 self.assertEquals(extra, 1)
642 self.assertEquals(filename, 'stuff.boo')
643 self.assertEquals(extract_dir, 'xx')
644
645 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
646 unpack_archive('stuff.boo', 'xx')
647
648 # trying to register a .boo unpacker again
649 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
650 ['.boo'], _boo)
651
652 # should work now
653 unregister_unpack_format('Boo')
654 register_unpack_format('Boo2', ['.boo'], _boo)
655 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
656 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
657
658 # let's leave a clean state
659 unregister_unpack_format('Boo2')
660 self.assertEquals(get_unpack_formats(), formats)
661
Christian Heimes9bd667a2008-01-20 15:14:11 +0000662
Christian Heimesada8c3b2008-03-18 18:26:33 +0000663class TestMove(unittest.TestCase):
664
665 def setUp(self):
666 filename = "foo"
667 self.src_dir = tempfile.mkdtemp()
668 self.dst_dir = tempfile.mkdtemp()
669 self.src_file = os.path.join(self.src_dir, filename)
670 self.dst_file = os.path.join(self.dst_dir, filename)
671 # Try to create a dir in the current directory, hoping that it is
672 # not located on the same filesystem as the system tmp dir.
673 try:
674 self.dir_other_fs = tempfile.mkdtemp(
675 dir=os.path.dirname(__file__))
676 self.file_other_fs = os.path.join(self.dir_other_fs,
677 filename)
678 except OSError:
679 self.dir_other_fs = None
680 with open(self.src_file, "wb") as f:
681 f.write(b"spam")
682
683 def tearDown(self):
684 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
685 try:
686 if d:
687 shutil.rmtree(d)
688 except:
689 pass
690
691 def _check_move_file(self, src, dst, real_dst):
692 contents = open(src, "rb").read()
693 shutil.move(src, dst)
694 self.assertEqual(contents, open(real_dst, "rb").read())
695 self.assertFalse(os.path.exists(src))
696
697 def _check_move_dir(self, src, dst, real_dst):
698 contents = sorted(os.listdir(src))
699 shutil.move(src, dst)
700 self.assertEqual(contents, sorted(os.listdir(real_dst)))
701 self.assertFalse(os.path.exists(src))
702
703 def test_move_file(self):
704 # Move a file to another location on the same filesystem.
705 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
706
707 def test_move_file_to_dir(self):
708 # Move a file inside an existing dir on the same filesystem.
709 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
710
711 def test_move_file_other_fs(self):
712 # Move a file to an existing dir on another filesystem.
713 if not self.dir_other_fs:
714 # skip
715 return
716 self._check_move_file(self.src_file, self.file_other_fs,
717 self.file_other_fs)
718
719 def test_move_file_to_dir_other_fs(self):
720 # Move a file to another location on another filesystem.
721 if not self.dir_other_fs:
722 # skip
723 return
724 self._check_move_file(self.src_file, self.dir_other_fs,
725 self.file_other_fs)
726
727 def test_move_dir(self):
728 # Move a dir to another location on the same filesystem.
729 dst_dir = tempfile.mktemp()
730 try:
731 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
732 finally:
733 try:
734 shutil.rmtree(dst_dir)
735 except:
736 pass
737
738 def test_move_dir_other_fs(self):
739 # Move a dir to another location on another filesystem.
740 if not self.dir_other_fs:
741 # skip
742 return
743 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
744 try:
745 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
746 finally:
747 try:
748 shutil.rmtree(dst_dir)
749 except:
750 pass
751
752 def test_move_dir_to_dir(self):
753 # Move a dir inside an existing dir on the same filesystem.
754 self._check_move_dir(self.src_dir, self.dst_dir,
755 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
756
757 def test_move_dir_to_dir_other_fs(self):
758 # Move a dir inside an existing dir on another filesystem.
759 if not self.dir_other_fs:
760 # skip
761 return
762 self._check_move_dir(self.src_dir, self.dir_other_fs,
763 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
764
765 def test_existing_file_inside_dest_dir(self):
766 # A file with the same name inside the destination dir already exists.
767 with open(self.dst_file, "wb"):
768 pass
769 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
770
771 def test_dont_move_dir_in_itself(self):
772 # Moving a dir inside itself raises an Error.
773 dst = os.path.join(self.src_dir, "bar")
774 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
775
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000776 def test_destinsrc_false_negative(self):
777 os.mkdir(TESTFN)
778 try:
779 for src, dst in [('srcdir', 'srcdir/dest')]:
780 src = os.path.join(TESTFN, src)
781 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000782 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000783 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000784 'dst (%s) is not in src (%s)' % (dst, src))
785 finally:
786 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000787
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000788 def test_destinsrc_false_positive(self):
789 os.mkdir(TESTFN)
790 try:
791 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
792 src = os.path.join(TESTFN, src)
793 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000794 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000795 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000796 'dst (%s) is in src (%s)' % (dst, src))
797 finally:
798 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000799
Tarek Ziadé5340db32010-04-19 22:30:51 +0000800
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000801class TestCopyFile(unittest.TestCase):
802
803 _delete = False
804
805 class Faux(object):
806 _entered = False
807 _exited_with = None
808 _raised = False
809 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
810 self._raise_in_exit = raise_in_exit
811 self._suppress_at_exit = suppress_at_exit
812 def read(self, *args):
813 return ''
814 def __enter__(self):
815 self._entered = True
816 def __exit__(self, exc_type, exc_val, exc_tb):
817 self._exited_with = exc_type, exc_val, exc_tb
818 if self._raise_in_exit:
819 self._raised = True
820 raise IOError("Cannot close")
821 return self._suppress_at_exit
822
823 def tearDown(self):
824 if self._delete:
825 del shutil.open
826
827 def _set_shutil_open(self, func):
828 shutil.open = func
829 self._delete = True
830
831 def test_w_source_open_fails(self):
832 def _open(filename, mode='r'):
833 if filename == 'srcfile':
834 raise IOError('Cannot open "srcfile"')
835 assert 0 # shouldn't reach here.
836
837 self._set_shutil_open(_open)
838
839 self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
840
841 def test_w_dest_open_fails(self):
842
843 srcfile = self.Faux()
844
845 def _open(filename, mode='r'):
846 if filename == 'srcfile':
847 return srcfile
848 if filename == 'destfile':
849 raise IOError('Cannot open "destfile"')
850 assert 0 # shouldn't reach here.
851
852 self._set_shutil_open(_open)
853
854 shutil.copyfile('srcfile', 'destfile')
855 self.assertTrue(srcfile._entered)
856 self.assertTrue(srcfile._exited_with[0] is IOError)
857 self.assertEqual(srcfile._exited_with[1].args,
858 ('Cannot open "destfile"',))
859
860 def test_w_dest_close_fails(self):
861
862 srcfile = self.Faux()
863 destfile = self.Faux(True)
864
865 def _open(filename, mode='r'):
866 if filename == 'srcfile':
867 return srcfile
868 if filename == 'destfile':
869 return destfile
870 assert 0 # shouldn't reach here.
871
872 self._set_shutil_open(_open)
873
874 shutil.copyfile('srcfile', 'destfile')
875 self.assertTrue(srcfile._entered)
876 self.assertTrue(destfile._entered)
877 self.assertTrue(destfile._raised)
878 self.assertTrue(srcfile._exited_with[0] is IOError)
879 self.assertEqual(srcfile._exited_with[1].args,
880 ('Cannot close',))
881
882 def test_w_source_close_fails(self):
883
884 srcfile = self.Faux(True)
885 destfile = self.Faux()
886
887 def _open(filename, mode='r'):
888 if filename == 'srcfile':
889 return srcfile
890 if filename == 'destfile':
891 return destfile
892 assert 0 # shouldn't reach here.
893
894 self._set_shutil_open(_open)
895
896 self.assertRaises(IOError,
897 shutil.copyfile, 'srcfile', 'destfile')
898 self.assertTrue(srcfile._entered)
899 self.assertTrue(destfile._entered)
900 self.assertFalse(destfile._raised)
901 self.assertTrue(srcfile._exited_with[0] is None)
902 self.assertTrue(srcfile._raised)
903
904
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000905def test_main():
Tarek Ziadéae4d5c62010-05-05 22:27:31 +0000906 support.run_unittest(TestShutil, TestMove, TestCopyFile)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000907
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000908if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000909 test_main()