blob: 169290da7bfa99416ec9898e10c7d1040cc5cc30 [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
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000010from test import test_support
Johannes Gijsbers46f14592004-08-14 13:30:02 +000011from test.test_support import TESTFN
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000012
13class TestShutil(unittest.TestCase):
14 def test_rmtree_errors(self):
15 # filename is guaranteed not to exist
16 filename = tempfile.mktemp()
17 self.assertRaises(OSError, shutil.rmtree, filename)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000018
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000019 # See bug #1071513 for why we don't run this on cygwin
20 # and bug #1076467 for why we don't run this as root.
21 if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
Johannes Gijsbers6b220b02004-12-12 15:52:57 +000022 and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000023 def test_on_error(self):
24 self.errorState = 0
25 os.mkdir(TESTFN)
Tim Peters4590c002004-11-01 02:40:52 +000026 self.childpath = os.path.join(TESTFN, 'a')
27 f = open(self.childpath, 'w')
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000028 f.close()
Tim Peters4590c002004-11-01 02:40:52 +000029 old_dir_mode = os.stat(TESTFN).st_mode
30 old_child_mode = os.stat(self.childpath).st_mode
31 # Make unwritable.
32 os.chmod(self.childpath, stat.S_IREAD)
33 os.chmod(TESTFN, stat.S_IREAD)
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000034
35 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +000036 # Test whether onerror has actually been called.
Johannes Gijsbersb8b09d02004-12-06 20:50:15 +000037 self.assertEqual(self.errorState, 2,
38 "Expected call to onerror function did not happen.")
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000039
Tim Peters4590c002004-11-01 02:40:52 +000040 # Make writable again.
41 os.chmod(TESTFN, old_dir_mode)
42 os.chmod(self.childpath, old_child_mode)
43
44 # Clean up.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000045 shutil.rmtree(TESTFN)
46
47 def check_args_to_onerror(self, func, arg, exc):
Benjamin Peterson9c6fc512009-04-29 22:43:35 +000048 # test_rmtree_errors deliberately runs rmtree
49 # on a directory that is chmod 400, which will fail.
50 # This function is run when shutil.rmtree fails.
51 # 99.9% of the time it initially fails to remove
52 # a file in the directory, so the first time through
53 # func is os.remove.
54 # However, some Linux machines running ZFS on
55 # FUSE experienced a failure earlier in the process
56 # at os.listdir. The first failure may legally
57 # be either.
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000058 if self.errorState == 0:
Benjamin Peterson9c6fc512009-04-29 22:43:35 +000059 if func is os.remove:
60 self.assertEqual(arg, self.childpath)
61 else:
62 self.assertIs(func, os.listdir,
63 "func must be either os.remove or os.listdir")
64 self.assertEqual(arg, TESTFN)
Martin v. Löwis8e0d4942006-05-04 10:08:42 +000065 self.failUnless(issubclass(exc[0], OSError))
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +000066 self.errorState = 1
67 else:
68 self.assertEqual(func, os.rmdir)
69 self.assertEqual(arg, TESTFN)
Martin v. Löwis8e0d4942006-05-04 10:08:42 +000070 self.failUnless(issubclass(exc[0], OSError))
Johannes Gijsbers8e6f2de2004-11-23 09:27:27 +000071 self.errorState = 2
Barry Warsaw7fc2cca2003-01-24 17:34:13 +000072
Johannes Gijsbersd60e92a2004-09-11 21:26:21 +000073 def test_rmtree_dont_delete_file(self):
74 # When called on a file instead of a directory, don't delete it.
75 handle, path = tempfile.mkstemp()
76 os.fdopen(handle).close()
77 self.assertRaises(OSError, shutil.rmtree, path)
78 os.remove(path)
79
Martin v. Löwis4e678382006-07-30 13:00:31 +000080 def test_copytree_simple(self):
Tim Petersb2dd1a32006-08-10 03:01:26 +000081 def write_data(path, data):
82 f = open(path, "w")
83 f.write(data)
84 f.close()
85
86 def read_data(path):
87 f = open(path)
88 data = f.read()
89 f.close()
90 return data
91
Martin v. Löwis4e678382006-07-30 13:00:31 +000092 src_dir = tempfile.mkdtemp()
93 dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
Tim Petersb2dd1a32006-08-10 03:01:26 +000094
95 write_data(os.path.join(src_dir, 'test.txt'), '123')
96
Martin v. Löwis4e678382006-07-30 13:00:31 +000097 os.mkdir(os.path.join(src_dir, 'test_dir'))
Tim Petersb2dd1a32006-08-10 03:01:26 +000098 write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
99
Martin v. Löwis4e678382006-07-30 13:00:31 +0000100 try:
101 shutil.copytree(src_dir, dst_dir)
102 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
103 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
Tim Petersb2dd1a32006-08-10 03:01:26 +0000104 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
105 'test.txt')))
106 actual = read_data(os.path.join(dst_dir, 'test.txt'))
107 self.assertEqual(actual, '123')
108 actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
109 self.assertEqual(actual, '456')
Martin v. Löwis4e678382006-07-30 13:00:31 +0000110 finally:
Tim Petersb2dd1a32006-08-10 03:01:26 +0000111 for path in (
112 os.path.join(src_dir, 'test.txt'),
113 os.path.join(dst_dir, 'test.txt'),
114 os.path.join(src_dir, 'test_dir', 'test.txt'),
115 os.path.join(dst_dir, 'test_dir', 'test.txt'),
116 ):
117 if os.path.exists(path):
118 os.remove(path)
Christian Heimes547867e2007-11-20 03:21:02 +0000119 for path in (src_dir,
120 os.path.abspath(os.path.join(dst_dir, os.path.pardir))
121 ):
Tim Petersb2dd1a32006-08-10 03:01:26 +0000122 if os.path.exists(path):
Christian Heimes044d7092007-11-20 01:48:48 +0000123 shutil.rmtree(path)
Tim Peters64584522006-07-31 01:46:03 +0000124
Georg Brandle78fbcc2008-07-05 10:13:36 +0000125 def test_copytree_with_exclude(self):
126
127 def write_data(path, data):
128 f = open(path, "w")
129 f.write(data)
130 f.close()
131
132 def read_data(path):
133 f = open(path)
134 data = f.read()
135 f.close()
136 return data
137
138 # creating data
139 join = os.path.join
140 exists = os.path.exists
141 src_dir = tempfile.mkdtemp()
142 dst_dir = join(tempfile.mkdtemp(), 'destination')
143 write_data(join(src_dir, 'test.txt'), '123')
144 write_data(join(src_dir, 'test.tmp'), '123')
145 os.mkdir(join(src_dir, 'test_dir'))
146 write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
147 os.mkdir(join(src_dir, 'test_dir2'))
148 write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
149 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
150 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
151 write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
152 write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
153
154
155 # testing glob-like patterns
156 try:
157 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
158 shutil.copytree(src_dir, dst_dir, ignore=patterns)
159 # checking the result: some elements should not be copied
160 self.assert_(exists(join(dst_dir, 'test.txt')))
161 self.assert_(not exists(join(dst_dir, 'test.tmp')))
162 self.assert_(not exists(join(dst_dir, 'test_dir2')))
163 finally:
164 if os.path.exists(dst_dir):
165 shutil.rmtree(dst_dir)
166 try:
167 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
168 shutil.copytree(src_dir, dst_dir, ignore=patterns)
169 # checking the result: some elements should not be copied
170 self.assert_(not exists(join(dst_dir, 'test.tmp')))
171 self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
172 self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir')))
173 finally:
174 if os.path.exists(dst_dir):
175 shutil.rmtree(dst_dir)
176
177 # testing callable-style
178 try:
179 def _filter(src, names):
180 res = []
181 for name in names:
182 path = os.path.join(src, name)
183
184 if (os.path.isdir(path) and
185 path.split()[-1] == 'subdir'):
186 res.append(name)
187 elif os.path.splitext(path)[-1] in ('.py'):
188 res.append(name)
189 return res
190
191 shutil.copytree(src_dir, dst_dir, ignore=_filter)
192
193 # checking the result: some elements should not be copied
194 self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir2',
195 'test.py')))
196 self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir')))
197
198 finally:
199 if os.path.exists(dst_dir):
200 shutil.rmtree(dst_dir)
Tim Peters64584522006-07-31 01:46:03 +0000201
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000202 if hasattr(os, "symlink"):
203 def test_dont_copy_file_onto_link_to_itself(self):
204 # bug 851123.
205 os.mkdir(TESTFN)
Johannes Gijsbers68128712004-08-14 13:57:08 +0000206 src = os.path.join(TESTFN, 'cheese')
207 dst = os.path.join(TESTFN, 'shop')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000208 try:
Johannes Gijsbers68128712004-08-14 13:57:08 +0000209 f = open(src, 'w')
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000210 f.write('cheddar')
211 f.close()
Johannes Gijsbers68128712004-08-14 13:57:08 +0000212
213 os.link(src, dst)
214 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
215 self.assertEqual(open(src,'r').read(), 'cheddar')
216 os.remove(dst)
217
218 # Using `src` here would mean we end up with a symlink pointing
219 # to TESTFN/TESTFN/cheese, while it should point at
220 # TESTFN/cheese.
221 os.symlink('cheese', dst)
222 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
223 self.assertEqual(open(src,'r').read(), 'cheddar')
224 os.remove(dst)
Johannes Gijsbers46f14592004-08-14 13:30:02 +0000225 finally:
226 try:
227 shutil.rmtree(TESTFN)
228 except OSError:
229 pass
Brett Cannon1c3fa182004-06-19 21:11:35 +0000230
Georg Brandl52353982008-01-20 14:17:42 +0000231 def test_rmtree_on_symlink(self):
232 # bug 1669.
233 os.mkdir(TESTFN)
234 try:
235 src = os.path.join(TESTFN, 'cheese')
236 dst = os.path.join(TESTFN, 'shop')
237 os.mkdir(src)
238 os.symlink(src, dst)
239 self.assertRaises(OSError, shutil.rmtree, dst)
240 finally:
241 shutil.rmtree(TESTFN, ignore_errors=True)
242
243
Sean Reifscheider493894c2008-03-18 17:24:12 +0000244class TestMove(unittest.TestCase):
245
246 def setUp(self):
247 filename = "foo"
248 self.src_dir = tempfile.mkdtemp()
249 self.dst_dir = tempfile.mkdtemp()
250 self.src_file = os.path.join(self.src_dir, filename)
251 self.dst_file = os.path.join(self.dst_dir, filename)
252 # Try to create a dir in the current directory, hoping that it is
253 # not located on the same filesystem as the system tmp dir.
254 try:
255 self.dir_other_fs = tempfile.mkdtemp(
256 dir=os.path.dirname(__file__))
257 self.file_other_fs = os.path.join(self.dir_other_fs,
258 filename)
259 except OSError:
260 self.dir_other_fs = None
261 with open(self.src_file, "wb") as f:
262 f.write("spam")
263
264 def tearDown(self):
265 for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
266 try:
267 if d:
268 shutil.rmtree(d)
269 except:
270 pass
271
272 def _check_move_file(self, src, dst, real_dst):
273 contents = open(src, "rb").read()
274 shutil.move(src, dst)
275 self.assertEqual(contents, open(real_dst, "rb").read())
276 self.assertFalse(os.path.exists(src))
277
278 def _check_move_dir(self, src, dst, real_dst):
279 contents = sorted(os.listdir(src))
280 shutil.move(src, dst)
281 self.assertEqual(contents, sorted(os.listdir(real_dst)))
282 self.assertFalse(os.path.exists(src))
283
284 def test_move_file(self):
285 # Move a file to another location on the same filesystem.
286 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
287
288 def test_move_file_to_dir(self):
289 # Move a file inside an existing dir on the same filesystem.
290 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
291
292 def test_move_file_other_fs(self):
293 # Move a file to an existing dir on another filesystem.
294 if not self.dir_other_fs:
295 # skip
296 return
297 self._check_move_file(self.src_file, self.file_other_fs,
298 self.file_other_fs)
299
300 def test_move_file_to_dir_other_fs(self):
301 # Move a file to another location on another filesystem.
302 if not self.dir_other_fs:
303 # skip
304 return
305 self._check_move_file(self.src_file, self.dir_other_fs,
306 self.file_other_fs)
307
308 def test_move_dir(self):
309 # Move a dir to another location on the same filesystem.
310 dst_dir = tempfile.mktemp()
311 try:
312 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
313 finally:
314 try:
315 shutil.rmtree(dst_dir)
316 except:
317 pass
318
319 def test_move_dir_other_fs(self):
320 # Move a dir to another location on another filesystem.
321 if not self.dir_other_fs:
322 # skip
323 return
324 dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
325 try:
326 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
327 finally:
328 try:
329 shutil.rmtree(dst_dir)
330 except:
331 pass
332
333 def test_move_dir_to_dir(self):
334 # Move a dir inside an existing dir on the same filesystem.
335 self._check_move_dir(self.src_dir, self.dst_dir,
336 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
337
338 def test_move_dir_to_dir_other_fs(self):
339 # Move a dir inside an existing dir on another filesystem.
340 if not self.dir_other_fs:
341 # skip
342 return
343 self._check_move_dir(self.src_dir, self.dir_other_fs,
344 os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
345
346 def test_existing_file_inside_dest_dir(self):
347 # A file with the same name inside the destination dir already exists.
348 with open(self.dst_file, "wb"):
349 pass
350 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
351
352 def test_dont_move_dir_in_itself(self):
353 # Moving a dir inside itself raises an Error.
354 dst = os.path.join(self.src_dir, "bar")
355 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
356
Antoine Pitrou707c5932009-01-29 20:19:34 +0000357 def test_destinsrc_false_negative(self):
358 os.mkdir(TESTFN)
359 try:
360 for src, dst in [('srcdir', 'srcdir/dest')]:
361 src = os.path.join(TESTFN, src)
362 dst = os.path.join(TESTFN, dst)
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000363 self.assert_(shutil._destinsrc(src, dst),
364 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou707c5932009-01-29 20:19:34 +0000365 'dst (%s) is not in src (%s)' % (dst, src))
366 finally:
367 shutil.rmtree(TESTFN, ignore_errors=True)
Sean Reifscheider493894c2008-03-18 17:24:12 +0000368
Antoine Pitrou707c5932009-01-29 20:19:34 +0000369 def test_destinsrc_false_positive(self):
370 os.mkdir(TESTFN)
371 try:
372 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
373 src = os.path.join(TESTFN, src)
374 dst = os.path.join(TESTFN, dst)
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000375 self.failIf(shutil._destinsrc(src, dst),
376 msg='_destinsrc() wrongly concluded that '
Antoine Pitrou707c5932009-01-29 20:19:34 +0000377 'dst (%s) is in src (%s)' % (dst, src))
378 finally:
379 shutil.rmtree(TESTFN, ignore_errors=True)
Georg Brandl52353982008-01-20 14:17:42 +0000380
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000381def test_main():
Sean Reifscheider493894c2008-03-18 17:24:12 +0000382 test_support.run_unittest(TestShutil, TestMove)
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000383
Barry Warsaw7fc2cca2003-01-24 17:34:13 +0000384if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000385 test_main()