blob: a747d6f7bf127454cc9b37aa68dff574cb572b2d [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
Antoine Pitrou7fff0962009-05-01 21:09:44 +000012TESTFN2 = TESTFN + "2"
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000013
14class TestShutil(unittest.TestCase):
15 def test_rmtree_errors(self):
16 # filename is guaranteed not to exist
17 filename = tempfile.mktemp()
18 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000019
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000020 # See bug #1071513 for why we don't run this on cygwin
21 # and bug #1076467 for why we don't run this as root.
22 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000023 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000024 def test_on_error(self):
25 self.errorState = 0
26 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000027 self.childpath = os.path.join(TESTFN, 'a')
28 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000029 f.close()
Tim Peters4590c002004-11-01 02:40:52 +000030 old_dir_mode = os.stat(TESTFN).st_mode
31 old_child_mode = os.stat(self.childpath).st_mode
32 # Make unwritable.
33 os.chmod(self.childpath, stat.S_IREAD)
34 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000035
36 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +000037 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000038 self.assertEqual(self.errorState, 2,
39 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000040
Tim Peters4590c002004-11-01 02:40:52 +000041 # Make writable again.
42 os.chmod(TESTFN, old_dir_mode)
43 os.chmod(self.childpath, old_child_mode)
44
45 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000046 shutil.rmtree(TESTFN)
47
48 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson25c95f12009-05-08 20:42:26 +000049 # test_rmtree_errors deliberately runs rmtree
50 # on a directory that is chmod 400, which will fail.
51 # This function is run when shutil.rmtree fails.
52 # 99.9% of the time it initially fails to remove
53 # a file in the directory, so the first time through
54 # func is os.remove.
55 # However, some Linux machines running ZFS on
56 # FUSE experienced a failure earlier in the process
57 # at os.listdir. The first failure may legally
58 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000059 if self.errorState == 0:
Benjamin Peterson25c95f12009-05-08 20:42:26 +000060 if func is os.remove:
61 self.assertEqual(arg, self.childpath)
62 else:
63 self.assertIs(func, os.listdir,
64 "func must be either os.remove or os.listdir")
65 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000066 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000067 self.errorState = 1
68 else:
69 self.assertEqual(func, os.rmdir)
70 self.assertEqual(arg, TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000071 self.assertTrue(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +000072 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000073
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +000074 def test_rmtree_dont_delete_file(self):
75 # When called on a file instead of a directory, don't delete it.
76 handle, path = tempfile.mkstemp()
77 os.fdopen(handle).close()
78 self.assertRaises(OSError, shutil.rmtree, path)
79 os.remove(path)
80
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081 def test_copytree_simple(self):
82 def write_data(path, data):
83 f = open(path, "w")
84 f.write(data)
85 f.close()
86
87 def read_data(path):
88 f = open(path)
89 data = f.read()
90 f.close()
91 return data
92
93 src_dir = tempfile.mkdtemp()
94 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
95
96 write_data(os.path.join(src_dir, 'test.txt'), '123')
97
98 os.mkdir(os.path.join(src_dir, 'test_dir'))
99 write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
100
101 try:
102 shutil.copytree(src_dir, dst_dir)
103 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
104 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
105 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
106 'test.txt')))
107 actual = read_data(os.path.join(dst_dir, 'test.txt'))
108 self.assertEqual(actual, '123')
109 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
110 self.assertEqual(actual, '456')
111 finally:
112 for path in (
113 os.path.join(src_dir, 'test.txt'),
114 os.path.join(dst_dir, 'test.txt'),
115 os.path.join(src_dir, 'test_dir', 'test.txt'),
116 os.path.join(dst_dir, 'test_dir', 'test.txt'),
117 ):
118 if os.path.exists(path):
119 os.remove(path)
Christian Heimese052dd82007-11-20 03:20:04 +0000120 for path in (src_dir,
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000121 os.path.dirname(dst_dir)
Christian Heimese052dd82007-11-20 03:20:04 +0000122 ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 if os.path.exists(path):
Christian Heimes94140152007-11-20 01:45:17 +0000124 shutil.rmtree(path)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125
Georg Brandl2ee470f2008-07-16 12:55:28 +0000126 def test_copytree_with_exclude(self):
127
128 def write_data(path, data):
129 f = open(path, "w")
130 f.write(data)
131 f.close()
132
133 def read_data(path):
134 f = open(path)
135 data = f.read()
136 f.close()
137 return data
138
139 # creating data
140 join = os.path.join
141 exists = os.path.exists
142 src_dir = tempfile.mkdtemp()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000143 try:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000144 dst_dir = join(tempfile.mkdtemp(), 'destination')
145 write_data(join(src_dir, 'test.txt'), '123')
146 write_data(join(src_dir, 'test.tmp'), '123')
147 os.mkdir(join(src_dir, 'test_dir'))
148 write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
149 os.mkdir(join(src_dir, 'test_dir2'))
150 write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
151 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
152 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
153 write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
154 write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
155
156
157 # testing glob-like patterns
158 try:
159 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
160 shutil.copytree(src_dir, dst_dir, ignore=patterns)
161 # checking the result: some elements should not be copied
162 self.assertTrue(exists(join(dst_dir, 'test.txt')))
163 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
164 self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
165 finally:
166 if os.path.exists(dst_dir):
167 shutil.rmtree(dst_dir)
168 try:
169 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
170 shutil.copytree(src_dir, dst_dir, ignore=patterns)
171 # checking the result: some elements should not be copied
172 self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
173 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
174 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
175 finally:
176 if os.path.exists(dst_dir):
177 shutil.rmtree(dst_dir)
178
179 # testing callable-style
180 try:
181 def _filter(src, names):
182 res = []
183 for name in names:
184 path = os.path.join(src, name)
185
186 if (os.path.isdir(path) and
187 path.split()[-1] == 'subdir'):
188 res.append(name)
189 elif os.path.splitext(path)[-1] in ('.py'):
190 res.append(name)
191 return res
192
193 shutil.copytree(src_dir, dst_dir, ignore=_filter)
194
195 # checking the result: some elements should not be copied
196 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
197 'test.py')))
198 self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
199
200 finally:
201 if os.path.exists(dst_dir):
202 shutil.rmtree(dst_dir)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000203 finally:
Antoine Pitrou97c81ef2009-11-04 00:57:15 +0000204 shutil.rmtree(src_dir)
205 shutil.rmtree(os.path.dirname(dst_dir))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000206
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000207 if hasattr(os, "symlink"):
208 def test_dont_copy_file_onto_link_to_itself(self):
209 # bug 851123.
210 os.mkdir(TESTFN)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000211 src = os.path.join(TESTFN, 'cheese')
212 dst = os.path.join(TESTFN, 'shop')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000213 try:
Johannes Gijsbers68128712004-08-14 13:57:08 +0000214 f = open(src, 'w')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000215 f.write('cheddar')
216 f.close()
Johannes Gijsbers68128712004-08-14 13:57:08 +0000217
218 os.link(src, dst)
219 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
220 self.assertEqual(open(src,'r').read(), 'cheddar')
221 os.remove(dst)
222
223 # Using `src` here would mean we end up with a symlink pointing
224 # to TESTFN/TESTFN/cheese, while it should point at
225 # TESTFN/cheese.
226 os.symlink('cheese', dst)
227 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
228 self.assertEqual(open(src,'r').read(), 'cheddar')
229 os.remove(dst)
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000230 finally:
231 try:
232 shutil.rmtree(TESTFN)
233 except OSError:
234 pass
Brett Cannon1c3fa182004-06-19 21:11:35 +0000235
Christian Heimes9bd667a2008-01-20 15:14:11 +0000236 def test_rmtree_on_symlink(self):
237 # bug 1669.
238 os.mkdir(TESTFN)
239 try:
240 src = os.path.join(TESTFN, 'cheese')
241 dst = os.path.join(TESTFN, 'shop')
242 os.mkdir(src)
243 os.symlink(src, dst)
244 self.assertRaises(OSError, shutil.rmtree, dst)
245 finally:
246 shutil.rmtree(TESTFN, ignore_errors=True)
247
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000248 if hasattr(os, "mkfifo"):
249 # Issue #3002: copyfile and copytree block indefinitely on named pipes
250 def test_copyfile_named_pipe(self):
251 os.mkfifo(TESTFN)
252 try:
253 self.assertRaises(shutil.SpecialFileError,
254 shutil.copyfile, TESTFN, TESTFN2)
255 self.assertRaises(shutil.SpecialFileError,
256 shutil.copyfile, __file__, TESTFN)
257 finally:
258 os.remove(TESTFN)
259
260 def test_copytree_named_pipe(self):
261 os.mkdir(TESTFN)
262 try:
263 subdir = os.path.join(TESTFN, "subdir")
264 os.mkdir(subdir)
265 pipe = os.path.join(subdir, "mypipe")
266 os.mkfifo(pipe)
267 try:
268 shutil.copytree(TESTFN, TESTFN2)
269 except shutil.Error as e:
270 errors = e.args[0]
271 self.assertEqual(len(errors), 1)
272 src, dst, error_msg = errors[0]
273 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
274 else:
275 self.fail("shutil.Error should have been raised")
276 finally:
277 shutil.rmtree(TESTFN, ignore_errors=True)
278 shutil.rmtree(TESTFN2, ignore_errors=True)
279
Christian Heimes9bd667a2008-01-20 15:14:11 +0000280
Christian Heimesada8c3b2008-03-18 18:26:33 +0000281class TestMove(unittest.TestCase):
282
283 def setUp(self):
284 filename = "foo"
285 self.src_dir = tempfile.mkdtemp()
286 self.dst_dir = tempfile.mkdtemp()
287 self.src_file = os.path.join(self.src_dir, filename)
288 self.dst_file = os.path.join(self.dst_dir, filename)
289 # Try to create a dir in the current directory, hoping that it is
290 # not located on the same filesystem as the system tmp dir.
291 try:
292 self.dir_other_fs = tempfile.mkdtemp(
293 dir=os.path.dirname(__file__))
294 self.file_other_fs = os.path.join(self.dir_other_fs,
295 filename)
296 except OSError:
297 self.dir_other_fs = None
298 with open(self.src_file, "wb") as f:
299 f.write(b"spam")
300
301 def tearDown(self):
302 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
303 try:
304 if d:
305 shutil.rmtree(d)
306 except:
307 pass
308
309 def _check_move_file(self, src, dst, real_dst):
310 contents = open(src, "rb").read()
311 shutil.move(src, dst)
312 self.assertEqual(contents, open(real_dst, "rb").read())
313 self.assertFalse(os.path.exists(src))
314
315 def _check_move_dir(self, src, dst, real_dst):
316 contents = sorted(os.listdir(src))
317 shutil.move(src, dst)
318 self.assertEqual(contents, sorted(os.listdir(real_dst)))
319 self.assertFalse(os.path.exists(src))
320
321 def test_move_file(self):
322 # Move a file to another location on the same filesystem.
323 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
324
325 def test_move_file_to_dir(self):
326 # Move a file inside an existing dir on the same filesystem.
327 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
328
329 def test_move_file_other_fs(self):
330 # Move a file to an existing dir on another filesystem.
331 if not self.dir_other_fs:
332 # skip
333 return
334 self._check_move_file(self.src_file, self.file_other_fs,
335 self.file_other_fs)
336
337 def test_move_file_to_dir_other_fs(self):
338 # Move a file to another location on another filesystem.
339 if not self.dir_other_fs:
340 # skip
341 return
342 self._check_move_file(self.src_file, self.dir_other_fs,
343 self.file_other_fs)
344
345 def test_move_dir(self):
346 # Move a dir to another location on the same filesystem.
347 dst_dir = tempfile.mktemp()
348 try:
349 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
350 finally:
351 try:
352 shutil.rmtree(dst_dir)
353 except:
354 pass
355
356 def test_move_dir_other_fs(self):
357 # Move a dir to another location on another filesystem.
358 if not self.dir_other_fs:
359 # skip
360 return
361 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
362 try:
363 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
364 finally:
365 try:
366 shutil.rmtree(dst_dir)
367 except:
368 pass
369
370 def test_move_dir_to_dir(self):
371 # Move a dir inside an existing dir on the same filesystem.
372 self._check_move_dir(self.src_dir, self.dst_dir,
373 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
374
375 def test_move_dir_to_dir_other_fs(self):
376 # Move a dir inside an existing dir on another filesystem.
377 if not self.dir_other_fs:
378 # skip
379 return
380 self._check_move_dir(self.src_dir, self.dir_other_fs,
381 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
382
383 def test_existing_file_inside_dest_dir(self):
384 # A file with the same name inside the destination dir already exists.
385 with open(self.dst_file, "wb"):
386 pass
387 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
388
389 def test_dont_move_dir_in_itself(self):
390 # Moving a dir inside itself raises an Error.
391 dst = os.path.join(self.src_dir, "bar")
392 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
393
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000394 def test_destinsrc_false_negative(self):
395 os.mkdir(TESTFN)
396 try:
397 for src, dst in [('srcdir', 'srcdir/dest')]:
398 src = os.path.join(TESTFN, src)
399 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000400 self.assertTrue(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000401 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000402 'dst (%s) is not in src (%s)' % (dst, src))
403 finally:
404 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimesada8c3b2008-03-18 18:26:33 +0000405
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000406 def test_destinsrc_false_positive(self):
407 os.mkdir(TESTFN)
408 try:
409 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
410 src = os.path.join(TESTFN, src)
411 dst = os.path.join(TESTFN, dst)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000412 self.assertFalse(shutil._destinsrc(src, dst),
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000413 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000414 'dst (%s) is in src (%s)' % (dst, src))
415 finally:
416 shutil.rmtree(TESTFN, ignore_errors=True)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000417
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000418def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000419 support.run_unittest(TestShutil, TestMove)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000420
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000421if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000422 test_main()