Debian Codegraph @

Lib/test/test_shutil.py

raw
1 # Copyright (C) 2003 Python Software Foundation
2
3 import unittest
4 import unittest.mock
5 import shutil
6 import tempfile
7 import sys
8 import stat
9 import os
10 import os.path
11 import errno
12 import functools
13 import pathlib
14 import subprocess
15 import random
16 import string
17 import contextlib
18 import io
19 from shutil import (make_archive,
20 register_archive_format, unregister_archive_format,
21 get_archive_formats, Error, unpack_archive,
22 register_unpack_format, RegistryError,
23 unregister_unpack_format, get_unpack_formats,
24 SameFileError, _GiveupOnFastCopy)
25 import tarfile
26 import zipfile
27 try:
28 import posix
29 except ImportError:
30 posix = None
31
32 from test import support
33 from test.support import os_helper
34 from test.support.os_helper import TESTFN, FakePath
35 from test.support import warnings_helper
36
37 TESTFN2 = TESTFN + "2"
38 TESTFN_SRC = TESTFN + "_SRC"
39 TESTFN_DST = TESTFN + "_DST"
40 MACOS = sys.platform.startswith("darwin")
41 SOLARIS = sys.platform.startswith("sunos")
42 AIX = sys.platform[:3] == 'aix'
43 try:
44 import grp
45 import pwd
46 UID_GID_SUPPORT = True
47 except ImportError:
48 UID_GID_SUPPORT = False
49
50 try:
51 import _winapi
52 except ImportError:
53 _winapi = None
54
55 no_chdir = unittest.mock.patch('os.chdir',
56 side_effect=AssertionError("shouldn't call os.chdir()"))
57
58 def _fake_rename(*args, **kwargs):
59 # Pretend the destination path is on a different filesystem.
60 raise OSError(getattr(errno, 'EXDEV', 18), "Invalid cross-device link")
61
62 def mock_rename(func):
63 @functools.wraps(func)
64 def wrap(*args, **kwargs):
65 try:
66 builtin_rename = os.rename
67 os.rename = _fake_rename
68 return func(*args, **kwargs)
69 finally:
70 os.rename = builtin_rename
71 return wrap
72
73 def create_file(path, content=b''):
74 """Write *content* to a file located at *path*.
75
76 If *path* is a tuple instead of a string, os.path.join will be used to
77 make a path.
78 """
79 if isinstance(path, tuple):
80 path = os.path.join(*path)
81 if isinstance(content, str):
82 content = content.encode()
83 with open(path, 'xb') as fp:
84 fp.write(content)
85
86 def write_test_file(path, size):
87 """Create a test file with an arbitrary size and random text content."""
88 def chunks(total, step):
89 assert total >= step
90 while total > step:
91 yield step
92 total -= step
93 if total:
94 yield total
95
96 bufsize = min(size, 8192)
97 chunk = b"".join([random.choice(string.ascii_letters).encode()
98 for i in range(bufsize)])
99 with open(path, 'wb') as f:
100 for csize in chunks(size, bufsize):
101 f.write(chunk)
102 assert os.path.getsize(path) == size
103
104 def read_file(path, binary=False):
105 """Return contents from a file located at *path*.
106
107 If *path* is a tuple instead of a string, os.path.join will be used to
108 make a path. If *binary* is true, the file will be opened in binary
109 mode.
110 """
111 if isinstance(path, tuple):
112 path = os.path.join(*path)
113 mode = 'rb' if binary else 'r'
114 encoding = None if binary else "utf-8"
115 with open(path, mode, encoding=encoding) as fp:
116 return fp.read()
117
118 def rlistdir(path):
119 res = []
120 for name in sorted(os.listdir(path)):
121 p = os.path.join(path, name)
122 if os.path.isdir(p) and not os.path.islink(p):
123 res.append(name + '/')
124 for n in rlistdir(p):
125 res.append(name + '/' + n)
126 else:
127 res.append(name)
128 return res
129
130 def supports_file2file_sendfile():
131 # ...apparently Linux and Solaris are the only ones
132 if not hasattr(os, "sendfile"):
133 return False
134 srcname = None
135 dstname = None
136 try:
137 with tempfile.NamedTemporaryFile("wb", dir=os.getcwd(), delete=False) as f:
138 srcname = f.name
139 f.write(b"0123456789")
140
141 with open(srcname, "rb") as src:
142 with tempfile.NamedTemporaryFile("wb", dir=os.getcwd(), delete=False) as dst:
143 dstname = dst.name
144 infd = src.fileno()
145 outfd = dst.fileno()
146 try:
147 os.sendfile(outfd, infd, 0, 2)
148 except OSError:
149 return False
150 else:
151 return True
152 finally:
153 if srcname is not None:
154 os_helper.unlink(srcname)
155 if dstname is not None:
156 os_helper.unlink(dstname)
157
158
159 SUPPORTS_SENDFILE = supports_file2file_sendfile()
160
161 # AIX 32-bit mode, by default, lacks enough memory for the xz/lzma compiler test
162 # The AIX command 'dump -o program' gives XCOFF header information
163 # The second word of the last line in the maxdata value
164 # when 32-bit maxdata must be greater than 0x1000000 for the xz test to succeed
165 def _maxdataOK():
166 if AIX and sys.maxsize == 2147483647:
167 hdrs=subprocess.getoutput("/usr/bin/dump -o %s" % sys.executable)
168 maxdata=hdrs.split("\n")[-1].split()[1]
169 return int(maxdata,16) >= 0x20000000
170 else:
171 return True
172
173
174 class BaseTest:
175
176 def mkdtemp(self, prefix=None):
177 """Create a temporary directory that will be cleaned up.
178
179 Returns the path of the directory.
180 """
181 d = tempfile.mkdtemp(prefix=prefix, dir=os.getcwd())
182 self.addCleanup(os_helper.rmtree, d)
183 return d
184
185
186 class TestRmTree(BaseTest, unittest.TestCase):
187
188 def test_rmtree_works_on_bytes(self):
189 tmp = self.mkdtemp()
190 victim = os.path.join(tmp, 'killme')
191 os.mkdir(victim)
192 create_file(os.path.join(victim, 'somefile'), 'foo')
193 victim = os.fsencode(victim)
194 self.assertIsInstance(victim, bytes)
195 shutil.rmtree(victim)
196
197 @os_helper.skip_unless_symlink
198 def test_rmtree_fails_on_symlink_onerror(self):
199 tmp = self.mkdtemp()
200 dir_ = os.path.join(tmp, 'dir')
201 os.mkdir(dir_)
202 link = os.path.join(tmp, 'link')
203 os.symlink(dir_, link)
204 self.assertRaises(OSError, shutil.rmtree, link)
205 self.assertTrue(os.path.exists(dir_))
206 self.assertTrue(os.path.lexists(link))
207 errors = []
208 def onerror(*args):
209 errors.append(args)
210 shutil.rmtree(link, onerror=onerror)
211 self.assertEqual(len(errors), 1)
212 self.assertIs(errors[0][0], os.path.islink)
213 self.assertEqual(errors[0][1], link)
214 self.assertIsInstance(errors[0][2][1], OSError)
215
216 @os_helper.skip_unless_symlink
217 def test_rmtree_fails_on_symlink_onexc(self):
218 tmp = self.mkdtemp()
219 dir_ = os.path.join(tmp, 'dir')
220 os.mkdir(dir_)
221 link = os.path.join(tmp, 'link')
222 os.symlink(dir_, link)
223 self.assertRaises(OSError, shutil.rmtree, link)
224 self.assertTrue(os.path.exists(dir_))
225 self.assertTrue(os.path.lexists(link))
226 errors = []
227 def onexc(*args):
228 errors.append(args)
229 shutil.rmtree(link, onexc=onexc)
230 self.assertEqual(len(errors), 1)
231 self.assertIs(errors[0][0], os.path.islink)
232 self.assertEqual(errors[0][1], link)
233 self.assertIsInstance(errors[0][2], OSError)
234
235 @os_helper.skip_unless_symlink
236 def test_rmtree_works_on_symlinks(self):
237 tmp = self.mkdtemp()
238 dir1 = os.path.join(tmp, 'dir1')
239 dir2 = os.path.join(dir1, 'dir2')
240 dir3 = os.path.join(tmp, 'dir3')
241 for d in dir1, dir2, dir3:
242 os.mkdir(d)
243 file1 = os.path.join(tmp, 'file1')
244 create_file(file1, 'foo')
245 link1 = os.path.join(dir1, 'link1')
246 os.symlink(dir2, link1)
247 link2 = os.path.join(dir1, 'link2')
248 os.symlink(dir3, link2)
249 link3 = os.path.join(dir1, 'link3')
250 os.symlink(file1, link3)
251 # make sure symlinks are removed but not followed
252 shutil.rmtree(dir1)
253 self.assertFalse(os.path.exists(dir1))
254 self.assertTrue(os.path.exists(dir3))
255 self.assertTrue(os.path.exists(file1))
256
257 @unittest.skipUnless(_winapi, 'only relevant on Windows')
258 def test_rmtree_fails_on_junctions_onerror(self):
259 tmp = self.mkdtemp()
260 dir_ = os.path.join(tmp, 'dir')
261 os.mkdir(dir_)
262 link = os.path.join(tmp, 'link')
263 _winapi.CreateJunction(dir_, link)
264 self.addCleanup(os_helper.unlink, link)
265 self.assertRaises(OSError, shutil.rmtree, link)
266 self.assertTrue(os.path.exists(dir_))
267 self.assertTrue(os.path.lexists(link))
268 errors = []
269 def onerror(*args):
270 errors.append(args)
271 shutil.rmtree(link, onerror=onerror)
272 self.assertEqual(len(errors), 1)
273 self.assertIs(errors[0][0], os.path.islink)
274 self.assertEqual(errors[0][1], link)
275 self.assertIsInstance(errors[0][2][1], OSError)
276
277 @unittest.skipUnless(_winapi, 'only relevant on Windows')
278 def test_rmtree_fails_on_junctions_onexc(self):
279 tmp = self.mkdtemp()
280 dir_ = os.path.join(tmp, 'dir')
281 os.mkdir(dir_)
282 link = os.path.join(tmp, 'link')
283 _winapi.CreateJunction(dir_, link)
284 self.addCleanup(os_helper.unlink, link)
285 self.assertRaises(OSError, shutil.rmtree, link)
286 self.assertTrue(os.path.exists(dir_))
287 self.assertTrue(os.path.lexists(link))
288 errors = []
289 def onexc(*args):
290 errors.append(args)
291 shutil.rmtree(link, onexc=onexc)
292 self.assertEqual(len(errors), 1)
293 self.assertIs(errors[0][0], os.path.islink)
294 self.assertEqual(errors[0][1], link)
295 self.assertIsInstance(errors[0][2], OSError)
296
297 @unittest.skipUnless(_winapi, 'only relevant on Windows')
298 def test_rmtree_works_on_junctions(self):
299 tmp = self.mkdtemp()
300 dir1 = os.path.join(tmp, 'dir1')
301 dir2 = os.path.join(dir1, 'dir2')
302 dir3 = os.path.join(tmp, 'dir3')
303 for d in dir1, dir2, dir3:
304 os.mkdir(d)
305 file1 = os.path.join(tmp, 'file1')
306 create_file(file1, 'foo')
307 link1 = os.path.join(dir1, 'link1')
308 _winapi.CreateJunction(dir2, link1)
309 link2 = os.path.join(dir1, 'link2')
310 _winapi.CreateJunction(dir3, link2)
311 link3 = os.path.join(dir1, 'link3')
312 _winapi.CreateJunction(file1, link3)
313 # make sure junctions are removed but not followed
314 shutil.rmtree(dir1)
315 self.assertFalse(os.path.exists(dir1))
316 self.assertTrue(os.path.exists(dir3))
317 self.assertTrue(os.path.exists(file1))
318
319 def test_rmtree_errors(self):
320 # filename is guaranteed not to exist
321 filename = tempfile.mktemp(dir=self.mkdtemp())
322 self.assertRaises(FileNotFoundError, shutil.rmtree, filename)
323 # test that ignore_errors option is honored
324 shutil.rmtree(filename, ignore_errors=True)
325
326 # existing file
327 tmpdir = self.mkdtemp()
328 filename = os.path.join(tmpdir, "tstfile")
329 create_file(filename)
330 with self.assertRaises(NotADirectoryError) as cm:
331 shutil.rmtree(filename)
332 self.assertEqual(cm.exception.filename, filename)
333 self.assertTrue(os.path.exists(filename))
334 # test that ignore_errors option is honored
335 shutil.rmtree(filename, ignore_errors=True)
336 self.assertTrue(os.path.exists(filename))
337
338 self.assertRaises(TypeError, shutil.rmtree, None)
339 self.assertRaises(TypeError, shutil.rmtree, None, ignore_errors=True)
340 exc = TypeError if shutil.rmtree.avoids_symlink_attacks else NotImplementedError
341 with self.assertRaises(exc):
342 shutil.rmtree(filename, dir_fd='invalid')
343 with self.assertRaises(exc):
344 shutil.rmtree(filename, dir_fd='invalid', ignore_errors=True)
345
346 def test_rmtree_errors_onerror(self):
347 tmpdir = self.mkdtemp()
348 filename = os.path.join(tmpdir, "tstfile")
349 create_file(filename)
350 errors = []
351 def onerror(*args):
352 errors.append(args)
353 shutil.rmtree(filename, onerror=onerror)
354 self.assertEqual(len(errors), 2)
355 self.assertIs(errors[0][0], os.scandir)
356 self.assertEqual(errors[0][1], filename)
357 self.assertIsInstance(errors[0][2][1], NotADirectoryError)
358 self.assertEqual(errors[0][2][1].filename, filename)
359 self.assertIs(errors[1][0], os.rmdir)
360 self.assertEqual(errors[1][1], filename)
361 self.assertIsInstance(errors[1][2][1], NotADirectoryError)
362 self.assertEqual(errors[1][2][1].filename, filename)
363
364 def test_rmtree_errors_onexc(self):
365 tmpdir = self.mkdtemp()
366 filename = os.path.join(tmpdir, "tstfile")
367 create_file(filename)
368 errors = []
369 def onexc(*args):
370 errors.append(args)
371 shutil.rmtree(filename, onexc=onexc)
372 self.assertEqual(len(errors), 2)
373 self.assertIs(errors[0][0], os.scandir)
374 self.assertEqual(errors[0][1], filename)
375 self.assertIsInstance(errors[0][2], NotADirectoryError)
376 self.assertEqual(errors[0][2].filename, filename)
377 self.assertIs(errors[1][0], os.rmdir)
378 self.assertEqual(errors[1][1], filename)
379 self.assertIsInstance(errors[1][2], NotADirectoryError)
380 self.assertEqual(errors[1][2].filename, filename)
381
382 @unittest.skipIf(sys.platform[:6] == 'cygwin',
383 "This test can't be run on Cygwin (issue #1071513).")
384 @os_helper.skip_if_dac_override
385 @os_helper.skip_unless_working_chmod
386 def test_on_error(self):
387 self.errorState = 0
388 os.mkdir(TESTFN)
389 self.addCleanup(shutil.rmtree, TESTFN)
390
391 self.child_file_path = os.path.join(TESTFN, 'a')
392 self.child_dir_path = os.path.join(TESTFN, 'b')
393 os_helper.create_empty_file(self.child_file_path)
394 os.mkdir(self.child_dir_path)
395 old_dir_mode = os.stat(TESTFN).st_mode
396 old_child_file_mode = os.stat(self.child_file_path).st_mode
397 old_child_dir_mode = os.stat(self.child_dir_path).st_mode
398 # Make unwritable.
399 new_mode = stat.S_IREAD|stat.S_IEXEC
400 os.chmod(self.child_file_path, new_mode)
401 os.chmod(self.child_dir_path, new_mode)
402 os.chmod(TESTFN, new_mode)
403
404 self.addCleanup(os.chmod, TESTFN, old_dir_mode)
405 self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
406 self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
407
408 shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
409 # Test whether onerror has actually been called.
410 self.assertEqual(self.errorState, 3,
411 "Expected call to onerror function did not happen.")
412
413 def check_args_to_onerror(self, func, arg, exc):
414 # test_rmtree_errors deliberately runs rmtree
415 # on a directory that is chmod 500, which will fail.
416 # This function is run when shutil.rmtree fails.
417 # 99.9% of the time it initially fails to remove
418 # a file in the directory, so the first time through
419 # func is os.remove.
420 # However, some Linux machines running ZFS on
421 # FUSE experienced a failure earlier in the process
422 # at os.listdir. The first failure may legally
423 # be either.
424 if self.errorState < 2:
425 if func is os.unlink:
426 self.assertEqual(arg, self.child_file_path)
427 elif func is os.rmdir:
428 self.assertEqual(arg, self.child_dir_path)
429 else:
430 self.assertIs(func, os.listdir)
431 self.assertIn(arg, [TESTFN, self.child_dir_path])
432 self.assertTrue(issubclass(exc[0], OSError))
433 self.errorState += 1
434 else:
435 self.assertEqual(func, os.rmdir)
436 self.assertEqual(arg, TESTFN)
437 self.assertTrue(issubclass(exc[0], OSError))
438 self.errorState = 3
439
440 @unittest.skipIf(sys.platform[:6] == 'cygwin',
441 "This test can't be run on Cygwin (issue #1071513).")
442 @os_helper.skip_if_dac_override
443 @os_helper.skip_unless_working_chmod
444 def test_on_exc(self):
445 self.errorState = 0
446 os.mkdir(TESTFN)
447 self.addCleanup(shutil.rmtree, TESTFN)
448
449 self.child_file_path = os.path.join(TESTFN, 'a')
450 self.child_dir_path = os.path.join(TESTFN, 'b')
451 os_helper.create_empty_file(self.child_file_path)
452 os.mkdir(self.child_dir_path)
453 old_dir_mode = os.stat(TESTFN).st_mode
454 old_child_file_mode = os.stat(self.child_file_path).st_mode
455 old_child_dir_mode = os.stat(self.child_dir_path).st_mode
456 # Make unwritable.
457 new_mode = stat.S_IREAD|stat.S_IEXEC
458 os.chmod(self.child_file_path, new_mode)
459 os.chmod(self.child_dir_path, new_mode)
460 os.chmod(TESTFN, new_mode)
461
462 self.addCleanup(os.chmod, TESTFN, old_dir_mode)
463 self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
464 self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
465
466 shutil.rmtree(TESTFN, onexc=self.check_args_to_onexc)
467 # Test whether onexc has actually been called.
468 self.assertEqual(self.errorState, 3,
469 "Expected call to onexc function did not happen.")
470
471 def check_args_to_onexc(self, func, arg, exc):
472 # test_rmtree_errors deliberately runs rmtree
473 # on a directory that is chmod 500, which will fail.
474 # This function is run when shutil.rmtree fails.
475 # 99.9% of the time it initially fails to remove
476 # a file in the directory, so the first time through
477 # func is os.remove.
478 # However, some Linux machines running ZFS on
479 # FUSE experienced a failure earlier in the process
480 # at os.listdir. The first failure may legally
481 # be either.
482 if self.errorState < 2:
483 if func is os.unlink:
484 self.assertEqual(arg, self.child_file_path)
485 elif func is os.rmdir:
486 self.assertEqual(arg, self.child_dir_path)
487 else:
488 self.assertIs(func, os.listdir)
489 self.assertIn(arg, [TESTFN, self.child_dir_path])
490 self.assertTrue(isinstance(exc, OSError))
491 self.errorState += 1
492 else:
493 self.assertEqual(func, os.rmdir)
494 self.assertEqual(arg, TESTFN)
495 self.assertTrue(isinstance(exc, OSError))
496 self.errorState = 3
497
498 @unittest.skipIf(sys.platform[:6] == 'cygwin',
499 "This test can't be run on Cygwin (issue #1071513).")
500 @os_helper.skip_if_dac_override
501 @os_helper.skip_unless_working_chmod
502 def test_both_onerror_and_onexc(self):
503 onerror_called = False
504 onexc_called = False
505
506 def onerror(*args):
507 nonlocal onerror_called
508 onerror_called = True
509
510 def onexc(*args):
511 nonlocal onexc_called
512 onexc_called = True
513
514 os.mkdir(TESTFN)
515 self.addCleanup(shutil.rmtree, TESTFN)
516
517 self.child_file_path = os.path.join(TESTFN, 'a')
518 self.child_dir_path = os.path.join(TESTFN, 'b')
519 os_helper.create_empty_file(self.child_file_path)
520 os.mkdir(self.child_dir_path)
521 old_dir_mode = os.stat(TESTFN).st_mode
522 old_child_file_mode = os.stat(self.child_file_path).st_mode
523 old_child_dir_mode = os.stat(self.child_dir_path).st_mode
524 # Make unwritable.
525 new_mode = stat.S_IREAD|stat.S_IEXEC
526 os.chmod(self.child_file_path, new_mode)
527 os.chmod(self.child_dir_path, new_mode)
528 os.chmod(TESTFN, new_mode)
529
530 self.addCleanup(os.chmod, TESTFN, old_dir_mode)
531 self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
532 self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
533
534 shutil.rmtree(TESTFN, onerror=onerror, onexc=onexc)
535 self.assertTrue(onexc_called)
536 self.assertFalse(onerror_called)
537
538 def test_rmtree_does_not_choke_on_failing_lstat(self):
539 try:
540 orig_lstat = os.lstat
541 def raiser(fn, *args, **kwargs):
542 if fn != TESTFN:
543 raise OSError()
544 else:
545 return orig_lstat(fn)
546 os.lstat = raiser
547
548 os.mkdir(TESTFN)
549 create_file((TESTFN, 'foo'), 'foo')
550 shutil.rmtree(TESTFN)
551 finally:
552 os.lstat = orig_lstat
553
554 def test_rmtree_uses_safe_fd_version_if_available(self):
555 _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
556 os.supports_dir_fd and
557 os.listdir in os.supports_fd and
558 os.stat in os.supports_follow_symlinks)
559 if _use_fd_functions:
560 self.assertTrue(shutil._use_fd_functions)
561 self.assertTrue(shutil.rmtree.avoids_symlink_attacks)
562 tmp_dir = self.mkdtemp()
563 d = os.path.join(tmp_dir, 'a')
564 os.mkdir(d)
565 try:
566 real_rmtree = shutil._rmtree_safe_fd
567 class Called(Exception): pass
568 def _raiser(*args, **kwargs):
569 raise Called
570 shutil._rmtree_safe_fd = _raiser
571 self.assertRaises(Called, shutil.rmtree, d)
572 finally:
573 shutil._rmtree_safe_fd = real_rmtree
574 else:
575 self.assertFalse(shutil._use_fd_functions)
576 self.assertFalse(shutil.rmtree.avoids_symlink_attacks)
577
578 @unittest.skipUnless(shutil._use_fd_functions, "requires safe rmtree")
579 def test_rmtree_fails_on_close(self):
580 # Test that the error handler is called for failed os.close() and that
581 # os.close() is only called once for a file descriptor.
582 tmp = self.mkdtemp()
583 dir1 = os.path.join(tmp, 'dir1')
584 os.mkdir(dir1)
585 dir2 = os.path.join(dir1, 'dir2')
586 os.mkdir(dir2)
587 def close(fd):
588 orig_close(fd)
589 nonlocal close_count
590 close_count += 1
591 raise OSError
592
593 close_count = 0
594 with support.swap_attr(os, 'close', close) as orig_close:
595 with self.assertRaises(OSError):
596 shutil.rmtree(dir1)
597 self.assertTrue(os.path.isdir(dir2))
598 self.assertEqual(close_count, 2)
599
600 close_count = 0
601 errors = []
602 def onexc(*args):
603 errors.append(args)
604 with support.swap_attr(os, 'close', close) as orig_close:
605 shutil.rmtree(dir1, onexc=onexc)
606 self.assertEqual(len(errors), 2)
607 self.assertIs(errors[0][0], close)
608 self.assertEqual(errors[0][1], dir2)
609 self.assertIs(errors[1][0], close)
610 self.assertEqual(errors[1][1], dir1)
611 self.assertEqual(close_count, 2)
612
613 @unittest.skipUnless(shutil._use_fd_functions, "dir_fd is not supported")
614 def test_rmtree_with_dir_fd(self):
615 tmp_dir = self.mkdtemp()
616 victim = 'killme'
617 fullname = os.path.join(tmp_dir, victim)
618 dir_fd = os.open(tmp_dir, os.O_RDONLY)
619 self.addCleanup(os.close, dir_fd)
620 os.mkdir(fullname)
621 os.mkdir(os.path.join(fullname, 'subdir'))
622 create_file(os.path.join(fullname, 'subdir', 'somefile'), 'foo')
623 self.assertTrue(os.path.exists(fullname))
624 shutil.rmtree(victim, dir_fd=dir_fd)
625 self.assertFalse(os.path.exists(fullname))
626
627 @unittest.skipIf(shutil._use_fd_functions, "dir_fd is supported")
628 def test_rmtree_with_dir_fd_unsupported(self):
629 tmp_dir = self.mkdtemp()
630 with self.assertRaises(NotImplementedError):
631 shutil.rmtree(tmp_dir, dir_fd=0)
632 self.assertTrue(os.path.exists(tmp_dir))
633
634 def test_rmtree_dont_delete_file(self):
635 # When called on a file instead of a directory, don't delete it.
636 handle, path = tempfile.mkstemp(dir=self.mkdtemp())
637 os.close(handle)
638 self.assertRaises(NotADirectoryError, shutil.rmtree, path)
639 os.remove(path)
640
641 @os_helper.skip_unless_symlink
642 def test_rmtree_on_symlink(self):
643 # bug 1669.
644 os.mkdir(TESTFN)
645 try:
646 src = os.path.join(TESTFN, 'cheese')
647 dst = os.path.join(TESTFN, 'shop')
648 os.mkdir(src)
649 os.symlink(src, dst)
650 self.assertRaises(OSError, shutil.rmtree, dst)
651 shutil.rmtree(dst, ignore_errors=True)
652 finally:
653 shutil.rmtree(TESTFN, ignore_errors=True)
654
655 @unittest.skipUnless(_winapi, 'only relevant on Windows')
656 def test_rmtree_on_junction(self):
657 os.mkdir(TESTFN)
658 try:
659 src = os.path.join(TESTFN, 'cheese')
660 dst = os.path.join(TESTFN, 'shop')
661 os.mkdir(src)
662 create_file(os.path.join(src, 'spam'))
663 _winapi.CreateJunction(src, dst)
664 self.assertRaises(OSError, shutil.rmtree, dst)
665 shutil.rmtree(dst, ignore_errors=True)
666 finally:
667 shutil.rmtree(TESTFN, ignore_errors=True)
668
669 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
670 @unittest.skipIf(sys.platform == "vxworks",
671 "fifo requires special path on VxWorks")
672 def test_rmtree_on_named_pipe(self):
673 os.mkfifo(TESTFN)
674 try:
675 with self.assertRaises(NotADirectoryError):
676 shutil.rmtree(TESTFN)
677 self.assertTrue(os.path.exists(TESTFN))
678 finally:
679 os.unlink(TESTFN)
680
681 os.mkdir(TESTFN)
682 os.mkfifo(os.path.join(TESTFN, 'mypipe'))
683 shutil.rmtree(TESTFN)
684 self.assertFalse(os.path.exists(TESTFN))
685
686 @unittest.skipIf(sys.platform[:6] == 'cygwin',
687 "This test can't be run on Cygwin (issue #1071513).")
688 @os_helper.skip_if_dac_override
689 @os_helper.skip_unless_working_chmod
690 def test_rmtree_deleted_race_condition(self):
691 # bpo-37260
692 #
693 # Test that a file or a directory deleted after it is enumerated
694 # by scandir() but before unlink() or rmdr() is called doesn't
695 # generate any errors.
696 def _onexc(fn, path, exc):
697 assert fn in (os.rmdir, os.unlink)
698 if not isinstance(exc, PermissionError):
699 raise
700 # Make the parent and the children writeable.
701 for p, mode in zip(paths, old_modes):
702 os.chmod(p, mode)
703 # Remove other dirs except one.
704 keep = next(p for p in dirs if p != path)
705 for p in dirs:
706 if p != keep:
707 os.rmdir(p)
708 # Remove other files except one.
709 keep = next(p for p in files if p != path)
710 for p in files:
711 if p != keep:
712 os.unlink(p)
713
714 os.mkdir(TESTFN)
715 paths = [TESTFN] + [os.path.join(TESTFN, f'child{i}')
716 for i in range(6)]
717 dirs = paths[1::2]
718 files = paths[2::2]
719 for path in dirs:
720 os.mkdir(path)
721 for path in files:
722 create_file(path)
723
724 old_modes = [os.stat(path).st_mode for path in paths]
725
726 # Make the parent and the children non-writeable.
727 new_mode = stat.S_IREAD|stat.S_IEXEC
728 for path in reversed(paths):
729 os.chmod(path, new_mode)
730
731 try:
732 shutil.rmtree(TESTFN, onexc=_onexc)
733 except:
734 # Test failed, so cleanup artifacts.
735 for path, mode in zip(paths, old_modes):
736 try:
737 os.chmod(path, mode)
738 except OSError:
739 pass
740 shutil.rmtree(TESTFN)
741 raise
742
743 def test_rmtree_above_recursion_limit(self):
744 recursion_limit = 40
745 # directory_depth > recursion_limit
746 directory_depth = recursion_limit + 10
747 base = os.path.join(TESTFN, *(['d'] * directory_depth))
748 os.makedirs(base)
749
750 with support.infinite_recursion(recursion_limit):
751 shutil.rmtree(TESTFN)
752
753
754 class TestCopyTree(BaseTest, unittest.TestCase):
755
756 def test_copytree_simple(self):
757 src_dir = self.mkdtemp()
758 dst_dir = os.path.join(self.mkdtemp(), 'destination')
759 self.addCleanup(shutil.rmtree, src_dir)
760 self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
761 create_file((src_dir, 'test.txt'), '123')
762 os.mkdir(os.path.join(src_dir, 'test_dir'))
763 create_file((src_dir, 'test_dir', 'test.txt'), '456')
764
765 shutil.copytree(src_dir, dst_dir)
766 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
767 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
768 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
769 'test.txt')))
770 actual = read_file((dst_dir, 'test.txt'))
771 self.assertEqual(actual, '123')
772 actual = read_file((dst_dir, 'test_dir', 'test.txt'))
773 self.assertEqual(actual, '456')
774
775 def test_copytree_dirs_exist_ok(self):
776 src_dir = self.mkdtemp()
777 dst_dir = self.mkdtemp()
778 self.addCleanup(shutil.rmtree, src_dir)
779 self.addCleanup(shutil.rmtree, dst_dir)
780
781 create_file((src_dir, 'nonexisting.txt'), '123')
782 os.mkdir(os.path.join(src_dir, 'existing_dir'))
783 os.mkdir(os.path.join(dst_dir, 'existing_dir'))
784 create_file((dst_dir, 'existing_dir', 'existing.txt'), 'will be replaced')
785 create_file((src_dir, 'existing_dir', 'existing.txt'), 'has been replaced')
786
787 shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True)
788 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'nonexisting.txt')))
789 self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'existing_dir')))
790 self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'existing_dir',
791 'existing.txt')))
792 actual = read_file((dst_dir, 'nonexisting.txt'))
793 self.assertEqual(actual, '123')
794 actual = read_file((dst_dir, 'existing_dir', 'existing.txt'))
795 self.assertEqual(actual, 'has been replaced')
796
797 with self.assertRaises(FileExistsError):
798 shutil.copytree(src_dir, dst_dir, dirs_exist_ok=False)
799
800 @os_helper.skip_unless_symlink
801 def test_copytree_symlinks(self):
802 tmp_dir = self.mkdtemp()
803 src_dir = os.path.join(tmp_dir, 'src')
804 dst_dir = os.path.join(tmp_dir, 'dst')
805 sub_dir = os.path.join(src_dir, 'sub')
806 os.mkdir(src_dir)
807 os.mkdir(sub_dir)
808 create_file((src_dir, 'file.txt'), 'foo')
809 src_link = os.path.join(sub_dir, 'link')
810 dst_link = os.path.join(dst_dir, 'sub/link')
811 os.symlink(os.path.join(src_dir, 'file.txt'),
812 src_link)
813 if hasattr(os, 'lchmod'):
814 os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
815 if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
816 os.lchflags(src_link, stat.UF_NODUMP)
817 src_stat = os.lstat(src_link)
818 shutil.copytree(src_dir, dst_dir, symlinks=True)
819 self.assertTrue(os.path.islink(os.path.join(dst_dir, 'sub', 'link')))
820 actual = os.readlink(os.path.join(dst_dir, 'sub', 'link'))
821 # Bad practice to blindly strip the prefix as it may be required to
822 # correctly refer to the file, but we're only comparing paths here.
823 if os.name == 'nt' and actual.startswith('\\\\?\\'):
824 actual = actual[4:]
825 self.assertEqual(actual, os.path.join(src_dir, 'file.txt'))
826 dst_stat = os.lstat(dst_link)
827 if hasattr(os, 'lchmod'):
828 self.assertEqual(dst_stat.st_mode, src_stat.st_mode)
829 if hasattr(os, 'lchflags'):
830 self.assertEqual(dst_stat.st_flags, src_stat.st_flags)
831
832 def test_copytree_with_exclude(self):
833 # creating data
834 join = os.path.join
835 exists = os.path.exists
836 src_dir = self.mkdtemp()
837 try:
838 dst_dir = join(self.mkdtemp(), 'destination')
839 create_file((src_dir, 'test.txt'), '123')
840 create_file((src_dir, 'test.tmp'), '123')
841 os.mkdir(join(src_dir, 'test_dir'))
842 create_file((src_dir, 'test_dir', 'test.txt'), '456')
843 os.mkdir(join(src_dir, 'test_dir2'))
844 create_file((src_dir, 'test_dir2', 'test.txt'), '456')
845 os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
846 os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
847 create_file((src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
848 create_file((src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
849
850 # testing glob-like patterns
851 try:
852 patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
853 shutil.copytree(src_dir, dst_dir, ignore=patterns)
854 # checking the result: some elements should not be copied
855 self.assertTrue(exists(join(dst_dir, 'test.txt')))
856 self.assertFalse(exists(join(dst_dir, 'test.tmp')))
857 self.assertFalse(exists(join(dst_dir, 'test_dir2')))
858 finally:
859 shutil.rmtree(dst_dir)
860 try:
861 patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
862 shutil.copytree(src_dir, dst_dir, ignore=patterns)
863 # checking the result: some elements should not be copied
864 self.assertFalse(exists(join(dst_dir, 'test.tmp')))
865 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2')))
866 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
867 finally:
868 shutil.rmtree(dst_dir)
869
870 # testing callable-style
871 try:
872 def _filter(src, names):
873 res = []
874 for name in names:
875 path = os.path.join(src, name)
876
877 if (os.path.isdir(path) and
878 path.split()[-1] == 'subdir'):
879 res.append(name)
880 elif os.path.splitext(path)[-1] in ('.py'):
881 res.append(name)
882 return res
883
884 shutil.copytree(src_dir, dst_dir, ignore=_filter)
885
886 # checking the result: some elements should not be copied
887 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2',
888 'test.py')))
889 self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
890
891 finally:
892 shutil.rmtree(dst_dir)
893 finally:
894 shutil.rmtree(src_dir)
895 shutil.rmtree(os.path.dirname(dst_dir))
896
897 def test_copytree_arg_types_of_ignore(self):
898 join = os.path.join
899 exists = os.path.exists
900
901 tmp_dir = self.mkdtemp()
902 src_dir = join(tmp_dir, "source")
903
904 os.mkdir(join(src_dir))
905 os.mkdir(join(src_dir, 'test_dir'))
906 os.mkdir(os.path.join(src_dir, 'test_dir', 'subdir'))
907 create_file((src_dir, 'test_dir', 'subdir', 'test.txt'), '456')
908
909 invokations = []
910
911 def _ignore(src, names):
912 invokations.append(src)
913 self.assertIsInstance(src, str)
914 self.assertIsInstance(names, list)
915 self.assertEqual(len(names), len(set(names)))
916 for name in names:
917 self.assertIsInstance(name, str)
918 return []
919
920 dst_dir = join(self.mkdtemp(), 'destination')
921 shutil.copytree(src_dir, dst_dir, ignore=_ignore)
922 self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
923 'test.txt')))
924
925 dst_dir = join(self.mkdtemp(), 'destination')
926 shutil.copytree(FakePath(src_dir), dst_dir, ignore=_ignore)
927 self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
928 'test.txt')))
929
930 dst_dir = join(self.mkdtemp(), 'destination')
931 src_dir_entry = list(os.scandir(tmp_dir))[0]
932 self.assertIsInstance(src_dir_entry, os.DirEntry)
933 shutil.copytree(src_dir_entry, dst_dir, ignore=_ignore)
934 self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
935 'test.txt')))
936
937 self.assertEqual(len(invokations), 9)
938
939 def test_copytree_retains_permissions(self):
940 tmp_dir = self.mkdtemp()
941 src_dir = os.path.join(tmp_dir, 'source')
942 os.mkdir(src_dir)
943 dst_dir = os.path.join(tmp_dir, 'destination')
944 self.addCleanup(shutil.rmtree, tmp_dir)
945
946 os.chmod(src_dir, 0o777)
947 create_file((src_dir, 'permissive.txt'), '123')
948 os.chmod(os.path.join(src_dir, 'permissive.txt'), 0o777)
949 create_file((src_dir, 'restrictive.txt'), '456')
950 os.chmod(os.path.join(src_dir, 'restrictive.txt'), 0o600)
951 restrictive_subdir = tempfile.mkdtemp(dir=src_dir)
952 self.addCleanup(os_helper.rmtree, restrictive_subdir)
953 os.chmod(restrictive_subdir, 0o600)
954
955 shutil.copytree(src_dir, dst_dir)
956 self.assertEqual(os.stat(src_dir).st_mode, os.stat(dst_dir).st_mode)
957 self.assertEqual(os.stat(os.path.join(src_dir, 'permissive.txt')).st_mode,
958 os.stat(os.path.join(dst_dir, 'permissive.txt')).st_mode)
959 self.assertEqual(os.stat(os.path.join(src_dir, 'restrictive.txt')).st_mode,
960 os.stat(os.path.join(dst_dir, 'restrictive.txt')).st_mode)
961 restrictive_subdir_dst = os.path.join(dst_dir,
962 os.path.split(restrictive_subdir)[1])
963 self.assertEqual(os.stat(restrictive_subdir).st_mode,
964 os.stat(restrictive_subdir_dst).st_mode)
965
966 @unittest.mock.patch('os.chmod')
967 def test_copytree_winerror(self, mock_patch):
968 # When copying to VFAT, copystat() raises OSError. On Windows, the
969 # exception object has a meaningful 'winerror' attribute, but not
970 # on other operating systems. Do not assume 'winerror' is set.
971 src_dir = self.mkdtemp()
972 dst_dir = os.path.join(self.mkdtemp(), 'destination')
973 self.addCleanup(shutil.rmtree, src_dir)
974 self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
975
976 mock_patch.side_effect = PermissionError('ka-boom')
977 with self.assertRaises(shutil.Error):
978 shutil.copytree(src_dir, dst_dir)
979
980 def test_copytree_custom_copy_function(self):
981 # See: https://bugs.python.org/issue35648
982 def custom_cpfun(a, b):
983 flag.append(None)
984 self.assertIsInstance(a, str)
985 self.assertIsInstance(b, str)
986 self.assertEqual(a, os.path.join(src, 'foo'))
987 self.assertEqual(b, os.path.join(dst, 'foo'))
988
989 flag = []
990 src = self.mkdtemp()
991 dst = tempfile.mktemp(dir=self.mkdtemp())
992 create_file(os.path.join(src, 'foo'))
993 shutil.copytree(src, dst, copy_function=custom_cpfun)
994 self.assertEqual(len(flag), 1)
995
996 # Issue #3002: copyfile and copytree block indefinitely on named pipes
997 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
998 @os_helper.skip_unless_symlink
999 @unittest.skipIf(sys.platform == "vxworks",
1000 "fifo requires special path on VxWorks")
1001 def test_copytree_named_pipe(self):
1002 os.mkdir(TESTFN)
1003 try:
1004 subdir = os.path.join(TESTFN, "subdir")
1005 os.mkdir(subdir)
1006 pipe = os.path.join(subdir, "mypipe")
1007 try:
1008 os.mkfifo(pipe)
1009 except PermissionError as e:
1010 self.skipTest('os.mkfifo(): %s' % e)
1011 try:
1012 shutil.copytree(TESTFN, TESTFN2)
1013 except shutil.Error as e:
1014 errors = e.args[0]
1015 self.assertEqual(len(errors), 1)
1016 src, dst, error_msg = errors[0]
1017 self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
1018 else:
1019 self.fail("shutil.Error should have been raised")
1020 finally:
1021 shutil.rmtree(TESTFN, ignore_errors=True)
1022 shutil.rmtree(TESTFN2, ignore_errors=True)
1023
1024 def test_copytree_special_func(self):
1025 src_dir = self.mkdtemp()
1026 dst_dir = os.path.join(self.mkdtemp(), 'destination')
1027 create_file((src_dir, 'test.txt'), '123')
1028 os.mkdir(os.path.join(src_dir, 'test_dir'))
1029 create_file((src_dir, 'test_dir', 'test.txt'), '456')
1030
1031 copied = []
1032 def _copy(src, dst):
1033 copied.append((src, dst))
1034
1035 shutil.copytree(src_dir, dst_dir, copy_function=_copy)
1036 self.assertEqual(len(copied), 2)
1037
1038 @os_helper.skip_unless_symlink
1039 def test_copytree_dangling_symlinks(self):
1040 src_dir = self.mkdtemp()
1041 valid_file = os.path.join(src_dir, 'test.txt')
1042 create_file(valid_file, 'abc')
1043 dir_a = os.path.join(src_dir, 'dir_a')
1044 os.mkdir(dir_a)
1045 for d in src_dir, dir_a:
1046 os.symlink('IDONTEXIST', os.path.join(d, 'broken'))
1047 os.symlink(valid_file, os.path.join(d, 'valid'))
1048
1049 # A dangling symlink should raise an error.
1050 dst_dir = os.path.join(self.mkdtemp(), 'destination')
1051 self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
1052
1053 # Dangling symlinks should be ignored with the proper flag.
1054 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
1055 shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
1056 for root, dirs, files in os.walk(dst_dir):
1057 self.assertNotIn('broken', files)
1058 self.assertIn('valid', files)
1059
1060 # a dangling symlink is copied if symlinks=True
1061 dst_dir = os.path.join(self.mkdtemp(), 'destination3')
1062 shutil.copytree(src_dir, dst_dir, symlinks=True)
1063 self.assertIn('test.txt', os.listdir(dst_dir))
1064
1065 @os_helper.skip_unless_symlink
1066 def test_copytree_symlink_dir(self):
1067 src_dir = self.mkdtemp()
1068 dst_dir = os.path.join(self.mkdtemp(), 'destination')
1069 os.mkdir(os.path.join(src_dir, 'real_dir'))
1070 create_file(os.path.join(src_dir, 'real_dir', 'test.txt'))
1071 os.symlink(os.path.join(src_dir, 'real_dir'),
1072 os.path.join(src_dir, 'link_to_dir'),
1073 target_is_directory=True)
1074
1075 shutil.copytree(src_dir, dst_dir, symlinks=False)
1076 self.assertFalse(os.path.islink(os.path.join(dst_dir, 'link_to_dir')))
1077 self.assertIn('test.txt', os.listdir(os.path.join(dst_dir, 'link_to_dir')))
1078
1079 dst_dir = os.path.join(self.mkdtemp(), 'destination2')
1080 shutil.copytree(src_dir, dst_dir, symlinks=True)
1081 self.assertTrue(os.path.islink(os.path.join(dst_dir, 'link_to_dir')))
1082 self.assertIn('test.txt', os.listdir(os.path.join(dst_dir, 'link_to_dir')))
1083
1084 def test_copytree_return_value(self):
1085 # copytree returns its destination path.
1086 src_dir = self.mkdtemp()
1087 dst_dir = src_dir + "dest"
1088 self.addCleanup(shutil.rmtree, dst_dir, True)
1089 src = os.path.join(src_dir, 'foo')
1090 create_file(src, 'foo')
1091 rv = shutil.copytree(src_dir, dst_dir)
1092 self.assertEqual(['foo'], os.listdir(rv))
1093
1094 def test_copytree_subdirectory(self):
1095 # copytree where dst is a subdirectory of src, see Issue 38688
1096 base_dir = self.mkdtemp()
1097 self.addCleanup(shutil.rmtree, base_dir, ignore_errors=True)
1098 src_dir = os.path.join(base_dir, "t", "pg")
1099 dst_dir = os.path.join(src_dir, "somevendor", "1.0")
1100 os.makedirs(src_dir)
1101 src = os.path.join(src_dir, 'pol')
1102 create_file(src, 'pol')
1103 rv = shutil.copytree(src_dir, dst_dir)
1104 self.assertEqual(['pol'], os.listdir(rv))
1105
1106 class TestCopy(BaseTest, unittest.TestCase):
1107
1108 ### shutil.copymode
1109
1110 @os_helper.skip_unless_symlink
1111 def test_copymode_follow_symlinks(self):
1112 tmp_dir = self.mkdtemp()
1113 src = os.path.join(tmp_dir, 'foo')
1114 dst = os.path.join(tmp_dir, 'bar')
1115 src_link = os.path.join(tmp_dir, 'baz')
1116 dst_link = os.path.join(tmp_dir, 'quux')
1117 create_file(src, 'foo')
1118 create_file(dst, 'foo')
1119 os.symlink(src, src_link)
1120 os.symlink(dst, dst_link)
1121 os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
1122 # file to file
1123 os.chmod(dst, stat.S_IRWXO)
1124 self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1125 shutil.copymode(src, dst)
1126 self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1127 # On Windows, os.chmod does not follow symlinks (issue #15411)
1128 # follow src link
1129 os.chmod(dst, stat.S_IRWXO)
1130 shutil.copymode(src_link, dst)
1131 self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1132 # follow dst link
1133 os.chmod(dst, stat.S_IRWXO)
1134 shutil.copymode(src, dst_link)
1135 self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1136 # follow both links
1137 os.chmod(dst, stat.S_IRWXO)
1138 shutil.copymode(src_link, dst_link)
1139 self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1140
1141 @unittest.skipUnless(hasattr(os, 'lchmod'), 'requires os.lchmod')
1142 @os_helper.skip_unless_symlink
1143 def test_copymode_symlink_to_symlink(self):
1144 tmp_dir = self.mkdtemp()
1145 src = os.path.join(tmp_dir, 'foo')
1146 dst = os.path.join(tmp_dir, 'bar')
1147 src_link = os.path.join(tmp_dir, 'baz')
1148 dst_link = os.path.join(tmp_dir, 'quux')
1149 create_file(src, 'foo')
1150 create_file(dst, 'foo')
1151 os.symlink(src, src_link)
1152 os.symlink(dst, dst_link)
1153 os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
1154 os.chmod(dst, stat.S_IRWXU)
1155 os.lchmod(src_link, stat.S_IRWXO|stat.S_IRWXG)
1156 # link to link
1157 os.lchmod(dst_link, stat.S_IRWXO)
1158 old_mode = os.stat(dst).st_mode
1159 shutil.copymode(src_link, dst_link, follow_symlinks=False)
1160 self.assertEqual(os.lstat(src_link).st_mode,
1161 os.lstat(dst_link).st_mode)
1162 self.assertEqual(os.stat(dst).st_mode, old_mode)
1163 # src link - use chmod
1164 os.lchmod(dst_link, stat.S_IRWXO)
1165 shutil.copymode(src_link, dst, follow_symlinks=False)
1166 self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1167 # dst link - use chmod
1168 os.lchmod(dst_link, stat.S_IRWXO)
1169 shutil.copymode(src, dst_link, follow_symlinks=False)
1170 self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
1171
1172 @unittest.skipIf(hasattr(os, 'lchmod'), 'requires os.lchmod to be missing')
1173 @os_helper.skip_unless_symlink
1174 def test_copymode_symlink_to_symlink_wo_lchmod(self):
1175 tmp_dir = self.mkdtemp()
1176 src = os.path.join(tmp_dir, 'foo')
1177 dst = os.path.join(tmp_dir, 'bar')
1178 src_link = os.path.join(tmp_dir, 'baz')
1179 dst_link = os.path.join(tmp_dir, 'quux')
1180 create_file(src, 'foo')
1181 create_file(dst, 'foo')
1182 os.symlink(src, src_link)
1183 os.symlink(dst, dst_link)
1184 shutil.copymode(src_link, dst_link, follow_symlinks=False) # silent fail
1185
1186 ### shutil.copystat
1187
1188 @os_helper.skip_unless_symlink
1189 def test_copystat_symlinks(self):
1190 tmp_dir = self.mkdtemp()
1191 src = os.path.join(tmp_dir, 'foo')
1192 dst = os.path.join(tmp_dir, 'bar')
1193 src_link = os.path.join(tmp_dir, 'baz')
1194 dst_link = os.path.join(tmp_dir, 'qux')
1195 create_file(src, 'foo')
1196 src_stat = os.stat(src)
1197 os.utime(src, (src_stat.st_atime,
1198 src_stat.st_mtime - 42.0)) # ensure different mtimes
1199 create_file(dst, 'bar')
1200 self.assertNotEqual(os.stat(src).st_mtime, os.stat(dst).st_mtime)
1201 os.symlink(src, src_link)
1202 os.symlink(dst, dst_link)
1203 if hasattr(os, 'lchmod'):
1204 os.lchmod(src_link, stat.S_IRWXO)
1205 if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
1206 os.lchflags(src_link, stat.UF_NODUMP)
1207 src_link_stat = os.lstat(src_link)
1208 # follow
1209 if hasattr(os, 'lchmod'):
1210 shutil.copystat(src_link, dst_link, follow_symlinks=True)
1211 self.assertNotEqual(src_link_stat.st_mode, os.stat(dst).st_mode)
1212 # don't follow
1213 shutil.copystat(src_link, dst_link, follow_symlinks=False)
1214 dst_link_stat = os.lstat(dst_link)
1215 if os.utime in os.supports_follow_symlinks:
1216 for attr in 'st_atime', 'st_mtime':
1217 # The modification times may be truncated in the new file.
1218 self.assertLessEqual(getattr(src_link_stat, attr),
1219 getattr(dst_link_stat, attr) + 1)
1220 if hasattr(os, 'lchmod'):
1221 self.assertEqual(src_link_stat.st_mode, dst_link_stat.st_mode)
1222 if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
1223 self.assertEqual(src_link_stat.st_flags, dst_link_stat.st_flags)
1224 # tell to follow but dst is not a link
1225 shutil.copystat(src_link, dst, follow_symlinks=False)
1226 self.assertTrue(abs(os.stat(src).st_mtime - os.stat(dst).st_mtime) <
1227 00000.1)
1228
1229 @unittest.skipUnless(hasattr(os, 'chflags') and
1230 hasattr(errno, 'EOPNOTSUPP') and
1231 hasattr(errno, 'ENOTSUP'),
1232 "requires os.chflags, EOPNOTSUPP & ENOTSUP")
1233 def test_copystat_handles_harmless_chflags_errors(self):
1234 tmpdir = self.mkdtemp()
1235 file1 = os.path.join(tmpdir, 'file1')
1236 file2 = os.path.join(tmpdir, 'file2')
1237 create_file(file1, 'xxx')
1238 create_file(file2, 'xxx')
1239
1240 def make_chflags_raiser(err):
1241 ex = OSError()
1242
1243 def _chflags_raiser(path, flags, *, follow_symlinks=True):
1244 ex.errno = err
1245 raise ex
1246 return _chflags_raiser
1247 old_chflags = os.chflags
1248 try:
1249 for err in errno.EOPNOTSUPP, errno.ENOTSUP:
1250 os.chflags = make_chflags_raiser(err)
1251 shutil.copystat(file1, file2)
1252 # assert others errors break it
1253 os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
1254 self.assertRaises(OSError, shutil.copystat, file1, file2)
1255 finally:
1256 os.chflags = old_chflags
1257
1258 ### shutil.copyxattr
1259
1260 @os_helper.skip_unless_xattr
1261 def test_copyxattr(self):
1262 tmp_dir = self.mkdtemp()
1263 src = os.path.join(tmp_dir, 'foo')
1264 create_file(src, 'foo')
1265 dst = os.path.join(tmp_dir, 'bar')
1266 create_file(dst, 'bar')
1267
1268 # no xattr == no problem
1269 shutil._copyxattr(src, dst)
1270 # common case
1271 os.setxattr(src, 'user.foo', b'42')
1272 os.setxattr(src, 'user.bar', b'43')
1273 shutil._copyxattr(src, dst)
1274 self.assertEqual(sorted(os.listxattr(src)), sorted(os.listxattr(dst)))
1275 self.assertEqual(
1276 os.getxattr(src, 'user.foo'),
1277 os.getxattr(dst, 'user.foo'))
1278 # check errors don't affect other attrs
1279 os.remove(dst)
1280 create_file(dst, 'bar')
1281 os_error = OSError(errno.EPERM, 'EPERM')
1282
1283 def _raise_on_user_foo(fname, attr, val, **kwargs):
1284 if attr == 'user.foo':
1285 raise os_error
1286 else:
1287 orig_setxattr(fname, attr, val, **kwargs)
1288 try:
1289 orig_setxattr = os.setxattr
1290 os.setxattr = _raise_on_user_foo
1291 shutil._copyxattr(src, dst)
1292 self.assertIn('user.bar', os.listxattr(dst))
1293 finally:
1294 os.setxattr = orig_setxattr
1295 # the source filesystem not supporting xattrs should be ok, too.
1296 def _raise_on_src(fname, *, follow_symlinks=True):
1297 if fname == src:
1298 raise OSError(errno.ENOTSUP, 'Operation not supported')
1299 return orig_listxattr(fname, follow_symlinks=follow_symlinks)
1300 try:
1301 orig_listxattr = os.listxattr
1302 os.listxattr = _raise_on_src
1303 shutil._copyxattr(src, dst)
1304 finally:
1305 os.listxattr = orig_listxattr
1306
1307 # test that shutil.copystat copies xattrs
1308 src = os.path.join(tmp_dir, 'the_original')
1309 srcro = os.path.join(tmp_dir, 'the_original_ro')
1310 create_file(src, src)
1311 create_file(srcro, srcro)
1312 os.setxattr(src, 'user.the_value', b'fiddly')
1313 os.setxattr(srcro, 'user.the_value', b'fiddly')
1314 os.chmod(srcro, 0o444)
1315 dst = os.path.join(tmp_dir, 'the_copy')
1316 dstro = os.path.join(tmp_dir, 'the_copy_ro')
1317 create_file(dst, dst)
1318 create_file(dstro, dstro)
1319 shutil.copystat(src, dst)
1320 shutil.copystat(srcro, dstro)
1321 self.assertEqual(os.getxattr(dst, 'user.the_value'), b'fiddly')
1322 self.assertEqual(os.getxattr(dstro, 'user.the_value'), b'fiddly')
1323
1324 @os_helper.skip_unless_symlink
1325 @os_helper.skip_unless_xattr
1326 @os_helper.skip_unless_dac_override
1327 def test_copyxattr_symlinks(self):
1328 # On Linux, it's only possible to access non-user xattr for symlinks;
1329 # which in turn require root privileges. This test should be expanded
1330 # as soon as other platforms gain support for extended attributes.
1331 tmp_dir = self.mkdtemp()
1332 src = os.path.join(tmp_dir, 'foo')
1333 src_link = os.path.join(tmp_dir, 'baz')
1334 create_file(src, 'foo')
1335 os.symlink(src, src_link)
1336 os.setxattr(src, 'trusted.foo', b'42')
1337 os.setxattr(src_link, 'trusted.foo', b'43', follow_symlinks=False)
1338 dst = os.path.join(tmp_dir, 'bar')
1339 dst_link = os.path.join(tmp_dir, 'qux')
1340 create_file(dst, 'bar')
1341 os.symlink(dst, dst_link)
1342 shutil._copyxattr(src_link, dst_link, follow_symlinks=False)
1343 self.assertEqual(os.getxattr(dst_link, 'trusted.foo', follow_symlinks=False), b'43')
1344 self.assertRaises(OSError, os.getxattr, dst, 'trusted.foo')
1345 shutil._copyxattr(src_link, dst, follow_symlinks=False)
1346 self.assertEqual(os.getxattr(dst, 'trusted.foo'), b'43')
1347
1348 ### shutil.copy
1349
1350 def _copy_file(self, method):
1351 fname = 'test.txt'
1352 tmpdir = self.mkdtemp()
1353 create_file((tmpdir, fname), 'xxx')
1354 file1 = os.path.join(tmpdir, fname)
1355 tmpdir2 = self.mkdtemp()
1356 method(file1, tmpdir2)
1357 file2 = os.path.join(tmpdir2, fname)
1358 return (file1, file2)
1359
1360 def test_copy(self):
1361 # Ensure that the copied file exists and has the same mode bits.
1362 file1, file2 = self._copy_file(shutil.copy)
1363 self.assertTrue(os.path.exists(file2))
1364 self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
1365
1366 @os_helper.skip_unless_symlink
1367 def test_copy_symlinks(self):
1368 tmp_dir = self.mkdtemp()
1369 src = os.path.join(tmp_dir, 'foo')
1370 dst = os.path.join(tmp_dir, 'bar')
1371 src_link = os.path.join(tmp_dir, 'baz')
1372 create_file(src, 'foo')
1373 os.symlink(src, src_link)
1374 if hasattr(os, 'lchmod'):
1375 os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
1376 # don't follow
1377 shutil.copy(src_link, dst, follow_symlinks=True)
1378 self.assertFalse(os.path.islink(dst))
1379 self.assertEqual(read_file(src), read_file(dst))
1380 os.remove(dst)
1381 # follow
1382 shutil.copy(src_link, dst, follow_symlinks=False)
1383 self.assertTrue(os.path.islink(dst))
1384 self.assertEqual(os.readlink(dst), os.readlink(src_link))
1385 if hasattr(os, 'lchmod'):
1386 self.assertEqual(os.lstat(src_link).st_mode,
1387 os.lstat(dst).st_mode)
1388
1389 ### shutil.copy2
1390
1391 @unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
1392 def test_copy2(self):
1393 # Ensure that the copied file exists and has the same mode and
1394 # modification time bits.
1395 file1, file2 = self._copy_file(shutil.copy2)
1396 self.assertTrue(os.path.exists(file2))
1397 file1_stat = os.stat(file1)
1398 file2_stat = os.stat(file2)
1399 self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
1400 for attr in 'st_atime', 'st_mtime':
1401 # The modification times may be truncated in the new file.
1402 self.assertLessEqual(getattr(file1_stat, attr),
1403 getattr(file2_stat, attr) + 1)
1404 if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
1405 self.assertEqual(getattr(file1_stat, 'st_flags'),
1406 getattr(file2_stat, 'st_flags'))
1407
1408 @os_helper.skip_unless_symlink
1409 def test_copy2_symlinks(self):
1410 tmp_dir = self.mkdtemp()
1411 src = os.path.join(tmp_dir, 'foo')
1412 dst = os.path.join(tmp_dir, 'bar')
1413 src_link = os.path.join(tmp_dir, 'baz')
1414 create_file(src, 'foo')
1415 os.symlink(src, src_link)
1416 if hasattr(os, 'lchmod'):
1417 os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
1418 if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
1419 os.lchflags(src_link, stat.UF_NODUMP)
1420 src_stat = os.stat(src)
1421 src_link_stat = os.lstat(src_link)
1422 # follow
1423 shutil.copy2(src_link, dst, follow_symlinks=True)
1424 self.assertFalse(os.path.islink(dst))
1425 self.assertEqual(read_file(src), read_file(dst))
1426 os.remove(dst)
1427 # don't follow
1428 shutil.copy2(src_link, dst, follow_symlinks=False)
1429 self.assertTrue(os.path.islink(dst))
1430 self.assertEqual(os.readlink(dst), os.readlink(src_link))
1431 dst_stat = os.lstat(dst)
1432 if os.utime in os.supports_follow_symlinks:
1433 for attr in 'st_atime', 'st_mtime':
1434 # The modification times may be truncated in the new file.
1435 self.assertLessEqual(getattr(src_link_stat, attr),
1436 getattr(dst_stat, attr) + 1)
1437 if hasattr(os, 'lchmod'):
1438 self.assertEqual(src_link_stat.st_mode, dst_stat.st_mode)
1439 self.assertNotEqual(src_stat.st_mode, dst_stat.st_mode)
1440 if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
1441 self.assertEqual(src_link_stat.st_flags, dst_stat.st_flags)
1442
1443 @os_helper.skip_unless_xattr
1444 def test_copy2_xattr(self):
1445 tmp_dir = self.mkdtemp()
1446 src = os.path.join(tmp_dir, 'foo')
1447 dst = os.path.join(tmp_dir, 'bar')
1448 create_file(src, 'foo')
1449 os.setxattr(src, 'user.foo', b'42')
1450 shutil.copy2(src, dst)
1451 self.assertEqual(
1452 os.getxattr(src, 'user.foo'),
1453 os.getxattr(dst, 'user.foo'))
1454 os.remove(dst)
1455
1456 def test_copy_return_value(self):
1457 # copy and copy2 both return their destination path.
1458 for fn in (shutil.copy, shutil.copy2):
1459 src_dir = self.mkdtemp()
1460 dst_dir = self.mkdtemp()
1461 src = os.path.join(src_dir, 'foo')
1462 create_file(src, 'foo')
1463 rv = fn(src, dst_dir)
1464 self.assertEqual(rv, os.path.join(dst_dir, 'foo'))
1465 rv = fn(src, os.path.join(dst_dir, 'bar'))
1466 self.assertEqual(rv, os.path.join(dst_dir, 'bar'))
1467
1468 def test_copy_dir(self):
1469 self._test_copy_dir(shutil.copy)
1470
1471 def test_copy2_dir(self):
1472 self._test_copy_dir(shutil.copy2)
1473
1474 def _test_copy_dir(self, copy_func):
1475 src_dir = self.mkdtemp()
1476 src_file = os.path.join(src_dir, 'foo')
1477 dir2 = self.mkdtemp()
1478 dst = os.path.join(src_dir, 'does_not_exist/')
1479 create_file(src_file, 'foo')
1480 if sys.platform == "win32":
1481 err = PermissionError
1482 else:
1483 err = IsADirectoryError
1484 self.assertRaises(err, copy_func, dir2, src_dir)
1485
1486 # raise *err* because of src rather than FileNotFoundError because of dst
1487 self.assertRaises(err, copy_func, dir2, dst)
1488 copy_func(src_file, dir2) # should not raise exceptions
1489
1490 ### shutil.copyfile
1491
1492 @os_helper.skip_unless_symlink
1493 def test_copyfile_symlinks(self):
1494 tmp_dir = self.mkdtemp()
1495 src = os.path.join(tmp_dir, 'src')
1496 dst = os.path.join(tmp_dir, 'dst')
1497 dst_link = os.path.join(tmp_dir, 'dst_link')
1498 link = os.path.join(tmp_dir, 'link')
1499 create_file(src, 'foo')
1500 os.symlink(src, link)
1501 # don't follow
1502 shutil.copyfile(link, dst_link, follow_symlinks=False)
1503 self.assertTrue(os.path.islink(dst_link))
1504 self.assertEqual(os.readlink(link), os.readlink(dst_link))
1505 # follow
1506 shutil.copyfile(link, dst)
1507 self.assertFalse(os.path.islink(dst))
1508
1509 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
1510 def test_dont_copy_file_onto_link_to_itself(self):
1511 # bug 851123.
1512 os.mkdir(TESTFN)
1513 src = os.path.join(TESTFN, 'cheese')
1514 dst = os.path.join(TESTFN, 'shop')
1515 try:
1516 create_file(src, 'cheddar')
1517 try:
1518 os.link(src, dst)
1519 except PermissionError as e:
1520 self.skipTest('os.link(): %s' % e)
1521 self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
1522 with open(src, 'r', encoding='utf-8') as f:
1523 self.assertEqual(f.read(), 'cheddar')
1524 os.remove(dst)
1525 finally:
1526 shutil.rmtree(TESTFN, ignore_errors=True)
1527
1528 @os_helper.skip_unless_symlink
1529 def test_dont_copy_file_onto_symlink_to_itself(self):
1530 # bug 851123.
1531 os.mkdir(TESTFN)
1532 src = os.path.join(TESTFN, 'cheese')
1533 dst = os.path.join(TESTFN, 'shop')
1534 try:
1535 create_file(src, 'cheddar')
1536 # Using `src` here would mean we end up with a symlink pointing
1537 # to TESTFN/TESTFN/cheese, while it should point at
1538 # TESTFN/cheese.
1539 os.symlink('cheese', dst)
1540 self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
1541 with open(src, 'r', encoding='utf-8') as f:
1542 self.assertEqual(f.read(), 'cheddar')
1543 os.remove(dst)
1544 finally:
1545 shutil.rmtree(TESTFN, ignore_errors=True)
1546
1547 # Issue #3002: copyfile and copytree block indefinitely on named pipes
1548 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
1549 @unittest.skipIf(sys.platform == "vxworks",
1550 "fifo requires special path on VxWorks")
1551 def test_copyfile_named_pipe(self):
1552 try:
1553 os.mkfifo(TESTFN)
1554 except PermissionError as e:
1555 self.skipTest('os.mkfifo(): %s' % e)
1556 try:
1557 self.assertRaises(shutil.SpecialFileError,
1558 shutil.copyfile, TESTFN, TESTFN2)
1559 self.assertRaises(shutil.SpecialFileError,
1560 shutil.copyfile, __file__, TESTFN)
1561 finally:
1562 os.remove(TESTFN)
1563
1564 def test_copyfile_return_value(self):
1565 # copytree returns its destination path.
1566 src_dir = self.mkdtemp()
1567 dst_dir = self.mkdtemp()
1568 dst_file = os.path.join(dst_dir, 'bar')
1569 src_file = os.path.join(src_dir, 'foo')
1570 create_file(src_file, 'foo')
1571 rv = shutil.copyfile(src_file, dst_file)
1572 self.assertTrue(os.path.exists(rv))
1573 self.assertEqual(read_file(src_file), read_file(dst_file))
1574
1575 def test_copyfile_same_file(self):
1576 # copyfile() should raise SameFileError if the source and destination
1577 # are the same.
1578 src_dir = self.mkdtemp()
1579 src_file = os.path.join(src_dir, 'foo')
1580 create_file(src_file, 'foo')
1581 self.assertRaises(SameFileError, shutil.copyfile, src_file, src_file)
1582 # But Error should work too, to stay backward compatible.
1583 self.assertRaises(Error, shutil.copyfile, src_file, src_file)
1584 # Make sure file is not corrupted.
1585 self.assertEqual(read_file(src_file), 'foo')
1586
1587 @unittest.skipIf(MACOS or SOLARIS or _winapi, 'On MACOS, Solaris and Windows the errors are not confusing (though different)')
1588 # gh-92670: The test uses a trailing slash to force the OS consider
1589 # the path as a directory, but on AIX the trailing slash has no effect
1590 # and is considered as a file.
1591 @unittest.skipIf(AIX, 'Not valid on AIX, see gh-92670')
1592 def test_copyfile_nonexistent_dir(self):
1593 # Issue 43219
1594 src_dir = self.mkdtemp()
1595 src_file = os.path.join(src_dir, 'foo')
1596 dst = os.path.join(src_dir, 'does_not_exist/')
1597 create_file(src_file, 'foo')
1598 self.assertRaises(FileNotFoundError, shutil.copyfile, src_file, dst)
1599
1600 def test_copyfile_copy_dir(self):
1601 # Issue 45234
1602 # test copy() and copyfile() raising proper exceptions when src and/or
1603 # dst are directories
1604 src_dir = self.mkdtemp()
1605 src_file = os.path.join(src_dir, 'foo')
1606 dir2 = self.mkdtemp()
1607 dst = os.path.join(src_dir, 'does_not_exist/')
1608 create_file(src_file, 'foo')
1609 if sys.platform == "win32":
1610 err = PermissionError
1611 else:
1612 err = IsADirectoryError
1613
1614 self.assertRaises(err, shutil.copyfile, src_dir, dst)
1615 self.assertRaises(err, shutil.copyfile, src_file, src_dir)
1616 self.assertRaises(err, shutil.copyfile, dir2, src_dir)
1617
1618
1619 class TestArchives(BaseTest, unittest.TestCase):
1620
1621 ### shutil.make_archive
1622
1623 def _tarinfo(self, path):
1624 with tarfile.open(path) as tar:
1625 names = tar.getnames()
1626 names.sort()
1627 return tuple(names)
1628
1629 def _create_files(self, base_dir='dist'):
1630 # creating something to tar
1631 root_dir = self.mkdtemp()
1632 dist = os.path.join(root_dir, base_dir)
1633 os.makedirs(dist, exist_ok=True)
1634 create_file((dist, 'file1'), 'xxx')
1635 create_file((dist, 'file2'), 'xxx')
1636 os.mkdir(os.path.join(dist, 'sub'))
1637 create_file((dist, 'sub', 'file3'), 'xxx')
1638 os.mkdir(os.path.join(dist, 'sub2'))
1639 if base_dir:
1640 create_file((root_dir, 'outer'), 'xxx')
1641 return root_dir, base_dir
1642
1643 @support.requires_zlib()
1644 def test_make_tarfile(self):
1645 root_dir, base_dir = self._create_files()
1646 # Test without base_dir.
1647 with os_helper.temp_cwd(), no_chdir:
1648 base_name = os.path.join('dst', 'archive')
1649 archive = make_archive(base_name, 'tar', root_dir)
1650 # check if the compressed tarball was created
1651 self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
1652 self.assertTrue(os.path.isfile(archive))
1653 self.assertTrue(tarfile.is_tarfile(archive))
1654 with tarfile.open(archive, 'r') as tf:
1655 self.assertCountEqual(tf.getnames(),
1656 ['.', './dist', './dist/sub', './dist/sub2',
1657 './dist/file1', './dist/file2', './dist/sub/file3',
1658 './outer'])
1659
1660 # Test with base_dir.
1661 with os_helper.temp_cwd(), no_chdir:
1662 base_name = os.path.join('dst2', 'archive')
1663 archive = make_archive(base_name, 'tar', root_dir, base_dir)
1664 self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
1665 # check if the uncompressed tarball was created
1666 self.assertTrue(os.path.isfile(archive))
1667 self.assertTrue(tarfile.is_tarfile(archive))
1668 with tarfile.open(archive, 'r') as tf:
1669 self.assertCountEqual(tf.getnames(),
1670 ['dist', 'dist/sub', 'dist/sub2',
1671 'dist/file1', 'dist/file2', 'dist/sub/file3'])
1672
1673 # Test with multi-component base_dir.
1674 with os_helper.temp_cwd(), no_chdir:
1675 base_name = os.path.join('dst3', 'archive')
1676 archive = make_archive(base_name, 'tar', root_dir,
1677 os.path.join(base_dir, 'sub'))
1678 self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
1679 self.assertTrue(os.path.isfile(archive))
1680 self.assertTrue(tarfile.is_tarfile(archive))
1681 with tarfile.open(archive, 'r') as tf:
1682 self.assertCountEqual(tf.getnames(),
1683 ['dist/sub', 'dist/sub/file3'])
1684
1685 @support.requires_zlib()
1686 def test_make_tarfile_without_rootdir(self):
1687 root_dir, base_dir = self._create_files()
1688 # Test without base_dir.
1689 base_name = os.path.join(self.mkdtemp(), 'dst', 'archive')
1690 base_name = os.path.relpath(base_name, root_dir)
1691 with os_helper.change_cwd(root_dir), no_chdir:
1692 archive = make_archive(base_name, 'gztar')
1693 self.assertEqual(archive, base_name + '.tar.gz')
1694 self.assertTrue(os.path.isfile(archive))
1695 self.assertTrue(tarfile.is_tarfile(archive))
1696 with tarfile.open(archive, 'r:gz') as tf:
1697 self.assertCountEqual(tf.getnames(),
1698 ['.', './dist', './dist/sub', './dist/sub2',
1699 './dist/file1', './dist/file2', './dist/sub/file3',
1700 './outer'])
1701
1702 # Test with base_dir.
1703 with os_helper.change_cwd(root_dir), no_chdir:
1704 base_name = os.path.join('dst', 'archive')
1705 archive = make_archive(base_name, 'tar', base_dir=base_dir)
1706 self.assertEqual(archive, base_name + '.tar')
1707 self.assertTrue(os.path.isfile(archive))
1708 self.assertTrue(tarfile.is_tarfile(archive))
1709 with tarfile.open(archive, 'r') as tf:
1710 self.assertCountEqual(tf.getnames(),
1711 ['dist', 'dist/sub', 'dist/sub2',
1712 'dist/file1', 'dist/file2', 'dist/sub/file3'])
1713
1714 def test_make_tarfile_with_explicit_curdir(self):
1715 # Test with base_dir=os.curdir.
1716 root_dir, base_dir = self._create_files()
1717 with os_helper.temp_cwd(), no_chdir:
1718 base_name = os.path.join('dst', 'archive')
1719 archive = make_archive(base_name, 'tar', root_dir, os.curdir)
1720 self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
1721 self.assertTrue(os.path.isfile(archive))
1722 self.assertTrue(tarfile.is_tarfile(archive))
1723 with tarfile.open(archive, 'r') as tf:
1724 self.assertCountEqual(tf.getnames(),
1725 ['.', './dist', './dist/sub', './dist/sub2',
1726 './dist/file1', './dist/file2', './dist/sub/file3',
1727 './outer'])
1728
1729 @support.requires_zlib()
1730 @unittest.skipUnless(shutil.which('tar'),
1731 'Need the tar command to run')
1732 def test_tarfile_vs_tar(self):
1733 root_dir, base_dir = self._create_files()
1734 base_name = os.path.join(self.mkdtemp(), 'archive')
1735 with no_chdir:
1736 tarball = make_archive(base_name, 'gztar', root_dir, base_dir)
1737
1738 # check if the compressed tarball was created
1739 self.assertEqual(tarball, base_name + '.tar.gz')
1740 self.assertTrue(os.path.isfile(tarball))
1741
1742 # now create another tarball using `tar`
1743 tarball2 = os.path.join(root_dir, 'archive2.tar')
1744 tar_cmd = ['tar', '-cf', 'archive2.tar', base_dir]
1745 if sys.platform == 'darwin':
1746 # macOS tar can include extended attributes,
1747 # ACLs and other mac specific metadata into the
1748 # archive (an recentish version of the OS).
1749 #
1750 # This feature can be disabled with the
1751 # '--no-mac-metadata' option on macOS 11 or
1752 # later.
1753 import platform
1754 if int(platform.mac_ver()[0].split('.')[0]) >= 11:
1755 tar_cmd.insert(1, '--no-mac-metadata')
1756 subprocess.check_call(tar_cmd, cwd=root_dir,
1757 stdout=subprocess.DEVNULL)
1758
1759 self.assertTrue(os.path.isfile(tarball2))
1760 # let's compare both tarballs
1761 self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
1762
1763 # trying an uncompressed one
1764 with no_chdir:
1765 tarball = make_archive(base_name, 'tar', root_dir, base_dir)
1766 self.assertEqual(tarball, base_name + '.tar')
1767 self.assertTrue(os.path.isfile(tarball))
1768
1769 # now for a dry_run
1770 with no_chdir:
1771 tarball = make_archive(base_name, 'tar', root_dir, base_dir,
1772 dry_run=True)
1773 self.assertEqual(tarball, base_name + '.tar')
1774 self.assertTrue(os.path.isfile(tarball))
1775
1776 @support.requires_zlib()
1777 def test_make_zipfile(self):
1778 root_dir, base_dir = self._create_files()
1779 # Test without base_dir.
1780 with os_helper.temp_cwd(), no_chdir:
1781 base_name = os.path.join('dst', 'archive')
1782 archive = make_archive(base_name, 'zip', root_dir)
1783 self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
1784 self.assertTrue(os.path.isfile(archive))
1785 self.assertTrue(zipfile.is_zipfile(archive))
1786 with zipfile.ZipFile(archive) as zf:
1787 self.assertCountEqual(zf.namelist(),
1788 ['dist/', 'dist/sub/', 'dist/sub2/',
1789 'dist/file1', 'dist/file2', 'dist/sub/file3',
1790 'outer'])
1791
1792 # Test with base_dir.
1793 with os_helper.temp_cwd(), no_chdir:
1794 base_name = os.path.join('dst2', 'archive')
1795 archive = make_archive(base_name, 'zip', root_dir, base_dir)
1796 self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
1797 self.assertTrue(os.path.isfile(archive))
1798 self.assertTrue(zipfile.is_zipfile(archive))
1799 with zipfile.ZipFile(archive) as zf:
1800 self.assertCountEqual(zf.namelist(),
1801 ['dist/', 'dist/sub/', 'dist/sub2/',
1802 'dist/file1', 'dist/file2', 'dist/sub/file3'])
1803
1804 # Test with multi-component base_dir.
1805 with os_helper.temp_cwd(), no_chdir:
1806 base_name = os.path.join('dst3', 'archive')
1807 archive = make_archive(base_name, 'zip', root_dir,
1808 os.path.join(base_dir, 'sub'))
1809 self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
1810 self.assertTrue(os.path.isfile(archive))
1811 self.assertTrue(zipfile.is_zipfile(archive))
1812 with zipfile.ZipFile(archive) as zf:
1813 self.assertCountEqual(zf.namelist(),
1814 ['dist/sub/', 'dist/sub/file3'])
1815
1816 @support.requires_zlib()
1817 def test_make_zipfile_without_rootdir(self):
1818 root_dir, base_dir = self._create_files()
1819 # Test without base_dir.
1820 base_name = os.path.join(self.mkdtemp(), 'dst', 'archive')
1821 base_name = os.path.relpath(base_name, root_dir)
1822 with os_helper.change_cwd(root_dir), no_chdir:
1823 archive = make_archive(base_name, 'zip')
1824 self.assertEqual(archive, base_name + '.zip')
1825 self.assertTrue(os.path.isfile(archive))
1826 self.assertTrue(zipfile.is_zipfile(archive))
1827 with zipfile.ZipFile(archive) as zf:
1828 self.assertCountEqual(zf.namelist(),
1829 ['dist/', 'dist/sub/', 'dist/sub2/',
1830 'dist/file1', 'dist/file2', 'dist/sub/file3',
1831 'outer'])
1832
1833 # Test with base_dir.
1834 root_dir, base_dir = self._create_files()
1835 with os_helper.change_cwd(root_dir), no_chdir:
1836 base_name = os.path.join('dst', 'archive')
1837 archive = make_archive(base_name, 'zip', base_dir=base_dir)
1838 self.assertEqual(archive, base_name + '.zip')
1839 self.assertTrue(os.path.isfile(archive))
1840 self.assertTrue(zipfile.is_zipfile(archive))
1841 with zipfile.ZipFile(archive) as zf:
1842 self.assertCountEqual(zf.namelist(),
1843 ['dist/', 'dist/sub/', 'dist/sub2/',
1844 'dist/file1', 'dist/file2', 'dist/sub/file3'])
1845
1846 @support.requires_zlib()
1847 def test_make_zipfile_with_explicit_curdir(self):
1848 # Test with base_dir=os.curdir.
1849 root_dir, base_dir = self._create_files()
1850 with os_helper.temp_cwd(), no_chdir:
1851 base_name = os.path.join('dst', 'archive')
1852 archive = make_archive(base_name, 'zip', root_dir, os.curdir)
1853 self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
1854 self.assertTrue(os.path.isfile(archive))
1855 self.assertTrue(zipfile.is_zipfile(archive))
1856 with zipfile.ZipFile(archive) as zf:
1857 self.assertCountEqual(zf.namelist(),
1858 ['dist/', 'dist/sub/', 'dist/sub2/',
1859 'dist/file1', 'dist/file2', 'dist/sub/file3',
1860 'outer'])
1861
1862 @support.requires_zlib()
1863 @unittest.skipUnless(shutil.which('zip'),
1864 'Need the zip command to run')
1865 def test_zipfile_vs_zip(self):
1866 root_dir, base_dir = self._create_files()
1867 base_name = os.path.join(self.mkdtemp(), 'archive')
1868 with no_chdir:
1869 archive = make_archive(base_name, 'zip', root_dir, base_dir)
1870
1871 # check if ZIP file was created
1872 self.assertEqual(archive, base_name + '.zip')
1873 self.assertTrue(os.path.isfile(archive))
1874
1875 # now create another ZIP file using `zip`
1876 archive2 = os.path.join(root_dir, 'archive2.zip')
1877 zip_cmd = ['zip', '-q', '-r', 'archive2.zip', base_dir]
1878 subprocess.check_call(zip_cmd, cwd=root_dir,
1879 stdout=subprocess.DEVNULL)
1880
1881 self.assertTrue(os.path.isfile(archive2))
1882 # let's compare both ZIP files
1883 with zipfile.ZipFile(archive) as zf:
1884 names = zf.namelist()
1885 with zipfile.ZipFile(archive2) as zf:
1886 names2 = zf.namelist()
1887 self.assertEqual(sorted(names), sorted(names2))
1888
1889 @support.requires_zlib()
1890 @unittest.skipUnless(shutil.which('unzip'),
1891 'Need the unzip command to run')
1892 def test_unzip_zipfile(self):
1893 root_dir, base_dir = self._create_files()
1894 base_name = os.path.join(self.mkdtemp(), 'archive')
1895 with no_chdir:
1896 archive = make_archive(base_name, 'zip', root_dir, base_dir)
1897
1898 # check if ZIP file was created
1899 self.assertEqual(archive, base_name + '.zip')
1900 self.assertTrue(os.path.isfile(archive))
1901
1902 # now check the ZIP file using `unzip -t`
1903 zip_cmd = ['unzip', '-t', archive]
1904 with os_helper.change_cwd(root_dir):
1905 try:
1906 subprocess.check_output(zip_cmd, stderr=subprocess.STDOUT)
1907 except subprocess.CalledProcessError as exc:
1908 details = exc.output.decode(errors="replace")
1909 if any(message in details for message in [
1910 'unrecognized option: t', # BusyBox
1911 'invalid option -- t', # Android
1912 ]):
1913 self.skipTest("unzip doesn't support -t")
1914 msg = "{}\n\n**Unzip Output**\n{}"
1915 self.fail(msg.format(exc, details))
1916
1917 def test_make_archive(self):
1918 tmpdir = self.mkdtemp()
1919 base_name = os.path.join(tmpdir, 'archive')
1920 self.assertRaises(ValueError, make_archive, base_name, 'xxx')
1921
1922 @support.requires_zlib()
1923 def test_make_archive_owner_group(self):
1924 # testing make_archive with owner and group, with various combinations
1925 # this works even if there's not gid/uid support
1926 if UID_GID_SUPPORT:
1927 group = grp.getgrgid(0)[0]
1928 owner = pwd.getpwuid(0)[0]
1929 else:
1930 group = owner = 'root'
1931
1932 root_dir, base_dir = self._create_files()
1933 base_name = os.path.join(self.mkdtemp(), 'archive')
1934 res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
1935 group=group)
1936 self.assertTrue(os.path.isfile(res))
1937
1938 res = make_archive(base_name, 'zip', root_dir, base_dir)
1939 self.assertTrue(os.path.isfile(res))
1940
1941 res = make_archive(base_name, 'tar', root_dir, base_dir,
1942 owner=owner, group=group)
1943 self.assertTrue(os.path.isfile(res))
1944
1945 res = make_archive(base_name, 'tar', root_dir, base_dir,
1946 owner='kjhkjhkjg', group='oihohoh')
1947 self.assertTrue(os.path.isfile(res))
1948
1949
1950 @support.requires_zlib()
1951 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
1952 def test_tarfile_root_owner(self):
1953 root_dir, base_dir = self._create_files()
1954 base_name = os.path.join(self.mkdtemp(), 'archive')
1955 group = grp.getgrgid(0)[0]
1956 owner = pwd.getpwuid(0)[0]
1957 with os_helper.change_cwd(root_dir), no_chdir:
1958 archive_name = make_archive(base_name, 'gztar', root_dir, 'dist',
1959 owner=owner, group=group)
1960
1961 # check if the compressed tarball was created
1962 self.assertTrue(os.path.isfile(archive_name))
1963
1964 # now checks the rights
1965 archive = tarfile.open(archive_name)
1966 try:
1967 for member in archive.getmembers():
1968 self.assertEqual(member.uid, 0)
1969 self.assertEqual(member.gid, 0)
1970 finally:
1971 archive.close()
1972
1973 def test_make_archive_cwd_default(self):
1974 current_dir = os.getcwd()
1975 def archiver(base_name, base_dir, **kw):
1976 self.assertNotIn('root_dir', kw)
1977 self.assertEqual(base_name, 'basename')
1978 self.assertEqual(os.getcwd(), current_dir)
1979 raise RuntimeError()
1980
1981 register_archive_format('xxx', archiver, [], 'xxx file')
1982 try:
1983 with no_chdir:
1984 with self.assertRaises(RuntimeError):
1985 make_archive('basename', 'xxx')
1986 self.assertEqual(os.getcwd(), current_dir)
1987 finally:
1988 unregister_archive_format('xxx')
1989
1990 def test_make_archive_cwd(self):
1991 current_dir = os.getcwd()
1992 root_dir = self.mkdtemp()
1993 def archiver(base_name, base_dir, **kw):
1994 self.assertNotIn('root_dir', kw)
1995 self.assertEqual(base_name, os.path.join(current_dir, 'basename'))
1996 self.assertEqual(os.getcwd(), root_dir)
1997 raise RuntimeError()
1998 dirs = []
1999 def _chdir(path):
2000 dirs.append(path)
2001 orig_chdir(path)
2002
2003 register_archive_format('xxx', archiver, [], 'xxx file')
2004 try:
2005 with support.swap_attr(os, 'chdir', _chdir) as orig_chdir:
2006 with self.assertRaises(RuntimeError):
2007 make_archive('basename', 'xxx', root_dir=root_dir)
2008 self.assertEqual(os.getcwd(), current_dir)
2009 self.assertEqual(dirs, [root_dir, current_dir])
2010 finally:
2011 unregister_archive_format('xxx')
2012
2013 def test_make_archive_cwd_supports_root_dir(self):
2014 current_dir = os.getcwd()
2015 root_dir = self.mkdtemp()
2016 def archiver(base_name, base_dir, **kw):
2017 self.assertEqual(base_name, 'basename')
2018 self.assertEqual(kw['root_dir'], root_dir)
2019 self.assertEqual(os.getcwd(), current_dir)
2020 raise RuntimeError()
2021 archiver.supports_root_dir = True
2022
2023 register_archive_format('xxx', archiver, [], 'xxx file')
2024 try:
2025 with no_chdir:
2026 with self.assertRaises(RuntimeError):
2027 make_archive('basename', 'xxx', root_dir=root_dir)
2028 self.assertEqual(os.getcwd(), current_dir)
2029 finally:
2030 unregister_archive_format('xxx')
2031
2032 def test_make_tarfile_in_curdir(self):
2033 # Issue #21280: Test with the archive in the current directory.
2034 root_dir = self.mkdtemp()
2035 with os_helper.change_cwd(root_dir), no_chdir:
2036 # root_dir must be None, so the archive path is relative.
2037 self.assertEqual(make_archive('test', 'tar'), 'test.tar')
2038 self.assertTrue(os.path.isfile('test.tar'))
2039
2040 @support.requires_zlib()
2041 def test_make_zipfile_in_curdir(self):
2042 # Issue #21280: Test with the archive in the current directory.
2043 root_dir = self.mkdtemp()
2044 with os_helper.change_cwd(root_dir), no_chdir:
2045 # root_dir must be None, so the archive path is relative.
2046 self.assertEqual(make_archive('test', 'zip'), 'test.zip')
2047 self.assertTrue(os.path.isfile('test.zip'))
2048
2049 def test_register_archive_format(self):
2050
2051 self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
2052 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
2053 1)
2054 self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
2055 [(1, 2), (1, 2, 3)])
2056
2057 register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
2058 formats = [name for name, params in get_archive_formats()]
2059 self.assertIn('xxx', formats)
2060
2061 unregister_archive_format('xxx')
2062 formats = [name for name, params in get_archive_formats()]
2063 self.assertNotIn('xxx', formats)
2064
2065 def test_make_tarfile_rootdir_nodir(self):
2066 # GH-99203: Test with root_dir is not a real directory.
2067 self.addCleanup(os_helper.unlink, f'{TESTFN}.tar')
2068 for dry_run in (False, True):
2069 with self.subTest(dry_run=dry_run):
2070 # root_dir does not exist.
2071 tmp_dir = self.mkdtemp()
2072 nonexisting_file = os.path.join(tmp_dir, 'nonexisting')
2073 with self.assertRaises(FileNotFoundError) as cm:
2074 make_archive(TESTFN, 'tar', nonexisting_file, dry_run=dry_run)
2075 self.assertEqual(cm.exception.errno, errno.ENOENT)
2076 self.assertEqual(cm.exception.filename, nonexisting_file)
2077 self.assertFalse(os.path.exists(f'{TESTFN}.tar'))
2078
2079 # root_dir is a file.
2080 tmp_fd, tmp_file = tempfile.mkstemp(dir=tmp_dir)
2081 os.close(tmp_fd)
2082 with self.assertRaises(NotADirectoryError) as cm:
2083 make_archive(TESTFN, 'tar', tmp_file, dry_run=dry_run)
2084 self.assertEqual(cm.exception.errno, errno.ENOTDIR)
2085 self.assertEqual(cm.exception.filename, tmp_file)
2086 self.assertFalse(os.path.exists(f'{TESTFN}.tar'))
2087
2088 @support.requires_zlib()
2089 def test_make_zipfile_rootdir_nodir(self):
2090 # GH-99203: Test with root_dir is not a real directory.
2091 self.addCleanup(os_helper.unlink, f'{TESTFN}.zip')
2092 for dry_run in (False, True):
2093 with self.subTest(dry_run=dry_run):
2094 # root_dir does not exist.
2095 tmp_dir = self.mkdtemp()
2096 nonexisting_file = os.path.join(tmp_dir, 'nonexisting')
2097 with self.assertRaises(FileNotFoundError) as cm:
2098 make_archive(TESTFN, 'zip', nonexisting_file, dry_run=dry_run)
2099 self.assertEqual(cm.exception.errno, errno.ENOENT)
2100 self.assertEqual(cm.exception.filename, nonexisting_file)
2101 self.assertFalse(os.path.exists(f'{TESTFN}.zip'))
2102
2103 # root_dir is a file.
2104 tmp_fd, tmp_file = tempfile.mkstemp(dir=tmp_dir)
2105 os.close(tmp_fd)
2106 with self.assertRaises(NotADirectoryError) as cm:
2107 make_archive(TESTFN, 'zip', tmp_file, dry_run=dry_run)
2108 self.assertEqual(cm.exception.errno, errno.ENOTDIR)
2109 self.assertEqual(cm.exception.filename, tmp_file)
2110 self.assertFalse(os.path.exists(f'{TESTFN}.zip'))
2111
2112 ### shutil.unpack_archive
2113
2114 def check_unpack_archive(self, format, **kwargs):
2115 self.check_unpack_archive_with_converter(
2116 format, lambda path: path, **kwargs)
2117 self.check_unpack_archive_with_converter(
2118 format, FakePath, **kwargs)
2119 self.check_unpack_archive_with_converter(format, FakePath, **kwargs)
2120
2121 def check_unpack_archive_with_converter(self, format, converter, **kwargs):
2122 root_dir, base_dir = self._create_files()
2123 expected = rlistdir(root_dir)
2124 expected.remove('outer')
2125
2126 base_name = os.path.join(self.mkdtemp(), 'archive')
2127 filename = make_archive(base_name, format, root_dir, base_dir)
2128
2129 # let's try to unpack it now
2130 tmpdir2 = self.mkdtemp()
2131 unpack_archive(converter(filename), converter(tmpdir2), **kwargs)
2132 self.assertEqual(rlistdir(tmpdir2), expected)
2133
2134 # and again, this time with the format specified
2135 tmpdir3 = self.mkdtemp()
2136 unpack_archive(converter(filename), converter(tmpdir3), format=format,
2137 **kwargs)
2138 self.assertEqual(rlistdir(tmpdir3), expected)
2139
2140 with self.assertRaises(shutil.ReadError):
2141 unpack_archive(converter(TESTFN), **kwargs)
2142 with self.assertRaises(ValueError):
2143 unpack_archive(converter(TESTFN), format='xxx', **kwargs)
2144
2145 def check_unpack_tarball(self, format):
2146 self.check_unpack_archive(format, filter='fully_trusted')
2147 self.check_unpack_archive(format, filter='data')
2148 with warnings_helper.check_warnings(
2149 ('Python 3.14', DeprecationWarning)):
2150 self.check_unpack_archive(format)
2151
2152 def test_unpack_archive_tar(self):
2153 self.check_unpack_tarball('tar')
2154
2155 @support.requires_zlib()
2156 def test_unpack_archive_gztar(self):
2157 self.check_unpack_tarball('gztar')
2158
2159 @support.requires_bz2()
2160 def test_unpack_archive_bztar(self):
2161 self.check_unpack_tarball('bztar')
2162
2163 @support.requires_lzma()
2164 @unittest.skipIf(AIX and not _maxdataOK(), "AIX MAXDATA must be 0x20000000 or larger")
2165 def test_unpack_archive_xztar(self):
2166 self.check_unpack_tarball('xztar')
2167
2168 @support.requires_zlib()
2169 def test_unpack_archive_zip(self):
2170 self.check_unpack_archive('zip')
2171 with self.assertRaises(TypeError):
2172 self.check_unpack_archive('zip', filter='data')
2173
2174 def test_unpack_registry(self):
2175
2176 formats = get_unpack_formats()
2177
2178 def _boo(filename, extract_dir, extra):
2179 self.assertEqual(extra, 1)
2180 self.assertEqual(filename, 'stuff.boo')
2181 self.assertEqual(extract_dir, 'xx')
2182
2183 register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
2184 unpack_archive('stuff.boo', 'xx')
2185
2186 # trying to register a .boo unpacker again
2187 self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
2188 ['.boo'], _boo)
2189
2190 # should work now
2191 unregister_unpack_format('Boo')
2192 register_unpack_format('Boo2', ['.boo'], _boo)
2193 self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
2194 self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
2195
2196 # let's leave a clean state
2197 unregister_unpack_format('Boo2')
2198 self.assertEqual(get_unpack_formats(), formats)
2199
2200
2201 class TestMisc(BaseTest, unittest.TestCase):
2202
2203 @unittest.skipUnless(hasattr(shutil, 'disk_usage'),
2204 "disk_usage not available on this platform")
2205 def test_disk_usage(self):
2206 usage = shutil.disk_usage(os.path.dirname(__file__))
2207 for attr in ('total', 'used', 'free'):
2208 self.assertIsInstance(getattr(usage, attr), int)
2209 self.assertGreater(usage.total, 0)
2210 self.assertGreater(usage.used, 0)
2211 self.assertGreaterEqual(usage.free, 0)
2212 self.assertGreaterEqual(usage.total, usage.used)
2213 self.assertGreater(usage.total, usage.free)
2214
2215 # bpo-32557: Check that disk_usage() also accepts a filename
2216 shutil.disk_usage(__file__)
2217
2218 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
2219 @unittest.skipUnless(hasattr(os, 'chown'), 'requires os.chown')
2220 def test_chown(self):
2221 dirname = self.mkdtemp()
2222 filename = tempfile.mktemp(dir=dirname)
2223 linkname = os.path.join(dirname, "chown_link")
2224 create_file(filename, 'testing chown function')
2225 os.symlink(filename, linkname)
2226
2227 with self.assertRaises(ValueError):
2228 shutil.chown(filename)
2229
2230 with self.assertRaises(LookupError):
2231 shutil.chown(filename, user='non-existing username')
2232
2233 with self.assertRaises(LookupError):
2234 shutil.chown(filename, group='non-existing groupname')
2235
2236 with self.assertRaises(TypeError):
2237 shutil.chown(filename, b'spam')
2238
2239 with self.assertRaises(TypeError):
2240 shutil.chown(filename, 3.14)
2241
2242 uid = os.getuid()
2243 gid = os.getgid()
2244
2245 def check_chown(path, uid=None, gid=None):
2246 s = os.stat(path)
2247 if uid is not None:
2248 self.assertEqual(uid, s.st_uid)
2249 if gid is not None:
2250 self.assertEqual(gid, s.st_gid)
2251
2252 shutil.chown(filename, uid, gid)
2253 check_chown(filename, uid, gid)
2254 shutil.chown(filename, uid)
2255 check_chown(filename, uid)
2256 shutil.chown(filename, user=uid)
2257 check_chown(filename, uid)
2258 shutil.chown(filename, group=gid)
2259 check_chown(filename, gid=gid)
2260
2261 shutil.chown(dirname, uid, gid)
2262 check_chown(dirname, uid, gid)
2263 shutil.chown(dirname, uid)
2264 check_chown(dirname, uid)
2265 shutil.chown(dirname, user=uid)
2266 check_chown(dirname, uid)
2267 shutil.chown(dirname, group=gid)
2268 check_chown(dirname, gid=gid)
2269
2270 try:
2271 user = pwd.getpwuid(uid)[0]
2272 group = grp.getgrgid(gid)[0]
2273 except KeyError:
2274 # On some systems uid/gid cannot be resolved.
2275 pass
2276 else:
2277 shutil.chown(filename, user, group)
2278 check_chown(filename, uid, gid)
2279 shutil.chown(dirname, user, group)
2280 check_chown(dirname, uid, gid)
2281
2282 dirfd = os.open(dirname, os.O_RDONLY)
2283 self.addCleanup(os.close, dirfd)
2284 basename = os.path.basename(filename)
2285 baselinkname = os.path.basename(linkname)
2286 shutil.chown(basename, uid, gid, dir_fd=dirfd)
2287 check_chown(filename, uid, gid)
2288 shutil.chown(basename, uid, dir_fd=dirfd)
2289 check_chown(filename, uid)
2290 shutil.chown(basename, group=gid, dir_fd=dirfd)
2291 check_chown(filename, gid=gid)
2292 shutil.chown(basename, uid, gid, dir_fd=dirfd, follow_symlinks=True)
2293 check_chown(filename, uid, gid)
2294 shutil.chown(basename, uid, gid, dir_fd=dirfd, follow_symlinks=False)
2295 check_chown(filename, uid, gid)
2296 shutil.chown(linkname, uid, follow_symlinks=True)
2297 check_chown(filename, uid)
2298 shutil.chown(baselinkname, group=gid, dir_fd=dirfd, follow_symlinks=False)
2299 check_chown(filename, gid=gid)
2300 shutil.chown(baselinkname, uid, gid, dir_fd=dirfd, follow_symlinks=True)
2301 check_chown(filename, uid, gid)
2302
2303 with self.assertRaises(TypeError):
2304 shutil.chown(filename, uid, dir_fd=dirname)
2305
2306 with self.assertRaises(FileNotFoundError):
2307 shutil.chown('missingfile', uid, gid, dir_fd=dirfd)
2308
2309 with self.assertRaises(ValueError):
2310 shutil.chown(filename, dir_fd=dirfd)
2311
2312
2313 @support.requires_subprocess()
2314 class TestWhich(BaseTest, unittest.TestCase):
2315
2316 def setUp(self):
2317 temp_dir = self.mkdtemp(prefix="Tmp")
2318 base_dir = os.path.join(temp_dir, TESTFN + '-basedir')
2319 os.mkdir(base_dir)
2320 self.dir = os.path.join(base_dir, TESTFN + '-dir')
2321 os.mkdir(self.dir)
2322 self.other_dir = os.path.join(base_dir, TESTFN + '-dir2')
2323 os.mkdir(self.other_dir)
2324 # Give the temp_file an ".exe" suffix for all.
2325 # It's needed on Windows and not harmful on other platforms.
2326 self.file = TESTFN + '.Exe'
2327 self.filepath = os.path.join(self.dir, self.file)
2328 self.create_file(self.filepath)
2329 self.env_path = self.dir
2330 self.curdir = os.curdir
2331 self.ext = ".EXE"
2332
2333 to_text_type = staticmethod(os.fsdecode)
2334
2335 def create_file(self, path):
2336 create_file(path)
2337 os.chmod(path, 0o755)
2338
2339 def assertNormEqual(self, actual, expected):
2340 self.assertEqual(os.path.normcase(actual), os.path.normcase(expected))
2341
2342 def test_basic(self):
2343 # Given an EXE in a directory, it should be returned.
2344 rv = shutil.which(self.file, path=self.dir)
2345 self.assertEqual(rv, self.filepath)
2346
2347 def test_absolute_cmd(self):
2348 # When given the fully qualified path to an executable that exists,
2349 # it should be returned.
2350 rv = shutil.which(self.filepath, path=self.other_dir)
2351 self.assertEqual(rv, self.filepath)
2352
2353 def test_relative_cmd(self):
2354 # When given the relative path with a directory part to an executable
2355 # that exists, it should be returned.
2356 base_dir, tail_dir = os.path.split(self.dir)
2357 relpath = os.path.join(tail_dir, self.file)
2358 with os_helper.change_cwd(path=base_dir):
2359 rv = shutil.which(relpath, path=self.other_dir)
2360 self.assertEqual(rv, relpath)
2361 # But it shouldn't be searched in PATH directories (issue #16957).
2362 with os_helper.change_cwd(path=self.dir):
2363 rv = shutil.which(relpath, path=base_dir)
2364 self.assertIsNone(rv)
2365
2366 @unittest.skipUnless(sys.platform != "win32",
2367 "test is for non win32")
2368 def test_cwd_non_win32(self):
2369 # Issue #16957
2370 with os_helper.change_cwd(path=self.dir):
2371 rv = shutil.which(self.file, path=self.other_dir)
2372 # non-win32: shouldn't match in the current directory.
2373 self.assertIsNone(rv)
2374
2375 @unittest.skipUnless(sys.platform == "win32",
2376 "test is for win32")
2377 def test_cwd_win32(self):
2378 base_dir = os.path.dirname(self.dir)
2379 with os_helper.change_cwd(path=self.dir):
2380 with unittest.mock.patch('shutil._win_path_needs_curdir', return_value=True):
2381 rv = shutil.which(self.file, path=self.other_dir)
2382 # Current directory implicitly on PATH
2383 self.assertEqual(rv, os.path.join(self.curdir, self.file))
2384 with unittest.mock.patch('shutil._win_path_needs_curdir', return_value=False):
2385 rv = shutil.which(self.file, path=self.other_dir)
2386 # Current directory not on PATH
2387 self.assertIsNone(rv)
2388
2389 @unittest.skipUnless(sys.platform == "win32",
2390 "test is for win32")
2391 def test_cwd_win32_added_before_all_other_path(self):
2392 other_file_path = os.path.join(self.other_dir, self.file)
2393 self.create_file(other_file_path)
2394 with unittest.mock.patch('shutil._win_path_needs_curdir', return_value=True):
2395 with os_helper.change_cwd(path=self.dir):
2396 rv = shutil.which(self.file, path=self.other_dir)
2397 self.assertEqual(rv, os.path.join(self.curdir, self.file))
2398 with os_helper.change_cwd(path=self.other_dir):
2399 rv = shutil.which(self.file, path=self.dir)
2400 self.assertEqual(rv, os.path.join(self.curdir, self.file))
2401
2402 @os_helper.skip_if_dac_override
2403 def test_non_matching_mode(self):
2404 # Set the file read-only and ask for writeable files.
2405 os.chmod(self.filepath, stat.S_IREAD)
2406 if os.access(self.filepath, os.W_OK):
2407 self.skipTest("can't set the file read-only")
2408 rv = shutil.which(self.file, path=self.dir, mode=os.W_OK)
2409 self.assertIsNone(rv)
2410
2411 def test_relative_path(self):
2412 base_dir, tail_dir = os.path.split(self.dir)
2413 with os_helper.change_cwd(path=base_dir):
2414 rv = shutil.which(self.file, path=tail_dir)
2415 self.assertEqual(rv, os.path.join(tail_dir, self.file))
2416
2417 def test_nonexistent_file(self):
2418 # Return None when no matching executable file is found on the path.
2419 rv = shutil.which("foo.exe", path=self.dir)
2420 self.assertIsNone(rv)
2421
2422 @unittest.skipUnless(sys.platform == "win32",
2423 "pathext check is Windows-only")
2424 def test_pathext_checking(self):
2425 # Ask for the file without the ".exe" extension, then ensure that
2426 # it gets found properly with the extension.
2427 rv = shutil.which(self.file[:-4], path=self.dir)
2428 self.assertEqual(rv, self.filepath[:-4] + self.ext)
2429
2430 def test_environ_path(self):
2431 with os_helper.EnvironmentVarGuard() as env:
2432 env['PATH'] = self.env_path
2433 rv = shutil.which(self.file)
2434 self.assertEqual(rv, self.filepath)
2435
2436 def test_environ_path_empty(self):
2437 # PATH='': no match
2438 with os_helper.EnvironmentVarGuard() as env:
2439 env['PATH'] = ''
2440 with unittest.mock.patch('os.confstr', return_value=self.dir, \
2441 create=True), \
2442 support.swap_attr(os, 'defpath', self.dir), \
2443 os_helper.change_cwd(self.dir):
2444 rv = shutil.which(self.file)
2445 self.assertIsNone(rv)
2446
2447 def test_environ_path_cwd(self):
2448 expected_cwd = self.file
2449 if sys.platform == "win32":
2450 expected_cwd = os.path.join(self.curdir, expected_cwd)
2451
2452 # PATH=':': explicitly looks in the current directory
2453 with os_helper.EnvironmentVarGuard() as env:
2454 env['PATH'] = os.pathsep
2455 with unittest.mock.patch('os.confstr', return_value=self.dir, \
2456 create=True), \
2457 support.swap_attr(os, 'defpath', self.dir):
2458 rv = shutil.which(self.file)
2459 self.assertIsNone(rv)
2460
2461 # look in current directory
2462 with os_helper.change_cwd(self.dir):
2463 rv = shutil.which(self.file)
2464 self.assertEqual(rv, expected_cwd)
2465
2466 def test_environ_path_missing(self):
2467 with os_helper.EnvironmentVarGuard() as env:
2468 del env['PATH']
2469
2470 # without confstr
2471 with unittest.mock.patch('os.confstr', side_effect=ValueError, \
2472 create=True), \
2473 support.swap_attr(os, 'defpath', self.dir):
2474 rv = shutil.which(self.file)
2475 self.assertEqual(rv, self.filepath)
2476
2477 # with confstr
2478 with unittest.mock.patch('os.confstr', return_value=self.dir, \
2479 create=True), \
2480 support.swap_attr(os, 'defpath', ''):
2481 rv = shutil.which(self.file)
2482 self.assertEqual(rv, self.filepath)
2483
2484 def test_empty_path(self):
2485 base_dir = os.path.dirname(self.dir)
2486 with os_helper.change_cwd(path=self.dir), \
2487 os_helper.EnvironmentVarGuard() as env:
2488 env['PATH'] = self.env_path
2489 rv = shutil.which(self.file, path='')
2490 self.assertIsNone(rv)
2491
2492 def test_empty_path_no_PATH(self):
2493 with os_helper.EnvironmentVarGuard() as env:
2494 del env['PATH']
2495 rv = shutil.which(self.file)
2496 self.assertIsNone(rv)
2497
2498 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2499 def test_pathext(self):
2500 ext = '.xyz'
2501 cmd = self.to_text_type(TESTFN2)
2502 cmdext = cmd + self.to_text_type(ext)
2503 filepath = os.path.join(self.dir, cmdext)
2504 self.create_file(filepath)
2505 with os_helper.EnvironmentVarGuard() as env:
2506 env['PATHEXT'] = ext
2507 self.assertEqual(shutil.which(cmd, path=self.dir), filepath)
2508 self.assertEqual(shutil.which(cmdext, path=self.dir), filepath)
2509
2510 # Issue 40592: See https://bugs.python.org/issue40592
2511 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2512 def test_pathext_with_empty_str(self):
2513 ext = '.xyz'
2514 cmd = self.to_text_type(TESTFN2)
2515 cmdext = cmd + self.to_text_type(ext)
2516 filepath = os.path.join(self.dir, cmdext)
2517 self.create_file(filepath)
2518 with os_helper.EnvironmentVarGuard() as env:
2519 env['PATHEXT'] = ext + ';' # note the ;
2520 self.assertEqual(shutil.which(cmd, path=self.dir), filepath)
2521 self.assertEqual(shutil.which(cmdext, path=self.dir), filepath)
2522
2523 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2524 def test_pathext_with_multidot_extension(self):
2525 ext = '.foo.bar'
2526 cmd = self.to_text_type(TESTFN2)
2527 cmdext = cmd + self.to_text_type(ext)
2528 filepath = os.path.join(self.dir, cmdext)
2529 self.create_file(filepath)
2530 with os_helper.EnvironmentVarGuard() as env:
2531 env['PATHEXT'] = ext
2532 self.assertEqual(shutil.which(cmd, path=self.dir), filepath)
2533 self.assertEqual(shutil.which(cmdext, path=self.dir), filepath)
2534
2535 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2536 def test_pathext_with_null_extension(self):
2537 cmd = self.to_text_type(TESTFN2)
2538 cmddot = cmd + self.to_text_type('.')
2539 filepath = os.path.join(self.dir, cmd)
2540 self.create_file(filepath)
2541 with os_helper.EnvironmentVarGuard() as env:
2542 env['PATHEXT'] = '.xyz'
2543 self.assertIsNone(shutil.which(cmd, path=self.dir))
2544 self.assertIsNone(shutil.which(cmddot, path=self.dir))
2545 env['PATHEXT'] = '.xyz;.' # note the .
2546 self.assertEqual(shutil.which(cmd, path=self.dir), filepath)
2547 self.assertEqual(shutil.which(cmddot, path=self.dir),
2548 filepath + self.to_text_type('.'))
2549 env['PATHEXT'] = '.xyz;..' # multiple dots
2550 self.assertEqual(shutil.which(cmd, path=self.dir), filepath)
2551 self.assertEqual(shutil.which(cmddot, path=self.dir),
2552 filepath + self.to_text_type('.'))
2553
2554 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2555 def test_pathext_extension_ends_with_dot(self):
2556 ext = '.xyz'
2557 cmd = self.to_text_type(TESTFN2)
2558 cmdext = cmd + self.to_text_type(ext)
2559 dot = self.to_text_type('.')
2560 filepath = os.path.join(self.dir, cmdext)
2561 self.create_file(filepath)
2562 with os_helper.EnvironmentVarGuard() as env:
2563 env['PATHEXT'] = ext + '.'
2564 self.assertEqual(shutil.which(cmd, path=self.dir), filepath) # cmd.exe hangs here
2565 self.assertEqual(shutil.which(cmdext, path=self.dir), filepath)
2566 self.assertIsNone(shutil.which(cmd + dot, path=self.dir))
2567 self.assertIsNone(shutil.which(cmdext + dot, path=self.dir))
2568
2569 # See GH-75586
2570 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2571 def test_pathext_applied_on_files_in_path(self):
2572 ext = '.xyz'
2573 cmd = self.to_text_type(TESTFN2)
2574 cmdext = cmd + self.to_text_type(ext)
2575 filepath = os.path.join(self.dir, cmdext)
2576 self.create_file(filepath)
2577 with os_helper.EnvironmentVarGuard() as env:
2578 env["PATH"] = os.fsdecode(self.dir)
2579 env["PATHEXT"] = ext
2580 self.assertEqual(shutil.which(cmd), filepath)
2581 self.assertEqual(shutil.which(cmdext), filepath)
2582
2583 # See GH-75586
2584 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2585 def test_win_path_needs_curdir(self):
2586 with unittest.mock.patch('_winapi.NeedCurrentDirectoryForExePath', return_value=True) as need_curdir_mock:
2587 self.assertTrue(shutil._win_path_needs_curdir('dontcare', os.X_OK))
2588 need_curdir_mock.assert_called_once_with('dontcare')
2589 need_curdir_mock.reset_mock()
2590 self.assertTrue(shutil._win_path_needs_curdir('dontcare', 0))
2591 need_curdir_mock.assert_not_called()
2592
2593 with unittest.mock.patch('_winapi.NeedCurrentDirectoryForExePath', return_value=False) as need_curdir_mock:
2594 self.assertFalse(shutil._win_path_needs_curdir('dontcare', os.X_OK))
2595 need_curdir_mock.assert_called_once_with('dontcare')
2596
2597 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2598 def test_same_dir_with_pathext_extension(self):
2599 cmd = self.file # with .exe extension
2600 # full match
2601 self.assertNormEqual(shutil.which(cmd, path=self.dir), self.filepath)
2602 self.assertNormEqual(shutil.which(cmd, path=self.dir, mode=os.F_OK),
2603 self.filepath)
2604
2605 cmd2 = cmd + self.to_text_type('.com') # with .exe.com extension
2606 other_file_path = os.path.join(self.dir, cmd2)
2607 self.create_file(other_file_path)
2608
2609 # full match
2610 self.assertNormEqual(shutil.which(cmd, path=self.dir), self.filepath)
2611 self.assertNormEqual(shutil.which(cmd, path=self.dir, mode=os.F_OK),
2612 self.filepath)
2613 self.assertNormEqual(shutil.which(cmd2, path=self.dir), other_file_path)
2614 self.assertNormEqual(shutil.which(cmd2, path=self.dir, mode=os.F_OK),
2615 other_file_path)
2616
2617 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2618 def test_same_dir_without_pathext_extension(self):
2619 cmd = self.file[:-4] # without .exe extension
2620 # pathext match
2621 self.assertNormEqual(shutil.which(cmd, path=self.dir), self.filepath)
2622 self.assertNormEqual(shutil.which(cmd, path=self.dir, mode=os.F_OK),
2623 self.filepath)
2624
2625 # without extension
2626 other_file_path = os.path.join(self.dir, cmd)
2627 self.create_file(other_file_path)
2628
2629 # pathext match if mode contains X_OK
2630 self.assertNormEqual(shutil.which(cmd, path=self.dir), self.filepath)
2631 # full match
2632 self.assertNormEqual(shutil.which(cmd, path=self.dir, mode=os.F_OK),
2633 other_file_path)
2634 self.assertNormEqual(shutil.which(self.file, path=self.dir), self.filepath)
2635 self.assertNormEqual(shutil.which(self.file, path=self.dir, mode=os.F_OK),
2636 self.filepath)
2637
2638 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2639 def test_dir_order_with_pathext_extension(self):
2640 cmd = self.file # with .exe extension
2641 search_path = os.pathsep.join([os.fsdecode(self.other_dir),
2642 os.fsdecode(self.dir)])
2643 # full match in the second directory
2644 self.assertNormEqual(shutil.which(cmd, path=search_path), self.filepath)
2645 self.assertNormEqual(shutil.which(cmd, path=search_path, mode=os.F_OK),
2646 self.filepath)
2647
2648 cmd2 = cmd + self.to_text_type('.com') # with .exe.com extension
2649 other_file_path = os.path.join(self.other_dir, cmd2)
2650 self.create_file(other_file_path)
2651
2652 # pathext match in the first directory
2653 self.assertNormEqual(shutil.which(cmd, path=search_path), other_file_path)
2654 self.assertNormEqual(shutil.which(cmd, path=search_path, mode=os.F_OK),
2655 other_file_path)
2656 # full match in the first directory
2657 self.assertNormEqual(shutil.which(cmd2, path=search_path), other_file_path)
2658 self.assertNormEqual(shutil.which(cmd2, path=search_path, mode=os.F_OK),
2659 other_file_path)
2660
2661 # full match in the first directory
2662 search_path = os.pathsep.join([os.fsdecode(self.dir),
2663 os.fsdecode(self.other_dir)])
2664 self.assertEqual(shutil.which(cmd, path=search_path), self.filepath)
2665 self.assertEqual(shutil.which(cmd, path=search_path, mode=os.F_OK),
2666 self.filepath)
2667
2668 @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
2669 def test_dir_order_without_pathext_extension(self):
2670 cmd = self.file[:-4] # without .exe extension
2671 search_path = os.pathsep.join([os.fsdecode(self.other_dir),
2672 os.fsdecode(self.dir)])
2673 # pathext match in the second directory
2674 self.assertNormEqual(shutil.which(cmd, path=search_path), self.filepath)
2675 self.assertNormEqual(shutil.which(cmd, path=search_path, mode=os.F_OK),
2676 self.filepath)
2677
2678 # without extension
2679 other_file_path = os.path.join(self.other_dir, cmd)
2680 self.create_file(other_file_path)
2681
2682 # pathext match in the second directory
2683 self.assertNormEqual(shutil.which(cmd, path=search_path), self.filepath)
2684 # full match in the first directory
2685 self.assertNormEqual(shutil.which(cmd, path=search_path, mode=os.F_OK),
2686 other_file_path)
2687 # full match in the second directory
2688 self.assertNormEqual(shutil.which(self.file, path=search_path), self.filepath)
2689 self.assertNormEqual(shutil.which(self.file, path=search_path, mode=os.F_OK),
2690 self.filepath)
2691
2692 # pathext match in the first directory
2693 search_path = os.pathsep.join([os.fsdecode(self.dir),
2694 os.fsdecode(self.other_dir)])
2695 self.assertNormEqual(shutil.which(cmd, path=search_path), self.filepath)
2696 self.assertNormEqual(shutil.which(cmd, path=search_path, mode=os.F_OK),
2697 self.filepath)
2698
2699
2700 class TestWhichBytes(TestWhich):
2701 def setUp(self):
2702 TestWhich.setUp(self)
2703 self.dir = os.fsencode(self.dir)
2704 self.file = os.fsencode(self.file)
2705 self.filepath = os.fsencode(self.filepath)
2706 self.other_dir = os.fsencode(self.other_dir)
2707 self.curdir = os.fsencode(self.curdir)
2708 self.ext = os.fsencode(self.ext)
2709
2710 to_text_type = staticmethod(os.fsencode)
2711
2712
2713 class TestMove(BaseTest, unittest.TestCase):
2714
2715 def setUp(self):
2716 filename = "foo"
2717 self.src_dir = self.mkdtemp()
2718 self.dst_dir = self.mkdtemp()
2719 self.src_file = os.path.join(self.src_dir, filename)
2720 self.dst_file = os.path.join(self.dst_dir, filename)
2721 create_file(self.src_file, b"spam")
2722
2723 def _check_move_file(self, src, dst, real_dst):
2724 with open(src, "rb") as f:
2725 contents = f.read()
2726 shutil.move(src, dst)
2727 with open(real_dst, "rb") as f:
2728 self.assertEqual(contents, f.read())
2729 self.assertFalse(os.path.exists(src))
2730
2731 def _check_move_dir(self, src, dst, real_dst):
2732 contents = sorted(os.listdir(src))
2733 shutil.move(src, dst)
2734 self.assertEqual(contents, sorted(os.listdir(real_dst)))
2735 self.assertFalse(os.path.exists(src))
2736
2737 def test_move_file(self):
2738 # Move a file to another location on the same filesystem.
2739 self._check_move_file(self.src_file, self.dst_file, self.dst_file)
2740
2741 def test_move_file_to_dir(self):
2742 # Move a file inside an existing dir on the same filesystem.
2743 self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
2744
2745 def test_move_file_to_dir_pathlike_src(self):
2746 # Move a pathlike file to another location on the same filesystem.
2747 src = FakePath(self.src_file)
2748 self._check_move_file(src, self.dst_dir, self.dst_file)
2749
2750 def test_move_file_to_dir_pathlike_dst(self):
2751 # Move a file to another pathlike location on the same filesystem.
2752 dst = FakePath(self.dst_dir)
2753 self._check_move_file(self.src_file, dst, self.dst_file)
2754
2755 @mock_rename
2756 def test_move_file_other_fs(self):
2757 # Move a file to an existing dir on another filesystem.
2758 self.test_move_file()
2759
2760 @mock_rename
2761 def test_move_file_to_dir_other_fs(self):
2762 # Move a file to another location on another filesystem.
2763 self.test_move_file_to_dir()
2764
2765 def test_move_dir(self):
2766 # Move a dir to another location on the same filesystem.
2767 dst_dir = tempfile.mktemp(dir=self.mkdtemp())
2768 try:
2769 self._check_move_dir(self.src_dir, dst_dir, dst_dir)
2770 finally:
2771 os_helper.rmtree(dst_dir)
2772
2773 @mock_rename
2774 def test_move_dir_other_fs(self):
2775 # Move a dir to another location on another filesystem.
2776 self.test_move_dir()
2777
2778 def test_move_dir_to_dir(self):
2779 # Move a dir inside an existing dir on the same filesystem.
2780 self._check_move_dir(self.src_dir, self.dst_dir,
2781 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
2782
2783 @mock_rename
2784 def test_move_dir_to_dir_other_fs(self):
2785 # Move a dir inside an existing dir on another filesystem.
2786 self.test_move_dir_to_dir()
2787
2788 def test_move_dir_sep_to_dir(self):
2789 self._check_move_dir(self.src_dir + os.path.sep, self.dst_dir,
2790 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
2791
2792 @unittest.skipUnless(os.path.altsep, 'requires os.path.altsep')
2793 def test_move_dir_altsep_to_dir(self):
2794 self._check_move_dir(self.src_dir + os.path.altsep, self.dst_dir,
2795 os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
2796
2797 def test_existing_file_inside_dest_dir(self):
2798 # A file with the same name inside the destination dir already exists.
2799 create_file(self.dst_file)
2800 self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
2801
2802 def test_dont_move_dir_in_itself(self):
2803 # Moving a dir inside itself raises an Error.
2804 dst = os.path.join(self.src_dir, "bar")
2805 self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
2806
2807 def test_destinsrc_false_negative(self):
2808 os.mkdir(TESTFN)
2809 try:
2810 for src, dst in [('srcdir', 'srcdir/dest')]:
2811 src = os.path.join(TESTFN, src)
2812 dst = os.path.join(TESTFN, dst)
2813 self.assertTrue(shutil._destinsrc(src, dst),
2814 msg='_destinsrc() wrongly concluded that '
2815 'dst (%s) is not in src (%s)' % (dst, src))
2816 finally:
2817 os_helper.rmtree(TESTFN)
2818
2819 def test_destinsrc_false_positive(self):
2820 os.mkdir(TESTFN)
2821 try:
2822 for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
2823 src = os.path.join(TESTFN, src)
2824 dst = os.path.join(TESTFN, dst)
2825 self.assertFalse(shutil._destinsrc(src, dst),
2826 msg='_destinsrc() wrongly concluded that '
2827 'dst (%s) is in src (%s)' % (dst, src))
2828 finally:
2829 os_helper.rmtree(TESTFN)
2830
2831 @os_helper.skip_unless_symlink
2832 @mock_rename
2833 def test_move_file_symlink(self):
2834 dst = os.path.join(self.src_dir, 'bar')
2835 os.symlink(self.src_file, dst)
2836 shutil.move(dst, self.dst_file)
2837 self.assertTrue(os.path.islink(self.dst_file))
2838 self.assertTrue(os.path.samefile(self.src_file, self.dst_file))
2839
2840 @os_helper.skip_unless_symlink
2841 @mock_rename
2842 def test_move_file_symlink_to_dir(self):
2843 filename = "bar"
2844 dst = os.path.join(self.src_dir, filename)
2845 os.symlink(self.src_file, dst)
2846 shutil.move(dst, self.dst_dir)
2847 final_link = os.path.join(self.dst_dir, filename)
2848 self.assertTrue(os.path.islink(final_link))
2849 self.assertTrue(os.path.samefile(self.src_file, final_link))
2850
2851 @os_helper.skip_unless_symlink
2852 @mock_rename
2853 def test_move_dangling_symlink(self):
2854 src = os.path.join(self.src_dir, 'baz')
2855 dst = os.path.join(self.src_dir, 'bar')
2856 os.symlink(src, dst)
2857 dst_link = os.path.join(self.dst_dir, 'quux')
2858 shutil.move(dst, dst_link)
2859 self.assertTrue(os.path.islink(dst_link))
2860 self.assertEqual(os.path.realpath(src), os.path.realpath(dst_link))
2861
2862 @os_helper.skip_unless_symlink
2863 @mock_rename
2864 def test_move_dir_symlink(self):
2865 src = os.path.join(self.src_dir, 'baz')
2866 dst = os.path.join(self.src_dir, 'bar')
2867 os.mkdir(src)
2868 os.symlink(src, dst)
2869 dst_link = os.path.join(self.dst_dir, 'quux')
2870 shutil.move(dst, dst_link)
2871 self.assertTrue(os.path.islink(dst_link))
2872 self.assertTrue(os.path.samefile(src, dst_link))
2873
2874 def test_move_return_value(self):
2875 rv = shutil.move(self.src_file, self.dst_dir)
2876 self.assertEqual(rv,
2877 os.path.join(self.dst_dir, os.path.basename(self.src_file)))
2878
2879 def test_move_as_rename_return_value(self):
2880 rv = shutil.move(self.src_file, os.path.join(self.dst_dir, 'bar'))
2881 self.assertEqual(rv, os.path.join(self.dst_dir, 'bar'))
2882
2883 @mock_rename
2884 def test_move_file_special_function(self):
2885 moved = []
2886 def _copy(src, dst):
2887 moved.append((src, dst))
2888 shutil.move(self.src_file, self.dst_dir, copy_function=_copy)
2889 self.assertEqual(len(moved), 1)
2890
2891 @mock_rename
2892 def test_move_dir_special_function(self):
2893 moved = []
2894 def _copy(src, dst):
2895 moved.append((src, dst))
2896 os_helper.create_empty_file(os.path.join(self.src_dir, 'child'))
2897 os_helper.create_empty_file(os.path.join(self.src_dir, 'child1'))
2898 shutil.move(self.src_dir, self.dst_dir, copy_function=_copy)
2899 self.assertEqual(len(moved), 3)
2900
2901 def test_move_dir_caseinsensitive(self):
2902 # Renames a folder to the same name
2903 # but a different case.
2904
2905 self.src_dir = self.mkdtemp()
2906 dst_dir = os.path.join(
2907 os.path.dirname(self.src_dir),
2908 os.path.basename(self.src_dir).upper())
2909 self.assertNotEqual(self.src_dir, dst_dir)
2910
2911 try:
2912 shutil.move(self.src_dir, dst_dir)
2913 self.assertTrue(os.path.isdir(dst_dir))
2914 finally:
2915 os.rmdir(dst_dir)
2916
2917 # bpo-26791: Check that a symlink to a directory can
2918 # be moved into that directory.
2919 @mock_rename
2920 def _test_move_symlink_to_dir_into_dir(self, dst):
2921 src = os.path.join(self.src_dir, 'linktodir')
2922 dst_link = os.path.join(self.dst_dir, 'linktodir')
2923 os.symlink(self.dst_dir, src, target_is_directory=True)
2924 shutil.move(src, dst)
2925 self.assertTrue(os.path.islink(dst_link))
2926 self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
2927 self.assertFalse(os.path.exists(src))
2928
2929 # Repeat the move operation with the destination
2930 # symlink already in place (should raise shutil.Error).
2931 os.symlink(self.dst_dir, src, target_is_directory=True)
2932 with self.assertRaises(shutil.Error):
2933 shutil.move(src, dst)
2934 self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
2935 self.assertTrue(os.path.exists(src))
2936
2937 @os_helper.skip_unless_symlink
2938 def test_move_symlink_to_dir_into_dir(self):
2939 self._test_move_symlink_to_dir_into_dir(self.dst_dir)
2940
2941 @os_helper.skip_unless_symlink
2942 def test_move_symlink_to_dir_into_symlink_to_dir(self):
2943 dst = os.path.join(self.src_dir, 'otherlinktodir')
2944 os.symlink(self.dst_dir, dst, target_is_directory=True)
2945 self._test_move_symlink_to_dir_into_dir(dst)
2946
2947 @os_helper.skip_unless_dac_override
2948 @unittest.skipUnless(hasattr(os, 'lchflags')
2949 and hasattr(stat, 'SF_IMMUTABLE')
2950 and hasattr(stat, 'UF_OPAQUE'),
2951 'requires lchflags')
2952 def test_move_dir_permission_denied(self):
2953 # bpo-42782: shutil.move should not create destination directories
2954 # if the source directory cannot be removed.
2955 try:
2956 os.mkdir(TESTFN_SRC)
2957 os.lchflags(TESTFN_SRC, stat.SF_IMMUTABLE)
2958
2959 # Testing on an empty immutable directory
2960 # TESTFN_DST should not exist if shutil.move failed
2961 self.assertRaises(PermissionError, shutil.move, TESTFN_SRC, TESTFN_DST)
2962 self.assertFalse(TESTFN_DST in os.listdir())
2963
2964 # Create a file and keep the directory immutable
2965 os.lchflags(TESTFN_SRC, stat.UF_OPAQUE)
2966 os_helper.create_empty_file(os.path.join(TESTFN_SRC, 'child'))
2967 os.lchflags(TESTFN_SRC, stat.SF_IMMUTABLE)
2968
2969 # Testing on a non-empty immutable directory
2970 # TESTFN_DST should not exist if shutil.move failed
2971 self.assertRaises(PermissionError, shutil.move, TESTFN_SRC, TESTFN_DST)
2972 self.assertFalse(TESTFN_DST in os.listdir())
2973 finally:
2974 if os.path.exists(TESTFN_SRC):
2975 os.lchflags(TESTFN_SRC, stat.UF_OPAQUE)
2976 os_helper.rmtree(TESTFN_SRC)
2977 if os.path.exists(TESTFN_DST):
2978 os.lchflags(TESTFN_DST, stat.UF_OPAQUE)
2979 os_helper.rmtree(TESTFN_DST)
2980
2981
2982 class TestCopyFile(unittest.TestCase):
2983
2984 class Faux(object):
2985 _entered = False
2986 _exited_with = None
2987 _raised = False
2988 def __init__(self, raise_in_exit=False, suppress_at_exit=True):
2989 self._raise_in_exit = raise_in_exit
2990 self._suppress_at_exit = suppress_at_exit
2991 def read(self, *args):
2992 return ''
2993 def __enter__(self):
2994 self._entered = True
2995 def __exit__(self, exc_type, exc_val, exc_tb):
2996 self._exited_with = exc_type, exc_val, exc_tb
2997 if self._raise_in_exit:
2998 self._raised = True
2999 raise OSError("Cannot close")
3000 return self._suppress_at_exit
3001
3002 def test_w_source_open_fails(self):
3003 def _open(filename, mode='r'):
3004 if filename == 'srcfile':
3005 raise OSError('Cannot open "srcfile"')
3006 assert 0 # shouldn't reach here.
3007
3008 with support.swap_attr(shutil, 'open', _open):
3009 with self.assertRaises(OSError):
3010 shutil.copyfile('srcfile', 'destfile')
3011
3012 @unittest.skipIf(MACOS, "skipped on macOS")
3013 def test_w_dest_open_fails(self):
3014 srcfile = self.Faux()
3015
3016 def _open(filename, mode='r'):
3017 if filename == 'srcfile':
3018 return srcfile
3019 if filename == 'destfile':
3020 raise OSError('Cannot open "destfile"')
3021 assert 0 # shouldn't reach here.
3022
3023 with support.swap_attr(shutil, 'open', _open):
3024 shutil.copyfile('srcfile', 'destfile')
3025 self.assertTrue(srcfile._entered)
3026 self.assertTrue(srcfile._exited_with[0] is OSError)
3027 self.assertEqual(srcfile._exited_with[1].args,
3028 ('Cannot open "destfile"',))
3029
3030 @unittest.skipIf(MACOS, "skipped on macOS")
3031 def test_w_dest_close_fails(self):
3032 srcfile = self.Faux()
3033 destfile = self.Faux(True)
3034
3035 def _open(filename, mode='r'):
3036 if filename == 'srcfile':
3037 return srcfile
3038 if filename == 'destfile':
3039 return destfile
3040 assert 0 # shouldn't reach here.
3041
3042 with support.swap_attr(shutil, 'open', _open):
3043 shutil.copyfile('srcfile', 'destfile')
3044 self.assertTrue(srcfile._entered)
3045 self.assertTrue(destfile._entered)
3046 self.assertTrue(destfile._raised)
3047 self.assertTrue(srcfile._exited_with[0] is OSError)
3048 self.assertEqual(srcfile._exited_with[1].args,
3049 ('Cannot close',))
3050
3051 @unittest.skipIf(MACOS, "skipped on macOS")
3052 def test_w_source_close_fails(self):
3053
3054 srcfile = self.Faux(True)
3055 destfile = self.Faux()
3056
3057 def _open(filename, mode='r'):
3058 if filename == 'srcfile':
3059 return srcfile
3060 if filename == 'destfile':
3061 return destfile
3062 assert 0 # shouldn't reach here.
3063
3064 with support.swap_attr(shutil, 'open', _open):
3065 with self.assertRaises(OSError):
3066 shutil.copyfile('srcfile', 'destfile')
3067 self.assertTrue(srcfile._entered)
3068 self.assertTrue(destfile._entered)
3069 self.assertFalse(destfile._raised)
3070 self.assertTrue(srcfile._exited_with[0] is None)
3071 self.assertTrue(srcfile._raised)
3072
3073
3074 class TestCopyFileObj(unittest.TestCase):
3075 FILESIZE = 2 * 1024 * 1024
3076
3077 @classmethod
3078 def setUpClass(cls):
3079 write_test_file(TESTFN, cls.FILESIZE)
3080
3081 @classmethod
3082 def tearDownClass(cls):
3083 os_helper.unlink(TESTFN)
3084 os_helper.unlink(TESTFN2)
3085
3086 def tearDown(self):
3087 os_helper.unlink(TESTFN2)
3088
3089 @contextlib.contextmanager
3090 def get_files(self):
3091 with open(TESTFN, "rb") as src:
3092 with open(TESTFN2, "wb") as dst:
3093 yield (src, dst)
3094
3095 def assert_files_eq(self, src, dst):
3096 with open(src, 'rb') as fsrc:
3097 with open(dst, 'rb') as fdst:
3098 self.assertEqual(fsrc.read(), fdst.read())
3099
3100 def test_content(self):
3101 with self.get_files() as (src, dst):
3102 shutil.copyfileobj(src, dst)
3103 self.assert_files_eq(TESTFN, TESTFN2)
3104
3105 def test_file_not_closed(self):
3106 with self.get_files() as (src, dst):
3107 shutil.copyfileobj(src, dst)
3108 assert not src.closed
3109 assert not dst.closed
3110
3111 def test_file_offset(self):
3112 with self.get_files() as (src, dst):
3113 shutil.copyfileobj(src, dst)
3114 self.assertEqual(src.tell(), self.FILESIZE)
3115 self.assertEqual(dst.tell(), self.FILESIZE)
3116
3117 @unittest.skipIf(os.name != 'nt', "Windows only")
3118 def test_win_impl(self):
3119 # Make sure alternate Windows implementation is called.
3120 with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
3121 shutil.copyfile(TESTFN, TESTFN2)
3122 assert m.called
3123
3124 # File size is 2 MiB but max buf size should be 1 MiB.
3125 self.assertEqual(m.call_args[0][2], 1 * 1024 * 1024)
3126
3127 # If file size < 1 MiB memoryview() length must be equal to
3128 # the actual file size.
3129 with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
3130 f.write(b'foo')
3131 fname = f.name
3132 self.addCleanup(os_helper.unlink, fname)
3133 with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
3134 shutil.copyfile(fname, TESTFN2)
3135 self.assertEqual(m.call_args[0][2], 3)
3136
3137 # Empty files should not rely on readinto() variant.
3138 with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
3139 pass
3140 fname = f.name
3141 self.addCleanup(os_helper.unlink, fname)
3142 with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
3143 shutil.copyfile(fname, TESTFN2)
3144 assert not m.called
3145 self.assert_files_eq(fname, TESTFN2)
3146
3147
3148 class _ZeroCopyFileTest(object):
3149 """Tests common to all zero-copy APIs."""
3150 FILESIZE = (10 * 1024 * 1024) # 10 MiB
3151 FILEDATA = b""
3152 PATCHPOINT = ""
3153
3154 @classmethod
3155 def setUpClass(cls):
3156 write_test_file(TESTFN, cls.FILESIZE)
3157 with open(TESTFN, 'rb') as f:
3158 cls.FILEDATA = f.read()
3159 assert len(cls.FILEDATA) == cls.FILESIZE
3160
3161 @classmethod
3162 def tearDownClass(cls):
3163 os_helper.unlink(TESTFN)
3164
3165 def tearDown(self):
3166 os_helper.unlink(TESTFN2)
3167
3168 @contextlib.contextmanager
3169 def get_files(self):
3170 with open(TESTFN, "rb") as src:
3171 with open(TESTFN2, "wb") as dst:
3172 yield (src, dst)
3173
3174 def zerocopy_fun(self, *args, **kwargs):
3175 raise NotImplementedError("must be implemented in subclass")
3176
3177 def reset(self):
3178 self.tearDown()
3179 self.tearDownClass()
3180 self.setUpClass()
3181 self.setUp()
3182
3183 # ---
3184
3185 def test_regular_copy(self):
3186 with self.get_files() as (src, dst):
3187 self.zerocopy_fun(src, dst)
3188 self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
3189 # Make sure the fallback function is not called.
3190 with self.get_files() as (src, dst):
3191 with unittest.mock.patch('shutil.copyfileobj') as m:
3192 shutil.copyfile(TESTFN, TESTFN2)
3193 assert not m.called
3194
3195 def test_same_file(self):
3196 self.addCleanup(self.reset)
3197 with self.get_files() as (src, dst):
3198 with self.assertRaises((OSError, _GiveupOnFastCopy)):
3199 self.zerocopy_fun(src, src)
3200 # Make sure src file is not corrupted.
3201 self.assertEqual(read_file(TESTFN, binary=True), self.FILEDATA)
3202
3203 def test_non_existent_src(self):
3204 name = tempfile.mktemp(dir=os.getcwd())
3205 with self.assertRaises(FileNotFoundError) as cm:
3206 shutil.copyfile(name, "new")
3207 self.assertEqual(cm.exception.filename, name)
3208
3209 def test_empty_file(self):
3210 srcname = TESTFN + 'src'
3211 dstname = TESTFN + 'dst'
3212 self.addCleanup(lambda: os_helper.unlink(srcname))
3213 self.addCleanup(lambda: os_helper.unlink(dstname))
3214 create_file(srcname)
3215
3216 with open(srcname, "rb") as src:
3217 with open(dstname, "wb") as dst:
3218 self.zerocopy_fun(src, dst)
3219
3220 self.assertEqual(read_file(dstname, binary=True), b"")
3221
3222 def test_unhandled_exception(self):
3223 with unittest.mock.patch(self.PATCHPOINT,
3224 side_effect=ZeroDivisionError):
3225 self.assertRaises(ZeroDivisionError,
3226 shutil.copyfile, TESTFN, TESTFN2)
3227
3228 def test_exception_on_first_call(self):
3229 # Emulate a case where the first call to the zero-copy
3230 # function raises an exception in which case the function is
3231 # supposed to give up immediately.
3232 with unittest.mock.patch(self.PATCHPOINT,
3233 side_effect=OSError(errno.EINVAL, "yo")):
3234 with self.get_files() as (src, dst):
3235 with self.assertRaises(_GiveupOnFastCopy):
3236 self.zerocopy_fun(src, dst)
3237
3238 def test_filesystem_full(self):
3239 # Emulate a case where filesystem is full and sendfile() fails
3240 # on first call.
3241 with unittest.mock.patch(self.PATCHPOINT,
3242 side_effect=OSError(errno.ENOSPC, "yo")):
3243 with self.get_files() as (src, dst):
3244 self.assertRaises(OSError, self.zerocopy_fun, src, dst)
3245
3246
3247 @unittest.skipIf(not SUPPORTS_SENDFILE, 'os.sendfile() not supported')
3248 class TestZeroCopySendfile(_ZeroCopyFileTest, unittest.TestCase):
3249 PATCHPOINT = "os.sendfile"
3250
3251 def zerocopy_fun(self, fsrc, fdst):
3252 return shutil._fastcopy_sendfile(fsrc, fdst)
3253
3254 def test_non_regular_file_src(self):
3255 with io.BytesIO(self.FILEDATA) as src:
3256 with open(TESTFN2, "wb") as dst:
3257 with self.assertRaises(_GiveupOnFastCopy):
3258 self.zerocopy_fun(src, dst)
3259 shutil.copyfileobj(src, dst)
3260
3261 self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
3262
3263 def test_non_regular_file_dst(self):
3264 with open(TESTFN, "rb") as src:
3265 with io.BytesIO() as dst:
3266 with self.assertRaises(_GiveupOnFastCopy):
3267 self.zerocopy_fun(src, dst)
3268 shutil.copyfileobj(src, dst)
3269 dst.seek(0)
3270 self.assertEqual(dst.read(), self.FILEDATA)
3271
3272 def test_exception_on_second_call(self):
3273 def sendfile(*args, **kwargs):
3274 if not flag:
3275 flag.append(None)
3276 return orig_sendfile(*args, **kwargs)
3277 else:
3278 raise OSError(errno.EBADF, "yo")
3279
3280 flag = []
3281 orig_sendfile = os.sendfile
3282 with unittest.mock.patch('os.sendfile', create=True,
3283 side_effect=sendfile):
3284 with self.get_files() as (src, dst):
3285 with self.assertRaises(OSError) as cm:
3286 shutil._fastcopy_sendfile(src, dst)
3287 assert flag
3288 self.assertEqual(cm.exception.errno, errno.EBADF)
3289
3290 def test_cant_get_size(self):
3291 # Emulate a case where src file size cannot be determined.
3292 # Internally bufsize will be set to a small value and
3293 # sendfile() will be called repeatedly.
3294 with unittest.mock.patch('os.fstat', side_effect=OSError) as m:
3295 with self.get_files() as (src, dst):
3296 shutil._fastcopy_sendfile(src, dst)
3297 assert m.called
3298 self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
3299
3300 def test_small_chunks(self):
3301 # Force internal file size detection to be smaller than the
3302 # actual file size. We want to force sendfile() to be called
3303 # multiple times, also in order to emulate a src fd which gets
3304 # bigger while it is being copied.
3305 mock = unittest.mock.Mock()
3306 mock.st_size = 65536 + 1
3307 with unittest.mock.patch('os.fstat', return_value=mock) as m:
3308 with self.get_files() as (src, dst):
3309 shutil._fastcopy_sendfile(src, dst)
3310 assert m.called
3311 self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
3312
3313 def test_big_chunk(self):
3314 # Force internal file size detection to be +100MB bigger than
3315 # the actual file size. Make sure sendfile() does not rely on
3316 # file size value except for (maybe) a better throughput /
3317 # performance.
3318 mock = unittest.mock.Mock()
3319 mock.st_size = self.FILESIZE + (100 * 1024 * 1024)
3320 with unittest.mock.patch('os.fstat', return_value=mock) as m:
3321 with self.get_files() as (src, dst):
3322 shutil._fastcopy_sendfile(src, dst)
3323 assert m.called
3324 self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
3325
3326 def test_blocksize_arg(self):
3327 with unittest.mock.patch('os.sendfile',
3328 side_effect=ZeroDivisionError) as m:
3329 self.assertRaises(ZeroDivisionError,
3330 shutil.copyfile, TESTFN, TESTFN2)
3331 blocksize = m.call_args[0][3]
3332 # Make sure file size and the block size arg passed to
3333 # sendfile() are the same.
3334 self.assertEqual(blocksize, os.path.getsize(TESTFN))
3335 # ...unless we're dealing with a small file.
3336 os_helper.unlink(TESTFN2)
3337 create_file(TESTFN2, b"hello")
3338 self.addCleanup(os_helper.unlink, TESTFN2 + '3')
3339 self.assertRaises(ZeroDivisionError,
3340 shutil.copyfile, TESTFN2, TESTFN2 + '3')
3341 blocksize = m.call_args[0][3]
3342 self.assertEqual(blocksize, 2 ** 23)
3343
3344 def test_file2file_not_supported(self):
3345 # Emulate a case where sendfile() only support file->socket
3346 # fds. In such a case copyfile() is supposed to skip the
3347 # fast-copy attempt from then on.
3348 assert shutil._USE_CP_SENDFILE
3349 try:
3350 with unittest.mock.patch(
3351 self.PATCHPOINT,
3352 side_effect=OSError(errno.ENOTSOCK, "yo")) as m:
3353 with self.get_files() as (src, dst):
3354 with self.assertRaises(_GiveupOnFastCopy):
3355 shutil._fastcopy_sendfile(src, dst)
3356 assert m.called
3357 assert not shutil._USE_CP_SENDFILE
3358
3359 with unittest.mock.patch(self.PATCHPOINT) as m:
3360 shutil.copyfile(TESTFN, TESTFN2)
3361 assert not m.called
3362 finally:
3363 shutil._USE_CP_SENDFILE = True
3364
3365
3366 @unittest.skipIf(not MACOS, 'macOS only')
3367 class TestZeroCopyMACOS(_ZeroCopyFileTest, unittest.TestCase):
3368 PATCHPOINT = "posix._fcopyfile"
3369
3370 def zerocopy_fun(self, src, dst):
3371 return shutil._fastcopy_fcopyfile(src, dst, posix._COPYFILE_DATA)
3372
3373
3374 class TestGetTerminalSize(unittest.TestCase):
3375 def test_does_not_crash(self):
3376 """Check if get_terminal_size() returns a meaningful value.
3377
3378 There's no easy portable way to actually check the size of the
3379 terminal, so let's check if it returns something sensible instead.
3380 """
3381 size = shutil.get_terminal_size()
3382 self.assertGreaterEqual(size.columns, 0)
3383 self.assertGreaterEqual(size.lines, 0)
3384
3385 def test_os_environ_first(self):
3386 "Check if environment variables have precedence"
3387
3388 with os_helper.EnvironmentVarGuard() as env:
3389 env['COLUMNS'] = '777'
3390 del env['LINES']
3391 size = shutil.get_terminal_size()
3392 self.assertEqual(size.columns, 777)
3393
3394 with os_helper.EnvironmentVarGuard() as env:
3395 del env['COLUMNS']
3396 env['LINES'] = '888'
3397 size = shutil.get_terminal_size()
3398 self.assertEqual(size.lines, 888)
3399
3400 def test_bad_environ(self):
3401 with os_helper.EnvironmentVarGuard() as env:
3402 env['COLUMNS'] = 'xxx'
3403 env['LINES'] = 'yyy'
3404 size = shutil.get_terminal_size()
3405 self.assertGreaterEqual(size.columns, 0)
3406 self.assertGreaterEqual(size.lines, 0)
3407
3408 @unittest.skipUnless(os.isatty(sys.__stdout__.fileno()), "not on tty")
3409 @support.requires_subprocess()
3410 @unittest.skipUnless(hasattr(os, 'get_terminal_size'),
3411 'need os.get_terminal_size()')
3412 def test_stty_match(self):
3413 """Check if stty returns the same results ignoring env
3414
3415 This test will fail if stdin and stdout are connected to
3416 different terminals with different sizes. Nevertheless, such
3417 situations should be pretty rare.
3418 """
3419 try:
3420 size = subprocess.check_output(['stty', 'size']).decode().split()
3421 except (FileNotFoundError, PermissionError,
3422 subprocess.CalledProcessError):
3423 self.skipTest("stty invocation failed")
3424 expected = (int(size[1]), int(size[0])) # reversed order
3425
3426 with os_helper.EnvironmentVarGuard() as env:
3427 env.unset('LINES', 'COLUMNS')
3428 actual = shutil.get_terminal_size()
3429
3430 self.assertEqual(expected, actual)
3431
3432 @unittest.skipIf(support.is_wasi, "WASI has no /dev/null")
3433 def test_fallback(self):
3434 with os_helper.EnvironmentVarGuard() as env:
3435 env.unset('LINES', 'COLUMNS')
3436
3437 # sys.__stdout__ has no fileno()
3438 with support.swap_attr(sys, '__stdout__', None):
3439 size = shutil.get_terminal_size(fallback=(10, 20))
3440 self.assertEqual(size.columns, 10)
3441 self.assertEqual(size.lines, 20)
3442
3443 # sys.__stdout__ is not a terminal on Unix
3444 # or fileno() not in (0, 1, 2) on Windows
3445 with open(os.devnull, 'w', encoding='utf-8') as f, \
3446 support.swap_attr(sys, '__stdout__', f):
3447 size = shutil.get_terminal_size(fallback=(30, 40))
3448 self.assertEqual(size.columns, 30)
3449 self.assertEqual(size.lines, 40)
3450
3451
3452 class PublicAPITests(unittest.TestCase):
3453 """Ensures that the correct values are exposed in the public API."""
3454
3455 def test_module_all_attribute(self):
3456 self.assertTrue(hasattr(shutil, '__all__'))
3457 target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
3458 'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
3459 'SpecialFileError', 'ExecError', 'make_archive',
3460 'get_archive_formats', 'register_archive_format',
3461 'unregister_archive_format', 'get_unpack_formats',
3462 'register_unpack_format', 'unregister_unpack_format',
3463 'unpack_archive', 'ignore_patterns', 'chown', 'which',
3464 'get_terminal_size', 'SameFileError']
3465 if hasattr(os, 'statvfs') or os.name == 'nt':
3466 target_api.append('disk_usage')
3467 self.assertEqual(set(shutil.__all__), set(target_api))
3468
3469
3470 if __name__ == '__main__':
3471 unittest.main()