2003-01-24 13:34:13 -04:00
|
|
|
# Copyright (C) 2003 Python Software Foundation
|
|
|
|
|
|
|
|
import unittest
|
2014-12-09 20:50:32 -04:00
|
|
|
import unittest.mock
|
2003-01-24 13:34:13 -04:00
|
|
|
import shutil
|
|
|
|
import tempfile
|
2004-11-23 05:27:27 -04:00
|
|
|
import sys
|
2004-10-31 08:05:31 -04:00
|
|
|
import stat
|
2004-06-19 18:11:35 -03:00
|
|
|
import os
|
|
|
|
import os.path
|
2012-01-02 14:18:02 -04:00
|
|
|
import errno
|
2011-03-16 15:05:35 -03:00
|
|
|
import functools
|
2017-05-05 18:27:12 -03:00
|
|
|
import pathlib
|
2012-02-08 18:28:36 -04:00
|
|
|
import subprocess
|
2018-06-12 18:04:50 -03:00
|
|
|
import random
|
|
|
|
import string
|
|
|
|
import contextlib
|
|
|
|
import io
|
2015-09-06 12:33:19 -03:00
|
|
|
from shutil import (make_archive,
|
2010-02-23 01:30:31 -04:00
|
|
|
register_archive_format, unregister_archive_format,
|
2010-04-28 14:51:36 -03:00
|
|
|
get_archive_formats, Error, unpack_archive,
|
|
|
|
register_unpack_format, RegistryError,
|
2012-10-07 07:49:58 -03:00
|
|
|
unregister_unpack_format, get_unpack_formats,
|
2018-06-12 18:04:50 -03:00
|
|
|
SameFileError, _GiveupOnFastCopy)
|
2010-02-23 01:30:31 -04:00
|
|
|
import tarfile
|
2016-12-16 12:58:33 -04:00
|
|
|
import zipfile
|
2018-06-12 18:04:50 -03:00
|
|
|
try:
|
|
|
|
import posix
|
|
|
|
except ImportError:
|
|
|
|
posix = None
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
from test import support
|
2020-06-30 10:46:31 -03:00
|
|
|
from test.support import os_helper
|
|
|
|
from test.support.os_helper import TESTFN, FakePath
|
2023-04-24 05:58:06 -03:00
|
|
|
from test.support import warnings_helper
|
2014-08-06 12:50:19 -03:00
|
|
|
|
2009-05-01 18:09:44 -03:00
|
|
|
TESTFN2 = TESTFN + "2"
|
2021-03-02 16:53:15 -04:00
|
|
|
TESTFN_SRC = TESTFN + "_SRC"
|
|
|
|
TESTFN_DST = TESTFN + "_DST"
|
2018-06-25 21:11:06 -03:00
|
|
|
MACOS = sys.platform.startswith("darwin")
|
2021-07-20 15:16:23 -03:00
|
|
|
SOLARIS = sys.platform.startswith("sunos")
|
2019-02-18 07:02:44 -04:00
|
|
|
AIX = sys.platform[:3] == 'aix'
|
2010-02-23 01:30:31 -04:00
|
|
|
try:
|
|
|
|
import grp
|
|
|
|
import pwd
|
|
|
|
UID_GID_SUPPORT = True
|
|
|
|
except ImportError:
|
|
|
|
UID_GID_SUPPORT = False
|
|
|
|
|
2019-08-21 19:27:33 -03:00
|
|
|
try:
|
|
|
|
import _winapi
|
|
|
|
except ImportError:
|
|
|
|
_winapi = None
|
|
|
|
|
2022-06-22 05:47:25 -03:00
|
|
|
no_chdir = unittest.mock.patch('os.chdir',
|
|
|
|
side_effect=AssertionError("shouldn't call os.chdir()"))
|
|
|
|
|
2011-03-16 15:05:35 -03:00
|
|
|
def _fake_rename(*args, **kwargs):
|
|
|
|
# Pretend the destination path is on a different filesystem.
|
2012-01-02 14:18:02 -04:00
|
|
|
raise OSError(getattr(errno, 'EXDEV', 18), "Invalid cross-device link")
|
2011-03-16 15:05:35 -03:00
|
|
|
|
|
|
|
def mock_rename(func):
|
|
|
|
@functools.wraps(func)
|
|
|
|
def wrap(*args, **kwargs):
|
|
|
|
try:
|
|
|
|
builtin_rename = os.rename
|
|
|
|
os.rename = _fake_rename
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
finally:
|
|
|
|
os.rename = builtin_rename
|
|
|
|
return wrap
|
|
|
|
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
def write_file(path, content, binary=False):
|
|
|
|
"""Write *content* to a file located at *path*.
|
|
|
|
|
|
|
|
If *path* is a tuple instead of a string, os.path.join will be used to
|
|
|
|
make a path. If *binary* is true, the file will be opened in binary
|
|
|
|
mode.
|
|
|
|
"""
|
|
|
|
if isinstance(path, tuple):
|
|
|
|
path = os.path.join(*path)
|
2021-04-05 01:11:23 -03:00
|
|
|
mode = 'wb' if binary else 'w'
|
|
|
|
encoding = None if binary else "utf-8"
|
|
|
|
with open(path, mode, encoding=encoding) as fp:
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
fp.write(content)
|
|
|
|
|
2018-06-12 18:04:50 -03:00
|
|
|
def write_test_file(path, size):
|
|
|
|
"""Create a test file with an arbitrary size and random text content."""
|
|
|
|
def chunks(total, step):
|
|
|
|
assert total >= step
|
|
|
|
while total > step:
|
|
|
|
yield step
|
|
|
|
total -= step
|
|
|
|
if total:
|
|
|
|
yield total
|
|
|
|
|
|
|
|
bufsize = min(size, 8192)
|
|
|
|
chunk = b"".join([random.choice(string.ascii_letters).encode()
|
|
|
|
for i in range(bufsize)])
|
|
|
|
with open(path, 'wb') as f:
|
|
|
|
for csize in chunks(size, bufsize):
|
|
|
|
f.write(chunk)
|
|
|
|
assert os.path.getsize(path) == size
|
|
|
|
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
def read_file(path, binary=False):
|
|
|
|
"""Return contents from a file located at *path*.
|
|
|
|
|
|
|
|
If *path* is a tuple instead of a string, os.path.join will be used to
|
|
|
|
make a path. If *binary* is true, the file will be opened in binary
|
|
|
|
mode.
|
|
|
|
"""
|
|
|
|
if isinstance(path, tuple):
|
|
|
|
path = os.path.join(*path)
|
2021-04-05 01:11:23 -03:00
|
|
|
mode = 'rb' if binary else 'r'
|
|
|
|
encoding = None if binary else "utf-8"
|
|
|
|
with open(path, mode, encoding=encoding) as fp:
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
return fp.read()
|
|
|
|
|
2015-09-06 12:33:19 -03:00
|
|
|
def rlistdir(path):
|
|
|
|
res = []
|
|
|
|
for name in sorted(os.listdir(path)):
|
|
|
|
p = os.path.join(path, name)
|
|
|
|
if os.path.isdir(p) and not os.path.islink(p):
|
|
|
|
res.append(name + '/')
|
|
|
|
for n in rlistdir(p):
|
|
|
|
res.append(name + '/' + n)
|
|
|
|
else:
|
|
|
|
res.append(name)
|
|
|
|
return res
|
|
|
|
|
2018-06-12 18:04:50 -03:00
|
|
|
def supports_file2file_sendfile():
|
|
|
|
# ...apparently Linux and Solaris are the only ones
|
|
|
|
if not hasattr(os, "sendfile"):
|
|
|
|
return False
|
|
|
|
srcname = None
|
|
|
|
dstname = None
|
|
|
|
try:
|
2019-11-15 13:49:21 -04:00
|
|
|
with tempfile.NamedTemporaryFile("wb", dir=os.getcwd(), delete=False) as f:
|
2018-06-12 18:04:50 -03:00
|
|
|
srcname = f.name
|
|
|
|
f.write(b"0123456789")
|
|
|
|
|
|
|
|
with open(srcname, "rb") as src:
|
2019-11-15 13:49:21 -04:00
|
|
|
with tempfile.NamedTemporaryFile("wb", dir=os.getcwd(), delete=False) as dst:
|
2019-06-26 20:39:53 -03:00
|
|
|
dstname = dst.name
|
2018-06-12 18:04:50 -03:00
|
|
|
infd = src.fileno()
|
|
|
|
outfd = dst.fileno()
|
|
|
|
try:
|
|
|
|
os.sendfile(outfd, infd, 0, 2)
|
|
|
|
except OSError:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
finally:
|
|
|
|
if srcname is not None:
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(srcname)
|
2018-06-12 18:04:50 -03:00
|
|
|
if dstname is not None:
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(dstname)
|
2018-06-12 18:04:50 -03:00
|
|
|
|
|
|
|
|
|
|
|
SUPPORTS_SENDFILE = supports_file2file_sendfile()
|
|
|
|
|
2019-02-18 07:02:44 -04:00
|
|
|
# AIX 32-bit mode, by default, lacks enough memory for the xz/lzma compiler test
|
|
|
|
# The AIX command 'dump -o program' gives XCOFF header information
|
|
|
|
# The second word of the last line in the maxdata value
|
|
|
|
# when 32-bit maxdata must be greater than 0x1000000 for the xz test to succeed
|
|
|
|
def _maxdataOK():
|
|
|
|
if AIX and sys.maxsize == 2147483647:
|
|
|
|
hdrs=subprocess.getoutput("/usr/bin/dump -o %s" % sys.executable)
|
|
|
|
maxdata=hdrs.split("\n")[-1].split()[1]
|
|
|
|
return int(maxdata,16) >= 0x20000000
|
|
|
|
else:
|
|
|
|
return True
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
class BaseTest:
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2019-11-15 13:49:21 -04:00
|
|
|
def mkdtemp(self, prefix=None):
|
2010-02-23 01:30:31 -04:00
|
|
|
"""Create a temporary directory that will be cleaned up.
|
|
|
|
|
|
|
|
Returns the path of the directory.
|
|
|
|
"""
|
2019-11-15 13:49:21 -04:00
|
|
|
d = tempfile.mkdtemp(prefix=prefix, dir=os.getcwd())
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(os_helper.rmtree, d)
|
2010-02-23 01:30:31 -04:00
|
|
|
return d
|
2010-04-19 19:30:51 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
|
|
|
|
class TestRmTree(BaseTest, unittest.TestCase):
|
|
|
|
|
2012-06-25 08:27:31 -03:00
|
|
|
def test_rmtree_works_on_bytes(self):
|
|
|
|
tmp = self.mkdtemp()
|
|
|
|
victim = os.path.join(tmp, 'killme')
|
|
|
|
os.mkdir(victim)
|
|
|
|
write_file(os.path.join(victim, 'somefile'), 'foo')
|
|
|
|
victim = os.fsencode(victim)
|
|
|
|
self.assertIsInstance(victim, bytes)
|
2016-09-08 15:11:13 -03:00
|
|
|
shutil.rmtree(victim)
|
2012-06-25 08:27:31 -03:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2023-03-19 15:33:51 -03:00
|
|
|
def test_rmtree_fails_on_symlink_onerror(self):
|
2012-06-28 07:07:29 -03:00
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir_ = os.path.join(tmp, 'dir')
|
|
|
|
os.mkdir(dir_)
|
|
|
|
link = os.path.join(tmp, 'link')
|
|
|
|
os.symlink(dir_, link)
|
|
|
|
self.assertRaises(OSError, shutil.rmtree, link)
|
|
|
|
self.assertTrue(os.path.exists(dir_))
|
2012-12-10 04:00:09 -04:00
|
|
|
self.assertTrue(os.path.lexists(link))
|
|
|
|
errors = []
|
|
|
|
def onerror(*args):
|
|
|
|
errors.append(args)
|
2023-12-03 10:02:37 -04:00
|
|
|
shutil.rmtree(link, onerror=onerror)
|
2012-12-10 04:00:09 -04:00
|
|
|
self.assertEqual(len(errors), 1)
|
|
|
|
self.assertIs(errors[0][0], os.path.islink)
|
|
|
|
self.assertEqual(errors[0][1], link)
|
|
|
|
self.assertIsInstance(errors[0][2][1], OSError)
|
2012-06-28 07:07:29 -03:00
|
|
|
|
2023-03-19 15:33:51 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
|
|
|
def test_rmtree_fails_on_symlink_onexc(self):
|
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir_ = os.path.join(tmp, 'dir')
|
|
|
|
os.mkdir(dir_)
|
|
|
|
link = os.path.join(tmp, 'link')
|
|
|
|
os.symlink(dir_, link)
|
|
|
|
self.assertRaises(OSError, shutil.rmtree, link)
|
|
|
|
self.assertTrue(os.path.exists(dir_))
|
|
|
|
self.assertTrue(os.path.lexists(link))
|
|
|
|
errors = []
|
|
|
|
def onexc(*args):
|
|
|
|
errors.append(args)
|
|
|
|
shutil.rmtree(link, onexc=onexc)
|
|
|
|
self.assertEqual(len(errors), 1)
|
|
|
|
self.assertIs(errors[0][0], os.path.islink)
|
|
|
|
self.assertEqual(errors[0][1], link)
|
|
|
|
self.assertIsInstance(errors[0][2], OSError)
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2012-06-28 07:07:29 -03:00
|
|
|
def test_rmtree_works_on_symlinks(self):
|
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir1 = os.path.join(tmp, 'dir1')
|
|
|
|
dir2 = os.path.join(dir1, 'dir2')
|
|
|
|
dir3 = os.path.join(tmp, 'dir3')
|
|
|
|
for d in dir1, dir2, dir3:
|
|
|
|
os.mkdir(d)
|
|
|
|
file1 = os.path.join(tmp, 'file1')
|
|
|
|
write_file(file1, 'foo')
|
|
|
|
link1 = os.path.join(dir1, 'link1')
|
|
|
|
os.symlink(dir2, link1)
|
|
|
|
link2 = os.path.join(dir1, 'link2')
|
|
|
|
os.symlink(dir3, link2)
|
|
|
|
link3 = os.path.join(dir1, 'link3')
|
|
|
|
os.symlink(file1, link3)
|
|
|
|
# make sure symlinks are removed but not followed
|
|
|
|
shutil.rmtree(dir1)
|
|
|
|
self.assertFalse(os.path.exists(dir1))
|
|
|
|
self.assertTrue(os.path.exists(dir3))
|
|
|
|
self.assertTrue(os.path.exists(file1))
|
|
|
|
|
2019-08-21 19:27:33 -03:00
|
|
|
@unittest.skipUnless(_winapi, 'only relevant on Windows')
|
2023-03-19 15:33:51 -03:00
|
|
|
def test_rmtree_fails_on_junctions_onerror(self):
|
2019-08-21 19:27:33 -03:00
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir_ = os.path.join(tmp, 'dir')
|
|
|
|
os.mkdir(dir_)
|
|
|
|
link = os.path.join(tmp, 'link')
|
|
|
|
_winapi.CreateJunction(dir_, link)
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(os_helper.unlink, link)
|
2019-08-21 19:27:33 -03:00
|
|
|
self.assertRaises(OSError, shutil.rmtree, link)
|
|
|
|
self.assertTrue(os.path.exists(dir_))
|
|
|
|
self.assertTrue(os.path.lexists(link))
|
|
|
|
errors = []
|
|
|
|
def onerror(*args):
|
|
|
|
errors.append(args)
|
2023-12-03 10:02:37 -04:00
|
|
|
shutil.rmtree(link, onerror=onerror)
|
2019-08-21 19:27:33 -03:00
|
|
|
self.assertEqual(len(errors), 1)
|
|
|
|
self.assertIs(errors[0][0], os.path.islink)
|
|
|
|
self.assertEqual(errors[0][1], link)
|
|
|
|
self.assertIsInstance(errors[0][2][1], OSError)
|
|
|
|
|
2023-03-19 15:33:51 -03:00
|
|
|
@unittest.skipUnless(_winapi, 'only relevant on Windows')
|
|
|
|
def test_rmtree_fails_on_junctions_onexc(self):
|
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir_ = os.path.join(tmp, 'dir')
|
|
|
|
os.mkdir(dir_)
|
|
|
|
link = os.path.join(tmp, 'link')
|
|
|
|
_winapi.CreateJunction(dir_, link)
|
|
|
|
self.addCleanup(os_helper.unlink, link)
|
|
|
|
self.assertRaises(OSError, shutil.rmtree, link)
|
|
|
|
self.assertTrue(os.path.exists(dir_))
|
|
|
|
self.assertTrue(os.path.lexists(link))
|
|
|
|
errors = []
|
|
|
|
def onexc(*args):
|
|
|
|
errors.append(args)
|
|
|
|
shutil.rmtree(link, onexc=onexc)
|
|
|
|
self.assertEqual(len(errors), 1)
|
|
|
|
self.assertIs(errors[0][0], os.path.islink)
|
|
|
|
self.assertEqual(errors[0][1], link)
|
|
|
|
self.assertIsInstance(errors[0][2], OSError)
|
|
|
|
|
2019-08-21 19:27:33 -03:00
|
|
|
@unittest.skipUnless(_winapi, 'only relevant on Windows')
|
|
|
|
def test_rmtree_works_on_junctions(self):
|
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir1 = os.path.join(tmp, 'dir1')
|
|
|
|
dir2 = os.path.join(dir1, 'dir2')
|
|
|
|
dir3 = os.path.join(tmp, 'dir3')
|
|
|
|
for d in dir1, dir2, dir3:
|
|
|
|
os.mkdir(d)
|
|
|
|
file1 = os.path.join(tmp, 'file1')
|
|
|
|
write_file(file1, 'foo')
|
|
|
|
link1 = os.path.join(dir1, 'link1')
|
|
|
|
_winapi.CreateJunction(dir2, link1)
|
|
|
|
link2 = os.path.join(dir1, 'link2')
|
|
|
|
_winapi.CreateJunction(dir3, link2)
|
|
|
|
link3 = os.path.join(dir1, 'link3')
|
|
|
|
_winapi.CreateJunction(file1, link3)
|
|
|
|
# make sure junctions are removed but not followed
|
|
|
|
shutil.rmtree(dir1)
|
|
|
|
self.assertFalse(os.path.exists(dir1))
|
|
|
|
self.assertTrue(os.path.exists(dir3))
|
|
|
|
self.assertTrue(os.path.exists(file1))
|
|
|
|
|
2023-12-05 11:40:49 -04:00
|
|
|
def test_rmtree_errors(self):
|
2003-01-24 13:34:13 -04:00
|
|
|
# filename is guaranteed not to exist
|
2019-11-15 13:49:21 -04:00
|
|
|
filename = tempfile.mktemp(dir=self.mkdtemp())
|
2012-12-10 04:11:25 -04:00
|
|
|
self.assertRaises(FileNotFoundError, shutil.rmtree, filename)
|
|
|
|
# test that ignore_errors option is honored
|
2012-12-10 04:00:09 -04:00
|
|
|
shutil.rmtree(filename, ignore_errors=True)
|
|
|
|
|
|
|
|
# existing file
|
|
|
|
tmpdir = self.mkdtemp()
|
|
|
|
filename = os.path.join(tmpdir, "tstfile")
|
2023-12-05 11:40:49 -04:00
|
|
|
write_file(filename, "")
|
2012-12-10 04:11:25 -04:00
|
|
|
with self.assertRaises(NotADirectoryError) as cm:
|
2012-12-10 04:00:09 -04:00
|
|
|
shutil.rmtree(filename)
|
2020-12-21 02:38:02 -04:00
|
|
|
self.assertEqual(cm.exception.filename, filename)
|
2012-12-10 04:00:09 -04:00
|
|
|
self.assertTrue(os.path.exists(filename))
|
2012-12-10 04:11:25 -04:00
|
|
|
# test that ignore_errors option is honored
|
2012-12-10 04:00:09 -04:00
|
|
|
shutil.rmtree(filename, ignore_errors=True)
|
|
|
|
self.assertTrue(os.path.exists(filename))
|
2023-12-05 11:40:49 -04:00
|
|
|
|
|
|
|
self.assertRaises(TypeError, shutil.rmtree, None)
|
|
|
|
self.assertRaises(TypeError, shutil.rmtree, None, ignore_errors=True)
|
|
|
|
exc = TypeError if shutil.rmtree.avoids_symlink_attacks else NotImplementedError
|
|
|
|
with self.assertRaises(exc):
|
|
|
|
shutil.rmtree(filename, dir_fd='invalid')
|
|
|
|
with self.assertRaises(exc):
|
|
|
|
shutil.rmtree(filename, dir_fd='invalid', ignore_errors=True)
|
|
|
|
|
|
|
|
def test_rmtree_errors_onerror(self):
|
|
|
|
tmpdir = self.mkdtemp()
|
|
|
|
filename = os.path.join(tmpdir, "tstfile")
|
|
|
|
write_file(filename, "")
|
2012-12-10 04:00:09 -04:00
|
|
|
errors = []
|
|
|
|
def onerror(*args):
|
|
|
|
errors.append(args)
|
2023-12-03 10:02:37 -04:00
|
|
|
shutil.rmtree(filename, onerror=onerror)
|
2012-12-10 04:00:09 -04:00
|
|
|
self.assertEqual(len(errors), 2)
|
2017-11-04 09:16:35 -03:00
|
|
|
self.assertIs(errors[0][0], os.scandir)
|
2012-12-10 04:00:09 -04:00
|
|
|
self.assertEqual(errors[0][1], filename)
|
2012-12-10 04:11:25 -04:00
|
|
|
self.assertIsInstance(errors[0][2][1], NotADirectoryError)
|
2020-12-21 02:38:02 -04:00
|
|
|
self.assertEqual(errors[0][2][1].filename, filename)
|
2012-12-10 04:00:09 -04:00
|
|
|
self.assertIs(errors[1][0], os.rmdir)
|
|
|
|
self.assertEqual(errors[1][1], filename)
|
2012-12-10 04:11:25 -04:00
|
|
|
self.assertIsInstance(errors[1][2][1], NotADirectoryError)
|
2020-12-21 02:38:02 -04:00
|
|
|
self.assertEqual(errors[1][2][1].filename, filename)
|
2004-10-31 08:05:31 -04:00
|
|
|
|
2023-03-19 15:33:51 -03:00
|
|
|
def test_rmtree_errors_onexc(self):
|
|
|
|
tmpdir = self.mkdtemp()
|
|
|
|
filename = os.path.join(tmpdir, "tstfile")
|
2023-12-05 11:40:49 -04:00
|
|
|
write_file(filename, "")
|
2023-03-19 15:33:51 -03:00
|
|
|
errors = []
|
|
|
|
def onexc(*args):
|
|
|
|
errors.append(args)
|
|
|
|
shutil.rmtree(filename, onexc=onexc)
|
|
|
|
self.assertEqual(len(errors), 2)
|
|
|
|
self.assertIs(errors[0][0], os.scandir)
|
|
|
|
self.assertEqual(errors[0][1], filename)
|
|
|
|
self.assertIsInstance(errors[0][2], NotADirectoryError)
|
|
|
|
self.assertEqual(errors[0][2].filename, filename)
|
|
|
|
self.assertIs(errors[1][0], os.rmdir)
|
|
|
|
self.assertEqual(errors[1][1], filename)
|
|
|
|
self.assertIsInstance(errors[1][2], NotADirectoryError)
|
|
|
|
self.assertEqual(errors[1][2].filename, filename)
|
2004-10-31 08:05:31 -04:00
|
|
|
|
2013-11-03 15:31:38 -04:00
|
|
|
@unittest.skipIf(sys.platform[:6] == 'cygwin',
|
|
|
|
"This test can't be run on Cygwin (issue #1071513).")
|
2022-06-27 15:27:19 -03:00
|
|
|
@os_helper.skip_if_dac_override
|
2022-06-06 14:24:11 -03:00
|
|
|
@os_helper.skip_unless_working_chmod
|
2013-11-03 15:31:38 -04:00
|
|
|
def test_on_error(self):
|
|
|
|
self.errorState = 0
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
self.addCleanup(shutil.rmtree, TESTFN)
|
|
|
|
|
|
|
|
self.child_file_path = os.path.join(TESTFN, 'a')
|
|
|
|
self.child_dir_path = os.path.join(TESTFN, 'b')
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.create_empty_file(self.child_file_path)
|
2013-11-03 15:31:38 -04:00
|
|
|
os.mkdir(self.child_dir_path)
|
|
|
|
old_dir_mode = os.stat(TESTFN).st_mode
|
|
|
|
old_child_file_mode = os.stat(self.child_file_path).st_mode
|
|
|
|
old_child_dir_mode = os.stat(self.child_dir_path).st_mode
|
|
|
|
# Make unwritable.
|
|
|
|
new_mode = stat.S_IREAD|stat.S_IEXEC
|
|
|
|
os.chmod(self.child_file_path, new_mode)
|
|
|
|
os.chmod(self.child_dir_path, new_mode)
|
|
|
|
os.chmod(TESTFN, new_mode)
|
|
|
|
|
|
|
|
self.addCleanup(os.chmod, TESTFN, old_dir_mode)
|
|
|
|
self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
|
|
|
|
self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
|
|
|
|
|
2023-12-03 10:02:37 -04:00
|
|
|
shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
|
2013-11-03 15:31:38 -04:00
|
|
|
# Test whether onerror has actually been called.
|
|
|
|
self.assertEqual(self.errorState, 3,
|
|
|
|
"Expected call to onerror function did not happen.")
|
2004-10-31 08:05:31 -04:00
|
|
|
|
|
|
|
def check_args_to_onerror(self, func, arg, exc):
|
Merged revisions 70768,71657,71721,71729,71794,71976,72036-72037,72079,72085,72131-72134,72191,72197-72198,72219,72221,72225,72303,72434,72467,72476 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r70768 | andrew.kuchling | 2009-03-30 17:29:15 -0500 (Mon, 30 Mar 2009) | 1 line
Typo fixes
........
r71657 | vinay.sajip | 2009-04-16 14:07:37 -0500 (Thu, 16 Apr 2009) | 1 line
Issue #5768: Change to Unicode output logic and test case for same.
........
r71721 | benjamin.peterson | 2009-04-18 14:26:19 -0500 (Sat, 18 Apr 2009) | 1 line
fix a few nits in unittest.py #5771
........
r71729 | benjamin.peterson | 2009-04-18 16:03:10 -0500 (Sat, 18 Apr 2009) | 1 line
move test to a more appropiate one
........
r71794 | vinay.sajip | 2009-04-22 07:10:47 -0500 (Wed, 22 Apr 2009) | 2 lines
Issue #5170: Fixed regression caused when fixing #5768.
........
r71976 | mark.dickinson | 2009-04-26 14:54:55 -0500 (Sun, 26 Apr 2009) | 2 lines
Fix typo in function name
........
r72036 | georg.brandl | 2009-04-27 12:04:23 -0500 (Mon, 27 Apr 2009) | 1 line
#5848: small unittest doc patch.
........
r72037 | georg.brandl | 2009-04-27 12:09:53 -0500 (Mon, 27 Apr 2009) | 1 line
#5840: dont claim we dont support TLS.
........
r72079 | r.david.murray | 2009-04-28 14:02:55 -0500 (Tue, 28 Apr 2009) | 2 lines
Remove spurious 'u'.
........
r72085 | georg.brandl | 2009-04-28 16:48:35 -0500 (Tue, 28 Apr 2009) | 1 line
Make the doctests in the docs pass, except for those in the turtle module.
........
r72131 | benjamin.peterson | 2009-04-29 17:43:35 -0500 (Wed, 29 Apr 2009) | 1 line
fix test_shutil on ZFS #5676
........
r72132 | georg.brandl | 2009-04-29 17:44:07 -0500 (Wed, 29 Apr 2009) | 1 line
#5878: fix repr of re object.
........
r72133 | benjamin.peterson | 2009-04-29 17:44:15 -0500 (Wed, 29 Apr 2009) | 1 line
make sure mode is removable while cleaning up test droppings
........
r72134 | benjamin.peterson | 2009-04-29 19:06:33 -0500 (Wed, 29 Apr 2009) | 1 line
make sure to close file
........
r72191 | michael.foord | 2009-05-02 06:43:06 -0500 (Sat, 02 May 2009) | 9 lines
Adds an exit parameter to unittest.main(). If False main no longer
calls sys.exit.
Closes issue 3379.
Michael Foord
........
r72197 | benjamin.peterson | 2009-05-02 11:24:37 -0500 (Sat, 02 May 2009) | 1 line
don't let sys.argv be used in the tests
........
r72198 | andrew.kuchling | 2009-05-02 12:12:15 -0500 (Sat, 02 May 2009) | 1 line
Add items
........
r72219 | michael.foord | 2009-05-02 15:15:05 -0500 (Sat, 02 May 2009) | 8 lines
Add addCleanup and doCleanups to unittest.TestCase.
Closes issue 5679.
Michael Foord
........
r72221 | benjamin.peterson | 2009-05-02 15:26:53 -0500 (Sat, 02 May 2009) | 1 line
add myself
........
r72225 | michael.foord | 2009-05-02 17:43:34 -0500 (Sat, 02 May 2009) | 1 line
........
r72303 | benjamin.peterson | 2009-05-04 19:55:24 -0500 (Mon, 04 May 2009) | 1 line
using sys._getframe(x), where x > 0 doesnt' work on IronPython
........
r72434 | r.david.murray | 2009-05-07 13:09:58 -0500 (Thu, 07 May 2009) | 2 lines
Pre-opened test file needs to be opened in binary mode.
........
r72467 | georg.brandl | 2009-05-08 07:17:34 -0500 (Fri, 08 May 2009) | 1 line
Fix name.
........
r72476 | thomas.heller | 2009-05-08 15:09:40 -0500 (Fri, 08 May 2009) | 4 lines
Add a file that contains diffs between offical libffi files and the
files in this repository. Should make it easier to merge new libffi
versions.
........
2009-05-08 17:42:26 -03:00
|
|
|
# test_rmtree_errors deliberately runs rmtree
|
2012-06-23 12:58:42 -03:00
|
|
|
# on a directory that is chmod 500, which will fail.
|
Merged revisions 70768,71657,71721,71729,71794,71976,72036-72037,72079,72085,72131-72134,72191,72197-72198,72219,72221,72225,72303,72434,72467,72476 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r70768 | andrew.kuchling | 2009-03-30 17:29:15 -0500 (Mon, 30 Mar 2009) | 1 line
Typo fixes
........
r71657 | vinay.sajip | 2009-04-16 14:07:37 -0500 (Thu, 16 Apr 2009) | 1 line
Issue #5768: Change to Unicode output logic and test case for same.
........
r71721 | benjamin.peterson | 2009-04-18 14:26:19 -0500 (Sat, 18 Apr 2009) | 1 line
fix a few nits in unittest.py #5771
........
r71729 | benjamin.peterson | 2009-04-18 16:03:10 -0500 (Sat, 18 Apr 2009) | 1 line
move test to a more appropiate one
........
r71794 | vinay.sajip | 2009-04-22 07:10:47 -0500 (Wed, 22 Apr 2009) | 2 lines
Issue #5170: Fixed regression caused when fixing #5768.
........
r71976 | mark.dickinson | 2009-04-26 14:54:55 -0500 (Sun, 26 Apr 2009) | 2 lines
Fix typo in function name
........
r72036 | georg.brandl | 2009-04-27 12:04:23 -0500 (Mon, 27 Apr 2009) | 1 line
#5848: small unittest doc patch.
........
r72037 | georg.brandl | 2009-04-27 12:09:53 -0500 (Mon, 27 Apr 2009) | 1 line
#5840: dont claim we dont support TLS.
........
r72079 | r.david.murray | 2009-04-28 14:02:55 -0500 (Tue, 28 Apr 2009) | 2 lines
Remove spurious 'u'.
........
r72085 | georg.brandl | 2009-04-28 16:48:35 -0500 (Tue, 28 Apr 2009) | 1 line
Make the doctests in the docs pass, except for those in the turtle module.
........
r72131 | benjamin.peterson | 2009-04-29 17:43:35 -0500 (Wed, 29 Apr 2009) | 1 line
fix test_shutil on ZFS #5676
........
r72132 | georg.brandl | 2009-04-29 17:44:07 -0500 (Wed, 29 Apr 2009) | 1 line
#5878: fix repr of re object.
........
r72133 | benjamin.peterson | 2009-04-29 17:44:15 -0500 (Wed, 29 Apr 2009) | 1 line
make sure mode is removable while cleaning up test droppings
........
r72134 | benjamin.peterson | 2009-04-29 19:06:33 -0500 (Wed, 29 Apr 2009) | 1 line
make sure to close file
........
r72191 | michael.foord | 2009-05-02 06:43:06 -0500 (Sat, 02 May 2009) | 9 lines
Adds an exit parameter to unittest.main(). If False main no longer
calls sys.exit.
Closes issue 3379.
Michael Foord
........
r72197 | benjamin.peterson | 2009-05-02 11:24:37 -0500 (Sat, 02 May 2009) | 1 line
don't let sys.argv be used in the tests
........
r72198 | andrew.kuchling | 2009-05-02 12:12:15 -0500 (Sat, 02 May 2009) | 1 line
Add items
........
r72219 | michael.foord | 2009-05-02 15:15:05 -0500 (Sat, 02 May 2009) | 8 lines
Add addCleanup and doCleanups to unittest.TestCase.
Closes issue 5679.
Michael Foord
........
r72221 | benjamin.peterson | 2009-05-02 15:26:53 -0500 (Sat, 02 May 2009) | 1 line
add myself
........
r72225 | michael.foord | 2009-05-02 17:43:34 -0500 (Sat, 02 May 2009) | 1 line
........
r72303 | benjamin.peterson | 2009-05-04 19:55:24 -0500 (Mon, 04 May 2009) | 1 line
using sys._getframe(x), where x > 0 doesnt' work on IronPython
........
r72434 | r.david.murray | 2009-05-07 13:09:58 -0500 (Thu, 07 May 2009) | 2 lines
Pre-opened test file needs to be opened in binary mode.
........
r72467 | georg.brandl | 2009-05-08 07:17:34 -0500 (Fri, 08 May 2009) | 1 line
Fix name.
........
r72476 | thomas.heller | 2009-05-08 15:09:40 -0500 (Fri, 08 May 2009) | 4 lines
Add a file that contains diffs between offical libffi files and the
files in this repository. Should make it easier to merge new libffi
versions.
........
2009-05-08 17:42:26 -03:00
|
|
|
# This function is run when shutil.rmtree fails.
|
|
|
|
# 99.9% of the time it initially fails to remove
|
|
|
|
# a file in the directory, so the first time through
|
|
|
|
# func is os.remove.
|
|
|
|
# However, some Linux machines running ZFS on
|
|
|
|
# FUSE experienced a failure earlier in the process
|
|
|
|
# at os.listdir. The first failure may legally
|
|
|
|
# be either.
|
2012-06-23 17:05:11 -03:00
|
|
|
if self.errorState < 2:
|
2012-06-23 15:28:32 -03:00
|
|
|
if func is os.unlink:
|
2012-06-23 17:05:11 -03:00
|
|
|
self.assertEqual(arg, self.child_file_path)
|
|
|
|
elif func is os.rmdir:
|
|
|
|
self.assertEqual(arg, self.child_dir_path)
|
Merged revisions 70768,71657,71721,71729,71794,71976,72036-72037,72079,72085,72131-72134,72191,72197-72198,72219,72221,72225,72303,72434,72467,72476 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r70768 | andrew.kuchling | 2009-03-30 17:29:15 -0500 (Mon, 30 Mar 2009) | 1 line
Typo fixes
........
r71657 | vinay.sajip | 2009-04-16 14:07:37 -0500 (Thu, 16 Apr 2009) | 1 line
Issue #5768: Change to Unicode output logic and test case for same.
........
r71721 | benjamin.peterson | 2009-04-18 14:26:19 -0500 (Sat, 18 Apr 2009) | 1 line
fix a few nits in unittest.py #5771
........
r71729 | benjamin.peterson | 2009-04-18 16:03:10 -0500 (Sat, 18 Apr 2009) | 1 line
move test to a more appropiate one
........
r71794 | vinay.sajip | 2009-04-22 07:10:47 -0500 (Wed, 22 Apr 2009) | 2 lines
Issue #5170: Fixed regression caused when fixing #5768.
........
r71976 | mark.dickinson | 2009-04-26 14:54:55 -0500 (Sun, 26 Apr 2009) | 2 lines
Fix typo in function name
........
r72036 | georg.brandl | 2009-04-27 12:04:23 -0500 (Mon, 27 Apr 2009) | 1 line
#5848: small unittest doc patch.
........
r72037 | georg.brandl | 2009-04-27 12:09:53 -0500 (Mon, 27 Apr 2009) | 1 line
#5840: dont claim we dont support TLS.
........
r72079 | r.david.murray | 2009-04-28 14:02:55 -0500 (Tue, 28 Apr 2009) | 2 lines
Remove spurious 'u'.
........
r72085 | georg.brandl | 2009-04-28 16:48:35 -0500 (Tue, 28 Apr 2009) | 1 line
Make the doctests in the docs pass, except for those in the turtle module.
........
r72131 | benjamin.peterson | 2009-04-29 17:43:35 -0500 (Wed, 29 Apr 2009) | 1 line
fix test_shutil on ZFS #5676
........
r72132 | georg.brandl | 2009-04-29 17:44:07 -0500 (Wed, 29 Apr 2009) | 1 line
#5878: fix repr of re object.
........
r72133 | benjamin.peterson | 2009-04-29 17:44:15 -0500 (Wed, 29 Apr 2009) | 1 line
make sure mode is removable while cleaning up test droppings
........
r72134 | benjamin.peterson | 2009-04-29 19:06:33 -0500 (Wed, 29 Apr 2009) | 1 line
make sure to close file
........
r72191 | michael.foord | 2009-05-02 06:43:06 -0500 (Sat, 02 May 2009) | 9 lines
Adds an exit parameter to unittest.main(). If False main no longer
calls sys.exit.
Closes issue 3379.
Michael Foord
........
r72197 | benjamin.peterson | 2009-05-02 11:24:37 -0500 (Sat, 02 May 2009) | 1 line
don't let sys.argv be used in the tests
........
r72198 | andrew.kuchling | 2009-05-02 12:12:15 -0500 (Sat, 02 May 2009) | 1 line
Add items
........
r72219 | michael.foord | 2009-05-02 15:15:05 -0500 (Sat, 02 May 2009) | 8 lines
Add addCleanup and doCleanups to unittest.TestCase.
Closes issue 5679.
Michael Foord
........
r72221 | benjamin.peterson | 2009-05-02 15:26:53 -0500 (Sat, 02 May 2009) | 1 line
add myself
........
r72225 | michael.foord | 2009-05-02 17:43:34 -0500 (Sat, 02 May 2009) | 1 line
........
r72303 | benjamin.peterson | 2009-05-04 19:55:24 -0500 (Mon, 04 May 2009) | 1 line
using sys._getframe(x), where x > 0 doesnt' work on IronPython
........
r72434 | r.david.murray | 2009-05-07 13:09:58 -0500 (Thu, 07 May 2009) | 2 lines
Pre-opened test file needs to be opened in binary mode.
........
r72467 | georg.brandl | 2009-05-08 07:17:34 -0500 (Fri, 08 May 2009) | 1 line
Fix name.
........
r72476 | thomas.heller | 2009-05-08 15:09:40 -0500 (Fri, 08 May 2009) | 4 lines
Add a file that contains diffs between offical libffi files and the
files in this repository. Should make it easier to merge new libffi
versions.
........
2009-05-08 17:42:26 -03:00
|
|
|
else:
|
2012-06-23 17:05:11 -03:00
|
|
|
self.assertIs(func, os.listdir)
|
2012-06-23 12:58:42 -03:00
|
|
|
self.assertIn(arg, [TESTFN, self.child_dir_path])
|
2009-06-30 20:06:06 -03:00
|
|
|
self.assertTrue(issubclass(exc[0], OSError))
|
2012-06-23 12:58:42 -03:00
|
|
|
self.errorState += 1
|
2004-10-31 08:05:31 -04:00
|
|
|
else:
|
|
|
|
self.assertEqual(func, os.rmdir)
|
|
|
|
self.assertEqual(arg, TESTFN)
|
2009-06-30 20:06:06 -03:00
|
|
|
self.assertTrue(issubclass(exc[0], OSError))
|
2012-06-23 12:58:42 -03:00
|
|
|
self.errorState = 3
|
|
|
|
|
2023-03-19 15:33:51 -03:00
|
|
|
@unittest.skipIf(sys.platform[:6] == 'cygwin',
|
|
|
|
"This test can't be run on Cygwin (issue #1071513).")
|
|
|
|
@os_helper.skip_if_dac_override
|
|
|
|
@os_helper.skip_unless_working_chmod
|
|
|
|
def test_on_exc(self):
|
|
|
|
self.errorState = 0
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
self.addCleanup(shutil.rmtree, TESTFN)
|
|
|
|
|
|
|
|
self.child_file_path = os.path.join(TESTFN, 'a')
|
|
|
|
self.child_dir_path = os.path.join(TESTFN, 'b')
|
|
|
|
os_helper.create_empty_file(self.child_file_path)
|
|
|
|
os.mkdir(self.child_dir_path)
|
|
|
|
old_dir_mode = os.stat(TESTFN).st_mode
|
|
|
|
old_child_file_mode = os.stat(self.child_file_path).st_mode
|
|
|
|
old_child_dir_mode = os.stat(self.child_dir_path).st_mode
|
|
|
|
# Make unwritable.
|
|
|
|
new_mode = stat.S_IREAD|stat.S_IEXEC
|
|
|
|
os.chmod(self.child_file_path, new_mode)
|
|
|
|
os.chmod(self.child_dir_path, new_mode)
|
|
|
|
os.chmod(TESTFN, new_mode)
|
|
|
|
|
|
|
|
self.addCleanup(os.chmod, TESTFN, old_dir_mode)
|
|
|
|
self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
|
|
|
|
self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
|
|
|
|
|
|
|
|
shutil.rmtree(TESTFN, onexc=self.check_args_to_onexc)
|
|
|
|
# Test whether onexc has actually been called.
|
|
|
|
self.assertEqual(self.errorState, 3,
|
|
|
|
"Expected call to onexc function did not happen.")
|
|
|
|
|
|
|
|
def check_args_to_onexc(self, func, arg, exc):
|
|
|
|
# test_rmtree_errors deliberately runs rmtree
|
|
|
|
# on a directory that is chmod 500, which will fail.
|
|
|
|
# This function is run when shutil.rmtree fails.
|
|
|
|
# 99.9% of the time it initially fails to remove
|
|
|
|
# a file in the directory, so the first time through
|
|
|
|
# func is os.remove.
|
|
|
|
# However, some Linux machines running ZFS on
|
|
|
|
# FUSE experienced a failure earlier in the process
|
|
|
|
# at os.listdir. The first failure may legally
|
|
|
|
# be either.
|
|
|
|
if self.errorState < 2:
|
|
|
|
if func is os.unlink:
|
|
|
|
self.assertEqual(arg, self.child_file_path)
|
|
|
|
elif func is os.rmdir:
|
|
|
|
self.assertEqual(arg, self.child_dir_path)
|
|
|
|
else:
|
|
|
|
self.assertIs(func, os.listdir)
|
|
|
|
self.assertIn(arg, [TESTFN, self.child_dir_path])
|
|
|
|
self.assertTrue(isinstance(exc, OSError))
|
|
|
|
self.errorState += 1
|
|
|
|
else:
|
|
|
|
self.assertEqual(func, os.rmdir)
|
|
|
|
self.assertEqual(arg, TESTFN)
|
|
|
|
self.assertTrue(isinstance(exc, OSError))
|
|
|
|
self.errorState = 3
|
|
|
|
|
2023-03-19 21:03:55 -03:00
|
|
|
@unittest.skipIf(sys.platform[:6] == 'cygwin',
|
|
|
|
"This test can't be run on Cygwin (issue #1071513).")
|
|
|
|
@os_helper.skip_if_dac_override
|
|
|
|
@os_helper.skip_unless_working_chmod
|
2023-03-19 15:33:51 -03:00
|
|
|
def test_both_onerror_and_onexc(self):
|
|
|
|
onerror_called = False
|
|
|
|
onexc_called = False
|
|
|
|
|
|
|
|
def onerror(*args):
|
|
|
|
nonlocal onerror_called
|
|
|
|
onerror_called = True
|
|
|
|
|
|
|
|
def onexc(*args):
|
|
|
|
nonlocal onexc_called
|
|
|
|
onexc_called = True
|
|
|
|
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
self.addCleanup(shutil.rmtree, TESTFN)
|
|
|
|
|
|
|
|
self.child_file_path = os.path.join(TESTFN, 'a')
|
|
|
|
self.child_dir_path = os.path.join(TESTFN, 'b')
|
|
|
|
os_helper.create_empty_file(self.child_file_path)
|
|
|
|
os.mkdir(self.child_dir_path)
|
|
|
|
old_dir_mode = os.stat(TESTFN).st_mode
|
|
|
|
old_child_file_mode = os.stat(self.child_file_path).st_mode
|
|
|
|
old_child_dir_mode = os.stat(self.child_dir_path).st_mode
|
|
|
|
# Make unwritable.
|
|
|
|
new_mode = stat.S_IREAD|stat.S_IEXEC
|
|
|
|
os.chmod(self.child_file_path, new_mode)
|
|
|
|
os.chmod(self.child_dir_path, new_mode)
|
|
|
|
os.chmod(TESTFN, new_mode)
|
|
|
|
|
|
|
|
self.addCleanup(os.chmod, TESTFN, old_dir_mode)
|
|
|
|
self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
|
|
|
|
self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
|
|
|
|
|
2023-12-03 10:02:37 -04:00
|
|
|
shutil.rmtree(TESTFN, onerror=onerror, onexc=onexc)
|
2023-03-19 15:33:51 -03:00
|
|
|
self.assertTrue(onexc_called)
|
|
|
|
self.assertFalse(onerror_called)
|
|
|
|
|
2012-06-23 12:58:42 -03:00
|
|
|
def test_rmtree_does_not_choke_on_failing_lstat(self):
|
|
|
|
try:
|
|
|
|
orig_lstat = os.lstat
|
2012-06-28 07:07:29 -03:00
|
|
|
def raiser(fn, *args, **kwargs):
|
2012-06-23 12:58:42 -03:00
|
|
|
if fn != TESTFN:
|
|
|
|
raise OSError()
|
|
|
|
else:
|
|
|
|
return orig_lstat(fn)
|
|
|
|
os.lstat = raiser
|
|
|
|
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
write_file((TESTFN, 'foo'), 'foo')
|
|
|
|
shutil.rmtree(TESTFN)
|
|
|
|
finally:
|
|
|
|
os.lstat = orig_lstat
|
2003-01-24 13:34:13 -04:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_rmtree_uses_safe_fd_version_if_available(self):
|
|
|
|
_use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
|
|
|
|
os.supports_dir_fd and
|
|
|
|
os.listdir in os.supports_fd and
|
|
|
|
os.stat in os.supports_follow_symlinks)
|
|
|
|
if _use_fd_functions:
|
|
|
|
self.assertTrue(shutil.rmtree.avoids_symlink_attacks)
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
d = os.path.join(tmp_dir, 'a')
|
|
|
|
os.mkdir(d)
|
|
|
|
try:
|
2024-06-18 18:15:18 -03:00
|
|
|
real_open = os.open
|
2019-09-26 07:15:08 -03:00
|
|
|
class Called(Exception): pass
|
|
|
|
def _raiser(*args, **kwargs):
|
|
|
|
raise Called
|
2024-06-18 18:15:18 -03:00
|
|
|
os.open = _raiser
|
2019-09-26 07:15:08 -03:00
|
|
|
self.assertRaises(Called, shutil.rmtree, d)
|
|
|
|
finally:
|
2024-06-18 18:15:18 -03:00
|
|
|
os.open = real_open
|
2019-09-26 07:15:08 -03:00
|
|
|
else:
|
|
|
|
self.assertFalse(shutil.rmtree.avoids_symlink_attacks)
|
2011-12-29 13:54:15 -04:00
|
|
|
|
2024-06-18 18:15:18 -03:00
|
|
|
@unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks, "requires safe rmtree")
|
2023-12-05 13:09:39 -04:00
|
|
|
def test_rmtree_fails_on_close(self):
|
|
|
|
# Test that the error handler is called for failed os.close() and that
|
|
|
|
# os.close() is only called once for a file descriptor.
|
|
|
|
tmp = self.mkdtemp()
|
|
|
|
dir1 = os.path.join(tmp, 'dir1')
|
|
|
|
os.mkdir(dir1)
|
|
|
|
dir2 = os.path.join(dir1, 'dir2')
|
|
|
|
os.mkdir(dir2)
|
|
|
|
def close(fd):
|
|
|
|
orig_close(fd)
|
|
|
|
nonlocal close_count
|
|
|
|
close_count += 1
|
|
|
|
raise OSError
|
|
|
|
|
|
|
|
close_count = 0
|
|
|
|
with support.swap_attr(os, 'close', close) as orig_close:
|
|
|
|
with self.assertRaises(OSError):
|
|
|
|
shutil.rmtree(dir1)
|
|
|
|
self.assertTrue(os.path.isdir(dir2))
|
|
|
|
self.assertEqual(close_count, 2)
|
|
|
|
|
|
|
|
close_count = 0
|
|
|
|
errors = []
|
|
|
|
def onexc(*args):
|
|
|
|
errors.append(args)
|
|
|
|
with support.swap_attr(os, 'close', close) as orig_close:
|
|
|
|
shutil.rmtree(dir1, onexc=onexc)
|
|
|
|
self.assertEqual(len(errors), 2)
|
|
|
|
self.assertIs(errors[0][0], close)
|
|
|
|
self.assertEqual(errors[0][1], dir2)
|
|
|
|
self.assertIs(errors[1][0], close)
|
|
|
|
self.assertEqual(errors[1][1], dir1)
|
|
|
|
self.assertEqual(close_count, 2)
|
|
|
|
|
2024-06-18 18:15:18 -03:00
|
|
|
@unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks, "dir_fd is not supported")
|
2022-03-09 08:29:33 -04:00
|
|
|
def test_rmtree_with_dir_fd(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
victim = 'killme'
|
|
|
|
fullname = os.path.join(tmp_dir, victim)
|
|
|
|
dir_fd = os.open(tmp_dir, os.O_RDONLY)
|
|
|
|
self.addCleanup(os.close, dir_fd)
|
|
|
|
os.mkdir(fullname)
|
|
|
|
os.mkdir(os.path.join(fullname, 'subdir'))
|
|
|
|
write_file(os.path.join(fullname, 'subdir', 'somefile'), 'foo')
|
|
|
|
self.assertTrue(os.path.exists(fullname))
|
|
|
|
shutil.rmtree(victim, dir_fd=dir_fd)
|
|
|
|
self.assertFalse(os.path.exists(fullname))
|
|
|
|
|
2024-06-18 18:15:18 -03:00
|
|
|
@unittest.skipIf(shutil.rmtree.avoids_symlink_attacks, "dir_fd is supported")
|
2022-03-09 08:29:33 -04:00
|
|
|
def test_rmtree_with_dir_fd_unsupported(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
with self.assertRaises(NotImplementedError):
|
|
|
|
shutil.rmtree(tmp_dir, dir_fd=0)
|
|
|
|
self.assertTrue(os.path.exists(tmp_dir))
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_rmtree_dont_delete_file(self):
|
|
|
|
# When called on a file instead of a directory, don't delete it.
|
2019-11-15 13:49:21 -04:00
|
|
|
handle, path = tempfile.mkstemp(dir=self.mkdtemp())
|
2019-09-26 07:15:08 -03:00
|
|
|
os.close(handle)
|
|
|
|
self.assertRaises(NotADirectoryError, shutil.rmtree, path)
|
|
|
|
os.remove(path)
|
2011-12-29 13:54:15 -04:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_rmtree_on_symlink(self):
|
|
|
|
# bug 1669.
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
try:
|
|
|
|
src = os.path.join(TESTFN, 'cheese')
|
|
|
|
dst = os.path.join(TESTFN, 'shop')
|
|
|
|
os.mkdir(src)
|
|
|
|
os.symlink(src, dst)
|
|
|
|
self.assertRaises(OSError, shutil.rmtree, dst)
|
|
|
|
shutil.rmtree(dst, ignore_errors=True)
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(TESTFN, ignore_errors=True)
|
|
|
|
|
|
|
|
@unittest.skipUnless(_winapi, 'only relevant on Windows')
|
|
|
|
def test_rmtree_on_junction(self):
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
try:
|
|
|
|
src = os.path.join(TESTFN, 'cheese')
|
|
|
|
dst = os.path.join(TESTFN, 'shop')
|
|
|
|
os.mkdir(src)
|
|
|
|
open(os.path.join(src, 'spam'), 'wb').close()
|
|
|
|
_winapi.CreateJunction(src, dst)
|
|
|
|
self.assertRaises(OSError, shutil.rmtree, dst)
|
|
|
|
shutil.rmtree(dst, ignore_errors=True)
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(TESTFN, ignore_errors=True)
|
|
|
|
|
2024-03-13 06:40:28 -03:00
|
|
|
@unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
|
|
|
|
@unittest.skipIf(sys.platform == "vxworks",
|
|
|
|
"fifo requires special path on VxWorks")
|
|
|
|
def test_rmtree_on_named_pipe(self):
|
|
|
|
os.mkfifo(TESTFN)
|
|
|
|
try:
|
|
|
|
with self.assertRaises(NotADirectoryError):
|
|
|
|
shutil.rmtree(TESTFN)
|
|
|
|
self.assertTrue(os.path.exists(TESTFN))
|
|
|
|
finally:
|
|
|
|
os.unlink(TESTFN)
|
|
|
|
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
os.mkfifo(os.path.join(TESTFN, 'mypipe'))
|
|
|
|
shutil.rmtree(TESTFN)
|
|
|
|
self.assertFalse(os.path.exists(TESTFN))
|
|
|
|
|
2023-12-05 05:33:51 -04:00
|
|
|
@unittest.skipIf(sys.platform[:6] == 'cygwin',
|
|
|
|
"This test can't be run on Cygwin (issue #1071513).")
|
|
|
|
@os_helper.skip_if_dac_override
|
|
|
|
@os_helper.skip_unless_working_chmod
|
|
|
|
def test_rmtree_deleted_race_condition(self):
|
|
|
|
# bpo-37260
|
|
|
|
#
|
|
|
|
# Test that a file or a directory deleted after it is enumerated
|
|
|
|
# by scandir() but before unlink() or rmdr() is called doesn't
|
|
|
|
# generate any errors.
|
|
|
|
def _onexc(fn, path, exc):
|
|
|
|
assert fn in (os.rmdir, os.unlink)
|
|
|
|
if not isinstance(exc, PermissionError):
|
|
|
|
raise
|
|
|
|
# Make the parent and the children writeable.
|
|
|
|
for p, mode in zip(paths, old_modes):
|
|
|
|
os.chmod(p, mode)
|
|
|
|
# Remove other dirs except one.
|
|
|
|
keep = next(p for p in dirs if p != path)
|
|
|
|
for p in dirs:
|
|
|
|
if p != keep:
|
|
|
|
os.rmdir(p)
|
|
|
|
# Remove other files except one.
|
|
|
|
keep = next(p for p in files if p != path)
|
|
|
|
for p in files:
|
|
|
|
if p != keep:
|
|
|
|
os.unlink(p)
|
|
|
|
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
paths = [TESTFN] + [os.path.join(TESTFN, f'child{i}')
|
|
|
|
for i in range(6)]
|
|
|
|
dirs = paths[1::2]
|
|
|
|
files = paths[2::2]
|
|
|
|
for path in dirs:
|
|
|
|
os.mkdir(path)
|
|
|
|
for path in files:
|
|
|
|
write_file(path, '')
|
|
|
|
|
|
|
|
old_modes = [os.stat(path).st_mode for path in paths]
|
|
|
|
|
|
|
|
# Make the parent and the children non-writeable.
|
|
|
|
new_mode = stat.S_IREAD|stat.S_IEXEC
|
|
|
|
for path in reversed(paths):
|
|
|
|
os.chmod(path, new_mode)
|
|
|
|
|
|
|
|
try:
|
|
|
|
shutil.rmtree(TESTFN, onexc=_onexc)
|
|
|
|
except:
|
|
|
|
# Test failed, so cleanup artifacts.
|
|
|
|
for path, mode in zip(paths, old_modes):
|
|
|
|
try:
|
|
|
|
os.chmod(path, mode)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
shutil.rmtree(TESTFN)
|
|
|
|
raise
|
|
|
|
|
2024-05-29 17:11:30 -03:00
|
|
|
def test_rmtree_above_recursion_limit(self):
|
|
|
|
recursion_limit = 40
|
|
|
|
# directory_depth > recursion_limit
|
|
|
|
directory_depth = recursion_limit + 10
|
|
|
|
base = os.path.join(TESTFN, *(['d'] * directory_depth))
|
|
|
|
os.makedirs(base)
|
|
|
|
|
|
|
|
with support.infinite_recursion(recursion_limit):
|
|
|
|
shutil.rmtree(TESTFN)
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
|
|
|
|
class TestCopyTree(BaseTest, unittest.TestCase):
|
|
|
|
|
|
|
|
def test_copytree_simple(self):
|
2019-11-15 13:49:21 -04:00
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination')
|
2019-09-26 07:15:08 -03:00
|
|
|
self.addCleanup(shutil.rmtree, src_dir)
|
|
|
|
self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
|
|
|
|
write_file((src_dir, 'test.txt'), '123')
|
|
|
|
os.mkdir(os.path.join(src_dir, 'test_dir'))
|
|
|
|
write_file((src_dir, 'test_dir', 'test.txt'), '456')
|
|
|
|
|
|
|
|
shutil.copytree(src_dir, dst_dir)
|
|
|
|
self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
|
|
|
|
self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
|
|
|
|
self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
|
|
|
|
'test.txt')))
|
|
|
|
actual = read_file((dst_dir, 'test.txt'))
|
|
|
|
self.assertEqual(actual, '123')
|
|
|
|
actual = read_file((dst_dir, 'test_dir', 'test.txt'))
|
|
|
|
self.assertEqual(actual, '456')
|
|
|
|
|
|
|
|
def test_copytree_dirs_exist_ok(self):
|
2019-11-15 13:49:21 -04:00
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = self.mkdtemp()
|
2019-09-26 07:15:08 -03:00
|
|
|
self.addCleanup(shutil.rmtree, src_dir)
|
|
|
|
self.addCleanup(shutil.rmtree, dst_dir)
|
|
|
|
|
|
|
|
write_file((src_dir, 'nonexisting.txt'), '123')
|
|
|
|
os.mkdir(os.path.join(src_dir, 'existing_dir'))
|
|
|
|
os.mkdir(os.path.join(dst_dir, 'existing_dir'))
|
|
|
|
write_file((dst_dir, 'existing_dir', 'existing.txt'), 'will be replaced')
|
|
|
|
write_file((src_dir, 'existing_dir', 'existing.txt'), 'has been replaced')
|
|
|
|
|
|
|
|
shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True)
|
|
|
|
self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'nonexisting.txt')))
|
|
|
|
self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'existing_dir')))
|
|
|
|
self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'existing_dir',
|
|
|
|
'existing.txt')))
|
|
|
|
actual = read_file((dst_dir, 'nonexisting.txt'))
|
|
|
|
self.assertEqual(actual, '123')
|
|
|
|
actual = read_file((dst_dir, 'existing_dir', 'existing.txt'))
|
|
|
|
self.assertEqual(actual, 'has been replaced')
|
|
|
|
|
|
|
|
with self.assertRaises(FileExistsError):
|
|
|
|
shutil.copytree(src_dir, dst_dir, dirs_exist_ok=False)
|
2011-12-29 13:54:15 -04:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copytree_symlinks(self):
|
2011-12-29 13:54:15 -04:00
|
|
|
tmp_dir = self.mkdtemp()
|
2019-09-26 07:15:08 -03:00
|
|
|
src_dir = os.path.join(tmp_dir, 'src')
|
|
|
|
dst_dir = os.path.join(tmp_dir, 'dst')
|
|
|
|
sub_dir = os.path.join(src_dir, 'sub')
|
|
|
|
os.mkdir(src_dir)
|
|
|
|
os.mkdir(sub_dir)
|
|
|
|
write_file((src_dir, 'file.txt'), 'foo')
|
|
|
|
src_link = os.path.join(sub_dir, 'link')
|
|
|
|
dst_link = os.path.join(dst_dir, 'sub/link')
|
|
|
|
os.symlink(os.path.join(src_dir, 'file.txt'),
|
|
|
|
src_link)
|
2011-12-29 13:54:15 -04:00
|
|
|
if hasattr(os, 'lchmod'):
|
2019-09-26 07:15:08 -03:00
|
|
|
os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
|
2011-12-29 13:54:15 -04:00
|
|
|
if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
|
|
|
|
os.lchflags(src_link, stat.UF_NODUMP)
|
2019-09-26 07:15:08 -03:00
|
|
|
src_stat = os.lstat(src_link)
|
|
|
|
shutil.copytree(src_dir, dst_dir, symlinks=True)
|
|
|
|
self.assertTrue(os.path.islink(os.path.join(dst_dir, 'sub', 'link')))
|
|
|
|
actual = os.readlink(os.path.join(dst_dir, 'sub', 'link'))
|
|
|
|
# Bad practice to blindly strip the prefix as it may be required to
|
|
|
|
# correctly refer to the file, but we're only comparing paths here.
|
|
|
|
if os.name == 'nt' and actual.startswith('\\\\?\\'):
|
|
|
|
actual = actual[4:]
|
|
|
|
self.assertEqual(actual, os.path.join(src_dir, 'file.txt'))
|
|
|
|
dst_stat = os.lstat(dst_link)
|
2011-12-29 13:54:15 -04:00
|
|
|
if hasattr(os, 'lchmod'):
|
2019-09-26 07:15:08 -03:00
|
|
|
self.assertEqual(dst_stat.st_mode, src_stat.st_mode)
|
|
|
|
if hasattr(os, 'lchflags'):
|
|
|
|
self.assertEqual(dst_stat.st_flags, src_stat.st_flags)
|
2012-05-10 21:05:19 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copytree_with_exclude(self):
|
|
|
|
# creating data
|
|
|
|
join = os.path.join
|
|
|
|
exists = os.path.exists
|
2019-11-15 13:49:21 -04:00
|
|
|
src_dir = self.mkdtemp()
|
2019-09-26 07:15:08 -03:00
|
|
|
try:
|
2019-11-15 13:49:21 -04:00
|
|
|
dst_dir = join(self.mkdtemp(), 'destination')
|
2019-09-26 07:15:08 -03:00
|
|
|
write_file((src_dir, 'test.txt'), '123')
|
|
|
|
write_file((src_dir, 'test.tmp'), '123')
|
|
|
|
os.mkdir(join(src_dir, 'test_dir'))
|
|
|
|
write_file((src_dir, 'test_dir', 'test.txt'), '456')
|
|
|
|
os.mkdir(join(src_dir, 'test_dir2'))
|
|
|
|
write_file((src_dir, 'test_dir2', 'test.txt'), '456')
|
|
|
|
os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
|
|
|
|
os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
|
|
|
|
write_file((src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
|
|
|
|
write_file((src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
|
|
|
|
|
|
|
|
# testing glob-like patterns
|
|
|
|
try:
|
|
|
|
patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
|
|
|
|
shutil.copytree(src_dir, dst_dir, ignore=patterns)
|
|
|
|
# checking the result: some elements should not be copied
|
|
|
|
self.assertTrue(exists(join(dst_dir, 'test.txt')))
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test.tmp')))
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test_dir2')))
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(dst_dir)
|
|
|
|
try:
|
|
|
|
patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
|
|
|
|
shutil.copytree(src_dir, dst_dir, ignore=patterns)
|
|
|
|
# checking the result: some elements should not be copied
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test.tmp')))
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2')))
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(dst_dir)
|
|
|
|
|
|
|
|
# testing callable-style
|
|
|
|
try:
|
|
|
|
def _filter(src, names):
|
|
|
|
res = []
|
|
|
|
for name in names:
|
|
|
|
path = os.path.join(src, name)
|
|
|
|
|
|
|
|
if (os.path.isdir(path) and
|
|
|
|
path.split()[-1] == 'subdir'):
|
|
|
|
res.append(name)
|
|
|
|
elif os.path.splitext(path)[-1] in ('.py'):
|
|
|
|
res.append(name)
|
|
|
|
return res
|
|
|
|
|
|
|
|
shutil.copytree(src_dir, dst_dir, ignore=_filter)
|
|
|
|
|
|
|
|
# checking the result: some elements should not be copied
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2',
|
|
|
|
'test.py')))
|
|
|
|
self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
|
|
|
|
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(dst_dir)
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(src_dir)
|
|
|
|
shutil.rmtree(os.path.dirname(dst_dir))
|
|
|
|
|
2020-01-24 10:51:16 -04:00
|
|
|
def test_copytree_arg_types_of_ignore(self):
|
|
|
|
join = os.path.join
|
|
|
|
exists = os.path.exists
|
|
|
|
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src_dir = join(tmp_dir, "source")
|
|
|
|
|
|
|
|
os.mkdir(join(src_dir))
|
|
|
|
os.mkdir(join(src_dir, 'test_dir'))
|
|
|
|
os.mkdir(os.path.join(src_dir, 'test_dir', 'subdir'))
|
|
|
|
write_file((src_dir, 'test_dir', 'subdir', 'test.txt'), '456')
|
|
|
|
|
2024-07-17 04:24:35 -03:00
|
|
|
invocations = []
|
2020-01-24 10:51:16 -04:00
|
|
|
|
|
|
|
def _ignore(src, names):
|
2024-07-17 04:24:35 -03:00
|
|
|
invocations.append(src)
|
2020-01-24 10:51:16 -04:00
|
|
|
self.assertIsInstance(src, str)
|
|
|
|
self.assertIsInstance(names, list)
|
|
|
|
self.assertEqual(len(names), len(set(names)))
|
|
|
|
for name in names:
|
|
|
|
self.assertIsInstance(name, str)
|
|
|
|
return []
|
|
|
|
|
|
|
|
dst_dir = join(self.mkdtemp(), 'destination')
|
|
|
|
shutil.copytree(src_dir, dst_dir, ignore=_ignore)
|
|
|
|
self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
|
|
|
|
'test.txt')))
|
|
|
|
|
|
|
|
dst_dir = join(self.mkdtemp(), 'destination')
|
2024-05-16 04:25:10 -03:00
|
|
|
shutil.copytree(FakePath(src_dir), dst_dir, ignore=_ignore)
|
2020-01-24 10:51:16 -04:00
|
|
|
self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
|
|
|
|
'test.txt')))
|
|
|
|
|
|
|
|
dst_dir = join(self.mkdtemp(), 'destination')
|
|
|
|
src_dir_entry = list(os.scandir(tmp_dir))[0]
|
|
|
|
self.assertIsInstance(src_dir_entry, os.DirEntry)
|
|
|
|
shutil.copytree(src_dir_entry, dst_dir, ignore=_ignore)
|
|
|
|
self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
|
|
|
|
'test.txt')))
|
|
|
|
|
2024-07-17 04:24:35 -03:00
|
|
|
self.assertEqual(len(invocations), 9)
|
2020-01-24 10:51:16 -04:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copytree_retains_permissions(self):
|
2019-11-15 13:49:21 -04:00
|
|
|
tmp_dir = self.mkdtemp()
|
2019-09-26 07:15:08 -03:00
|
|
|
src_dir = os.path.join(tmp_dir, 'source')
|
|
|
|
os.mkdir(src_dir)
|
|
|
|
dst_dir = os.path.join(tmp_dir, 'destination')
|
|
|
|
self.addCleanup(shutil.rmtree, tmp_dir)
|
|
|
|
|
|
|
|
os.chmod(src_dir, 0o777)
|
|
|
|
write_file((src_dir, 'permissive.txt'), '123')
|
|
|
|
os.chmod(os.path.join(src_dir, 'permissive.txt'), 0o777)
|
|
|
|
write_file((src_dir, 'restrictive.txt'), '456')
|
|
|
|
os.chmod(os.path.join(src_dir, 'restrictive.txt'), 0o600)
|
|
|
|
restrictive_subdir = tempfile.mkdtemp(dir=src_dir)
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(os_helper.rmtree, restrictive_subdir)
|
2019-09-26 07:15:08 -03:00
|
|
|
os.chmod(restrictive_subdir, 0o600)
|
|
|
|
|
|
|
|
shutil.copytree(src_dir, dst_dir)
|
|
|
|
self.assertEqual(os.stat(src_dir).st_mode, os.stat(dst_dir).st_mode)
|
|
|
|
self.assertEqual(os.stat(os.path.join(src_dir, 'permissive.txt')).st_mode,
|
|
|
|
os.stat(os.path.join(dst_dir, 'permissive.txt')).st_mode)
|
|
|
|
self.assertEqual(os.stat(os.path.join(src_dir, 'restrictive.txt')).st_mode,
|
|
|
|
os.stat(os.path.join(dst_dir, 'restrictive.txt')).st_mode)
|
|
|
|
restrictive_subdir_dst = os.path.join(dst_dir,
|
|
|
|
os.path.split(restrictive_subdir)[1])
|
|
|
|
self.assertEqual(os.stat(restrictive_subdir).st_mode,
|
|
|
|
os.stat(restrictive_subdir_dst).st_mode)
|
|
|
|
|
|
|
|
@unittest.mock.patch('os.chmod')
|
|
|
|
def test_copytree_winerror(self, mock_patch):
|
|
|
|
# When copying to VFAT, copystat() raises OSError. On Windows, the
|
|
|
|
# exception object has a meaningful 'winerror' attribute, but not
|
|
|
|
# on other operating systems. Do not assume 'winerror' is set.
|
2019-11-15 13:49:21 -04:00
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination')
|
2019-09-26 07:15:08 -03:00
|
|
|
self.addCleanup(shutil.rmtree, src_dir)
|
|
|
|
self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
|
|
|
|
|
|
|
|
mock_patch.side_effect = PermissionError('ka-boom')
|
|
|
|
with self.assertRaises(shutil.Error):
|
|
|
|
shutil.copytree(src_dir, dst_dir)
|
|
|
|
|
|
|
|
def test_copytree_custom_copy_function(self):
|
|
|
|
# See: https://bugs.python.org/issue35648
|
|
|
|
def custom_cpfun(a, b):
|
|
|
|
flag.append(None)
|
|
|
|
self.assertIsInstance(a, str)
|
|
|
|
self.assertIsInstance(b, str)
|
|
|
|
self.assertEqual(a, os.path.join(src, 'foo'))
|
|
|
|
self.assertEqual(b, os.path.join(dst, 'foo'))
|
|
|
|
|
|
|
|
flag = []
|
2019-11-15 13:49:21 -04:00
|
|
|
src = self.mkdtemp()
|
|
|
|
dst = tempfile.mktemp(dir=self.mkdtemp())
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(os.path.join(src, 'foo'), 'w', encoding='utf-8') as f:
|
2019-09-26 07:15:08 -03:00
|
|
|
f.close()
|
|
|
|
shutil.copytree(src, dst, copy_function=custom_cpfun)
|
|
|
|
self.assertEqual(len(flag), 1)
|
|
|
|
|
|
|
|
# Issue #3002: copyfile and copytree block indefinitely on named pipes
|
|
|
|
@unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2020-11-28 18:06:36 -04:00
|
|
|
@unittest.skipIf(sys.platform == "vxworks",
|
|
|
|
"fifo requires special path on VxWorks")
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copytree_named_pipe(self):
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
try:
|
|
|
|
subdir = os.path.join(TESTFN, "subdir")
|
|
|
|
os.mkdir(subdir)
|
|
|
|
pipe = os.path.join(subdir, "mypipe")
|
|
|
|
try:
|
|
|
|
os.mkfifo(pipe)
|
|
|
|
except PermissionError as e:
|
|
|
|
self.skipTest('os.mkfifo(): %s' % e)
|
|
|
|
try:
|
|
|
|
shutil.copytree(TESTFN, TESTFN2)
|
|
|
|
except shutil.Error as e:
|
|
|
|
errors = e.args[0]
|
|
|
|
self.assertEqual(len(errors), 1)
|
|
|
|
src, dst, error_msg = errors[0]
|
|
|
|
self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
|
|
|
|
else:
|
|
|
|
self.fail("shutil.Error should have been raised")
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(TESTFN, ignore_errors=True)
|
|
|
|
shutil.rmtree(TESTFN2, ignore_errors=True)
|
|
|
|
|
|
|
|
def test_copytree_special_func(self):
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination')
|
|
|
|
write_file((src_dir, 'test.txt'), '123')
|
|
|
|
os.mkdir(os.path.join(src_dir, 'test_dir'))
|
|
|
|
write_file((src_dir, 'test_dir', 'test.txt'), '456')
|
|
|
|
|
|
|
|
copied = []
|
|
|
|
def _copy(src, dst):
|
|
|
|
copied.append((src, dst))
|
|
|
|
|
|
|
|
shutil.copytree(src_dir, dst_dir, copy_function=_copy)
|
|
|
|
self.assertEqual(len(copied), 2)
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copytree_dangling_symlinks(self):
|
|
|
|
src_dir = self.mkdtemp()
|
2022-11-07 07:45:16 -04:00
|
|
|
valid_file = os.path.join(src_dir, 'test.txt')
|
|
|
|
write_file(valid_file, 'abc')
|
|
|
|
dir_a = os.path.join(src_dir, 'dir_a')
|
|
|
|
os.mkdir(dir_a)
|
|
|
|
for d in src_dir, dir_a:
|
|
|
|
os.symlink('IDONTEXIST', os.path.join(d, 'broken'))
|
|
|
|
os.symlink(valid_file, os.path.join(d, 'valid'))
|
|
|
|
|
|
|
|
# A dangling symlink should raise an error.
|
2019-09-26 07:15:08 -03:00
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination')
|
|
|
|
self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
|
|
|
|
|
2022-11-07 07:45:16 -04:00
|
|
|
# Dangling symlinks should be ignored with the proper flag.
|
2019-09-26 07:15:08 -03:00
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination2')
|
|
|
|
shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
|
2022-11-07 07:45:16 -04:00
|
|
|
for root, dirs, files in os.walk(dst_dir):
|
|
|
|
self.assertNotIn('broken', files)
|
|
|
|
self.assertIn('valid', files)
|
2019-09-26 07:15:08 -03:00
|
|
|
|
|
|
|
# a dangling symlink is copied if symlinks=True
|
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination3')
|
|
|
|
shutil.copytree(src_dir, dst_dir, symlinks=True)
|
|
|
|
self.assertIn('test.txt', os.listdir(dst_dir))
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copytree_symlink_dir(self):
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination')
|
|
|
|
os.mkdir(os.path.join(src_dir, 'real_dir'))
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(os.path.join(src_dir, 'real_dir', 'test.txt'), 'wb'):
|
2019-09-26 07:15:08 -03:00
|
|
|
pass
|
|
|
|
os.symlink(os.path.join(src_dir, 'real_dir'),
|
|
|
|
os.path.join(src_dir, 'link_to_dir'),
|
|
|
|
target_is_directory=True)
|
|
|
|
|
|
|
|
shutil.copytree(src_dir, dst_dir, symlinks=False)
|
|
|
|
self.assertFalse(os.path.islink(os.path.join(dst_dir, 'link_to_dir')))
|
|
|
|
self.assertIn('test.txt', os.listdir(os.path.join(dst_dir, 'link_to_dir')))
|
|
|
|
|
|
|
|
dst_dir = os.path.join(self.mkdtemp(), 'destination2')
|
|
|
|
shutil.copytree(src_dir, dst_dir, symlinks=True)
|
|
|
|
self.assertTrue(os.path.islink(os.path.join(dst_dir, 'link_to_dir')))
|
|
|
|
self.assertIn('test.txt', os.listdir(os.path.join(dst_dir, 'link_to_dir')))
|
|
|
|
|
|
|
|
def test_copytree_return_value(self):
|
|
|
|
# copytree returns its destination path.
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = src_dir + "dest"
|
|
|
|
self.addCleanup(shutil.rmtree, dst_dir, True)
|
|
|
|
src = os.path.join(src_dir, 'foo')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
rv = shutil.copytree(src_dir, dst_dir)
|
|
|
|
self.assertEqual(['foo'], os.listdir(rv))
|
|
|
|
|
2019-11-26 21:10:37 -04:00
|
|
|
def test_copytree_subdirectory(self):
|
|
|
|
# copytree where dst is a subdirectory of src, see Issue 38688
|
|
|
|
base_dir = self.mkdtemp()
|
|
|
|
self.addCleanup(shutil.rmtree, base_dir, ignore_errors=True)
|
|
|
|
src_dir = os.path.join(base_dir, "t", "pg")
|
|
|
|
dst_dir = os.path.join(src_dir, "somevendor", "1.0")
|
|
|
|
os.makedirs(src_dir)
|
|
|
|
src = os.path.join(src_dir, 'pol')
|
|
|
|
write_file(src, 'pol')
|
|
|
|
rv = shutil.copytree(src_dir, dst_dir)
|
|
|
|
self.assertEqual(['pol'], os.listdir(rv))
|
2019-09-26 07:15:08 -03:00
|
|
|
|
|
|
|
class TestCopy(BaseTest, unittest.TestCase):
|
|
|
|
|
|
|
|
### shutil.copymode
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copymode_follow_symlinks(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
dst_link = os.path.join(tmp_dir, 'quux')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
write_file(dst, 'foo')
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
os.symlink(dst, dst_link)
|
|
|
|
os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
|
|
|
|
# file to file
|
|
|
|
os.chmod(dst, stat.S_IRWXO)
|
|
|
|
self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
|
|
|
shutil.copymode(src, dst)
|
|
|
|
self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
|
|
|
# On Windows, os.chmod does not follow symlinks (issue #15411)
|
2023-12-23 07:07:54 -04:00
|
|
|
# follow src link
|
|
|
|
os.chmod(dst, stat.S_IRWXO)
|
|
|
|
shutil.copymode(src_link, dst)
|
|
|
|
self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
|
|
|
# follow dst link
|
|
|
|
os.chmod(dst, stat.S_IRWXO)
|
|
|
|
shutil.copymode(src, dst_link)
|
|
|
|
self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
|
|
|
# follow both links
|
|
|
|
os.chmod(dst, stat.S_IRWXO)
|
|
|
|
shutil.copymode(src_link, dst_link)
|
|
|
|
self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
2019-09-26 07:15:08 -03:00
|
|
|
|
|
|
|
@unittest.skipUnless(hasattr(os, 'lchmod'), 'requires os.lchmod')
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copymode_symlink_to_symlink(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
dst_link = os.path.join(tmp_dir, 'quux')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
write_file(dst, 'foo')
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
os.symlink(dst, dst_link)
|
|
|
|
os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
|
|
|
|
os.chmod(dst, stat.S_IRWXU)
|
|
|
|
os.lchmod(src_link, stat.S_IRWXO|stat.S_IRWXG)
|
|
|
|
# link to link
|
|
|
|
os.lchmod(dst_link, stat.S_IRWXO)
|
2023-12-14 03:16:06 -04:00
|
|
|
old_mode = os.stat(dst).st_mode
|
2019-09-26 07:15:08 -03:00
|
|
|
shutil.copymode(src_link, dst_link, follow_symlinks=False)
|
|
|
|
self.assertEqual(os.lstat(src_link).st_mode,
|
|
|
|
os.lstat(dst_link).st_mode)
|
2023-12-14 03:16:06 -04:00
|
|
|
self.assertEqual(os.stat(dst).st_mode, old_mode)
|
2019-09-26 07:15:08 -03:00
|
|
|
# src link - use chmod
|
|
|
|
os.lchmod(dst_link, stat.S_IRWXO)
|
|
|
|
shutil.copymode(src_link, dst, follow_symlinks=False)
|
|
|
|
self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
|
|
|
# dst link - use chmod
|
|
|
|
os.lchmod(dst_link, stat.S_IRWXO)
|
|
|
|
shutil.copymode(src, dst_link, follow_symlinks=False)
|
|
|
|
self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
|
|
|
|
|
|
|
|
@unittest.skipIf(hasattr(os, 'lchmod'), 'requires os.lchmod to be missing')
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copymode_symlink_to_symlink_wo_lchmod(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
dst_link = os.path.join(tmp_dir, 'quux')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
write_file(dst, 'foo')
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
os.symlink(dst, dst_link)
|
|
|
|
shutil.copymode(src_link, dst_link, follow_symlinks=False) # silent fail
|
|
|
|
|
|
|
|
### shutil.copystat
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copystat_symlinks(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
dst_link = os.path.join(tmp_dir, 'qux')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
src_stat = os.stat(src)
|
|
|
|
os.utime(src, (src_stat.st_atime,
|
|
|
|
src_stat.st_mtime - 42.0)) # ensure different mtimes
|
|
|
|
write_file(dst, 'bar')
|
|
|
|
self.assertNotEqual(os.stat(src).st_mtime, os.stat(dst).st_mtime)
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
os.symlink(dst, dst_link)
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
os.lchmod(src_link, stat.S_IRWXO)
|
|
|
|
if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
|
|
|
|
os.lchflags(src_link, stat.UF_NODUMP)
|
|
|
|
src_link_stat = os.lstat(src_link)
|
|
|
|
# follow
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
shutil.copystat(src_link, dst_link, follow_symlinks=True)
|
|
|
|
self.assertNotEqual(src_link_stat.st_mode, os.stat(dst).st_mode)
|
|
|
|
# don't follow
|
|
|
|
shutil.copystat(src_link, dst_link, follow_symlinks=False)
|
|
|
|
dst_link_stat = os.lstat(dst_link)
|
|
|
|
if os.utime in os.supports_follow_symlinks:
|
|
|
|
for attr in 'st_atime', 'st_mtime':
|
|
|
|
# The modification times may be truncated in the new file.
|
|
|
|
self.assertLessEqual(getattr(src_link_stat, attr),
|
|
|
|
getattr(dst_link_stat, attr) + 1)
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
self.assertEqual(src_link_stat.st_mode, dst_link_stat.st_mode)
|
|
|
|
if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
|
|
|
|
self.assertEqual(src_link_stat.st_flags, dst_link_stat.st_flags)
|
|
|
|
# tell to follow but dst is not a link
|
|
|
|
shutil.copystat(src_link, dst, follow_symlinks=False)
|
|
|
|
self.assertTrue(abs(os.stat(src).st_mtime - os.stat(dst).st_mtime) <
|
|
|
|
00000.1)
|
|
|
|
|
|
|
|
@unittest.skipUnless(hasattr(os, 'chflags') and
|
|
|
|
hasattr(errno, 'EOPNOTSUPP') and
|
|
|
|
hasattr(errno, 'ENOTSUP'),
|
|
|
|
"requires os.chflags, EOPNOTSUPP & ENOTSUP")
|
|
|
|
def test_copystat_handles_harmless_chflags_errors(self):
|
|
|
|
tmpdir = self.mkdtemp()
|
|
|
|
file1 = os.path.join(tmpdir, 'file1')
|
|
|
|
file2 = os.path.join(tmpdir, 'file2')
|
|
|
|
write_file(file1, 'xxx')
|
|
|
|
write_file(file2, 'xxx')
|
|
|
|
|
|
|
|
def make_chflags_raiser(err):
|
|
|
|
ex = OSError()
|
|
|
|
|
|
|
|
def _chflags_raiser(path, flags, *, follow_symlinks=True):
|
|
|
|
ex.errno = err
|
|
|
|
raise ex
|
|
|
|
return _chflags_raiser
|
2012-05-10 21:05:19 -03:00
|
|
|
old_chflags = os.chflags
|
|
|
|
try:
|
|
|
|
for err in errno.EOPNOTSUPP, errno.ENOTSUP:
|
|
|
|
os.chflags = make_chflags_raiser(err)
|
|
|
|
shutil.copystat(file1, file2)
|
|
|
|
# assert others errors break it
|
|
|
|
os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
|
|
|
|
self.assertRaises(OSError, shutil.copystat, file1, file2)
|
|
|
|
finally:
|
|
|
|
os.chflags = old_chflags
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
### shutil.copyxattr
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_xattr
|
2012-05-12 14:02:01 -03:00
|
|
|
def test_copyxattr(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
write_file(dst, 'bar')
|
|
|
|
|
|
|
|
# no xattr == no problem
|
|
|
|
shutil._copyxattr(src, dst)
|
|
|
|
# common case
|
|
|
|
os.setxattr(src, 'user.foo', b'42')
|
|
|
|
os.setxattr(src, 'user.bar', b'43')
|
|
|
|
shutil._copyxattr(src, dst)
|
2014-01-17 16:01:22 -04:00
|
|
|
self.assertEqual(sorted(os.listxattr(src)), sorted(os.listxattr(dst)))
|
2012-05-12 14:02:01 -03:00
|
|
|
self.assertEqual(
|
|
|
|
os.getxattr(src, 'user.foo'),
|
|
|
|
os.getxattr(dst, 'user.foo'))
|
|
|
|
# check errors don't affect other attrs
|
|
|
|
os.remove(dst)
|
|
|
|
write_file(dst, 'bar')
|
|
|
|
os_error = OSError(errno.EPERM, 'EPERM')
|
|
|
|
|
2012-06-22 20:30:09 -03:00
|
|
|
def _raise_on_user_foo(fname, attr, val, **kwargs):
|
2012-05-12 14:02:01 -03:00
|
|
|
if attr == 'user.foo':
|
|
|
|
raise os_error
|
|
|
|
else:
|
2012-06-22 20:30:09 -03:00
|
|
|
orig_setxattr(fname, attr, val, **kwargs)
|
2012-05-12 14:02:01 -03:00
|
|
|
try:
|
|
|
|
orig_setxattr = os.setxattr
|
|
|
|
os.setxattr = _raise_on_user_foo
|
|
|
|
shutil._copyxattr(src, dst)
|
2012-05-12 18:37:35 -03:00
|
|
|
self.assertIn('user.bar', os.listxattr(dst))
|
2012-05-12 14:02:01 -03:00
|
|
|
finally:
|
|
|
|
os.setxattr = orig_setxattr
|
2013-02-05 03:22:44 -04:00
|
|
|
# the source filesystem not supporting xattrs should be ok, too.
|
|
|
|
def _raise_on_src(fname, *, follow_symlinks=True):
|
|
|
|
if fname == src:
|
|
|
|
raise OSError(errno.ENOTSUP, 'Operation not supported')
|
|
|
|
return orig_listxattr(fname, follow_symlinks=follow_symlinks)
|
|
|
|
try:
|
|
|
|
orig_listxattr = os.listxattr
|
|
|
|
os.listxattr = _raise_on_src
|
|
|
|
shutil._copyxattr(src, dst)
|
|
|
|
finally:
|
|
|
|
os.listxattr = orig_listxattr
|
2012-05-12 14:02:01 -03:00
|
|
|
|
2012-07-14 21:55:11 -03:00
|
|
|
# test that shutil.copystat copies xattrs
|
|
|
|
src = os.path.join(tmp_dir, 'the_original')
|
2019-05-10 00:22:06 -03:00
|
|
|
srcro = os.path.join(tmp_dir, 'the_original_ro')
|
2012-07-14 21:55:11 -03:00
|
|
|
write_file(src, src)
|
2019-05-10 00:22:06 -03:00
|
|
|
write_file(srcro, srcro)
|
2012-07-14 21:55:11 -03:00
|
|
|
os.setxattr(src, 'user.the_value', b'fiddly')
|
2019-05-10 00:22:06 -03:00
|
|
|
os.setxattr(srcro, 'user.the_value', b'fiddly')
|
|
|
|
os.chmod(srcro, 0o444)
|
2012-07-14 21:55:11 -03:00
|
|
|
dst = os.path.join(tmp_dir, 'the_copy')
|
2019-05-10 00:22:06 -03:00
|
|
|
dstro = os.path.join(tmp_dir, 'the_copy_ro')
|
2012-07-14 21:55:11 -03:00
|
|
|
write_file(dst, dst)
|
2019-05-10 00:22:06 -03:00
|
|
|
write_file(dstro, dstro)
|
2012-07-14 21:55:11 -03:00
|
|
|
shutil.copystat(src, dst)
|
2019-05-10 00:22:06 -03:00
|
|
|
shutil.copystat(srcro, dstro)
|
2012-07-16 12:11:10 -03:00
|
|
|
self.assertEqual(os.getxattr(dst, 'user.the_value'), b'fiddly')
|
2019-05-10 00:22:06 -03:00
|
|
|
self.assertEqual(os.getxattr(dstro, 'user.the_value'), b'fiddly')
|
2012-07-14 21:55:11 -03:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
|
|
|
@os_helper.skip_unless_xattr
|
2022-06-27 15:27:19 -03:00
|
|
|
@os_helper.skip_unless_dac_override
|
2012-05-12 14:02:01 -03:00
|
|
|
def test_copyxattr_symlinks(self):
|
|
|
|
# On Linux, it's only possible to access non-user xattr for symlinks;
|
|
|
|
# which in turn require root privileges. This test should be expanded
|
|
|
|
# as soon as other platforms gain support for extended attributes.
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
os.setxattr(src, 'trusted.foo', b'42')
|
2012-06-22 20:30:09 -03:00
|
|
|
os.setxattr(src_link, 'trusted.foo', b'43', follow_symlinks=False)
|
2012-05-12 14:02:01 -03:00
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
dst_link = os.path.join(tmp_dir, 'qux')
|
|
|
|
write_file(dst, 'bar')
|
|
|
|
os.symlink(dst, dst_link)
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil._copyxattr(src_link, dst_link, follow_symlinks=False)
|
2012-06-22 20:30:09 -03:00
|
|
|
self.assertEqual(os.getxattr(dst_link, 'trusted.foo', follow_symlinks=False), b'43')
|
2012-05-12 14:02:01 -03:00
|
|
|
self.assertRaises(OSError, os.getxattr, dst, 'trusted.foo')
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil._copyxattr(src_link, dst, follow_symlinks=False)
|
2012-05-12 14:02:01 -03:00
|
|
|
self.assertEqual(os.getxattr(dst, 'trusted.foo'), b'43')
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
### shutil.copy
|
|
|
|
|
|
|
|
def _copy_file(self, method):
|
|
|
|
fname = 'test.txt'
|
|
|
|
tmpdir = self.mkdtemp()
|
|
|
|
write_file((tmpdir, fname), 'xxx')
|
|
|
|
file1 = os.path.join(tmpdir, fname)
|
|
|
|
tmpdir2 = self.mkdtemp()
|
|
|
|
method(file1, tmpdir2)
|
|
|
|
file2 = os.path.join(tmpdir2, fname)
|
|
|
|
return (file1, file2)
|
|
|
|
|
|
|
|
def test_copy(self):
|
|
|
|
# Ensure that the copied file exists and has the same mode bits.
|
|
|
|
file1, file2 = self._copy_file(shutil.copy)
|
|
|
|
self.assertTrue(os.path.exists(file2))
|
|
|
|
self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2011-12-29 13:54:15 -04:00
|
|
|
def test_copy_symlinks(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
|
|
|
|
# don't follow
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil.copy(src_link, dst, follow_symlinks=True)
|
2011-12-29 13:54:15 -04:00
|
|
|
self.assertFalse(os.path.islink(dst))
|
|
|
|
self.assertEqual(read_file(src), read_file(dst))
|
|
|
|
os.remove(dst)
|
|
|
|
# follow
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil.copy(src_link, dst, follow_symlinks=False)
|
2011-12-29 13:54:15 -04:00
|
|
|
self.assertTrue(os.path.islink(dst))
|
|
|
|
self.assertEqual(os.readlink(dst), os.readlink(src_link))
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
self.assertEqual(os.lstat(src_link).st_mode,
|
|
|
|
os.lstat(dst).st_mode)
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
### shutil.copy2
|
|
|
|
|
|
|
|
@unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
|
|
|
|
def test_copy2(self):
|
|
|
|
# Ensure that the copied file exists and has the same mode and
|
|
|
|
# modification time bits.
|
|
|
|
file1, file2 = self._copy_file(shutil.copy2)
|
|
|
|
self.assertTrue(os.path.exists(file2))
|
|
|
|
file1_stat = os.stat(file1)
|
|
|
|
file2_stat = os.stat(file2)
|
|
|
|
self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
|
|
|
|
for attr in 'st_atime', 'st_mtime':
|
|
|
|
# The modification times may be truncated in the new file.
|
|
|
|
self.assertLessEqual(getattr(file1_stat, attr),
|
|
|
|
getattr(file2_stat, attr) + 1)
|
|
|
|
if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
|
|
|
|
self.assertEqual(getattr(file1_stat, 'st_flags'),
|
|
|
|
getattr(file2_stat, 'st_flags'))
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2011-12-29 13:54:15 -04:00
|
|
|
def test_copy2_symlinks(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
src_link = os.path.join(tmp_dir, 'baz')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
os.symlink(src, src_link)
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
|
|
|
|
if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
|
|
|
|
os.lchflags(src_link, stat.UF_NODUMP)
|
|
|
|
src_stat = os.stat(src)
|
|
|
|
src_link_stat = os.lstat(src_link)
|
|
|
|
# follow
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil.copy2(src_link, dst, follow_symlinks=True)
|
2011-12-29 13:54:15 -04:00
|
|
|
self.assertFalse(os.path.islink(dst))
|
|
|
|
self.assertEqual(read_file(src), read_file(dst))
|
|
|
|
os.remove(dst)
|
|
|
|
# don't follow
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil.copy2(src_link, dst, follow_symlinks=False)
|
2011-12-29 13:54:15 -04:00
|
|
|
self.assertTrue(os.path.islink(dst))
|
|
|
|
self.assertEqual(os.readlink(dst), os.readlink(src_link))
|
|
|
|
dst_stat = os.lstat(dst)
|
2012-06-22 20:30:09 -03:00
|
|
|
if os.utime in os.supports_follow_symlinks:
|
2011-12-29 13:54:15 -04:00
|
|
|
for attr in 'st_atime', 'st_mtime':
|
|
|
|
# The modification times may be truncated in the new file.
|
|
|
|
self.assertLessEqual(getattr(src_link_stat, attr),
|
|
|
|
getattr(dst_stat, attr) + 1)
|
|
|
|
if hasattr(os, 'lchmod'):
|
|
|
|
self.assertEqual(src_link_stat.st_mode, dst_stat.st_mode)
|
|
|
|
self.assertNotEqual(src_stat.st_mode, dst_stat.st_mode)
|
|
|
|
if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
|
|
|
|
self.assertEqual(src_link_stat.st_flags, dst_stat.st_flags)
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_xattr
|
2012-05-12 14:02:01 -03:00
|
|
|
def test_copy2_xattr(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'foo')
|
|
|
|
dst = os.path.join(tmp_dir, 'bar')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
os.setxattr(src, 'user.foo', b'42')
|
|
|
|
shutil.copy2(src, dst)
|
|
|
|
self.assertEqual(
|
|
|
|
os.getxattr(src, 'user.foo'),
|
|
|
|
os.getxattr(dst, 'user.foo'))
|
|
|
|
os.remove(dst)
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copy_return_value(self):
|
|
|
|
# copy and copy2 both return their destination path.
|
|
|
|
for fn in (shutil.copy, shutil.copy2):
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
dst_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(src_dir, 'foo')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
rv = fn(src, dst_dir)
|
|
|
|
self.assertEqual(rv, os.path.join(dst_dir, 'foo'))
|
|
|
|
rv = fn(src, os.path.join(dst_dir, 'bar'))
|
|
|
|
self.assertEqual(rv, os.path.join(dst_dir, 'bar'))
|
|
|
|
|
2021-09-21 18:53:07 -03:00
|
|
|
def test_copy_dir(self):
|
|
|
|
self._test_copy_dir(shutil.copy)
|
|
|
|
|
|
|
|
def test_copy2_dir(self):
|
|
|
|
self._test_copy_dir(shutil.copy2)
|
|
|
|
|
|
|
|
def _test_copy_dir(self, copy_func):
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
src_file = os.path.join(src_dir, 'foo')
|
|
|
|
dir2 = self.mkdtemp()
|
|
|
|
dst = os.path.join(src_dir, 'does_not_exist/')
|
|
|
|
write_file(src_file, 'foo')
|
|
|
|
if sys.platform == "win32":
|
|
|
|
err = PermissionError
|
|
|
|
else:
|
|
|
|
err = IsADirectoryError
|
|
|
|
self.assertRaises(err, copy_func, dir2, src_dir)
|
|
|
|
|
|
|
|
# raise *err* because of src rather than FileNotFoundError because of dst
|
|
|
|
self.assertRaises(err, copy_func, dir2, dst)
|
|
|
|
copy_func(src_file, dir2) # should not raise exceptions
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
### shutil.copyfile
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2011-12-29 13:54:15 -04:00
|
|
|
def test_copyfile_symlinks(self):
|
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
src = os.path.join(tmp_dir, 'src')
|
|
|
|
dst = os.path.join(tmp_dir, 'dst')
|
|
|
|
dst_link = os.path.join(tmp_dir, 'dst_link')
|
|
|
|
link = os.path.join(tmp_dir, 'link')
|
|
|
|
write_file(src, 'foo')
|
|
|
|
os.symlink(src, link)
|
|
|
|
# don't follow
|
2012-07-15 14:57:38 -03:00
|
|
|
shutil.copyfile(link, dst_link, follow_symlinks=False)
|
2011-12-29 13:54:15 -04:00
|
|
|
self.assertTrue(os.path.islink(dst_link))
|
2019-09-26 07:15:08 -03:00
|
|
|
self.assertEqual(os.readlink(link), os.readlink(dst_link))
|
|
|
|
# follow
|
|
|
|
shutil.copyfile(link, dst)
|
|
|
|
self.assertFalse(os.path.islink(dst))
|
2019-02-26 07:04:41 -04:00
|
|
|
|
2010-12-04 22:04:16 -04:00
|
|
|
@unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
|
2010-04-23 10:03:09 -03:00
|
|
|
def test_dont_copy_file_onto_link_to_itself(self):
|
|
|
|
# bug 851123.
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
src = os.path.join(TESTFN, 'cheese')
|
|
|
|
dst = os.path.join(TESTFN, 'shop')
|
|
|
|
try:
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(src, 'w', encoding='utf-8') as f:
|
2010-12-04 22:04:16 -04:00
|
|
|
f.write('cheddar')
|
2017-11-12 12:31:07 -04:00
|
|
|
try:
|
|
|
|
os.link(src, dst)
|
|
|
|
except PermissionError as e:
|
|
|
|
self.skipTest('os.link(): %s' % e)
|
2012-10-07 07:49:58 -03:00
|
|
|
self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(src, 'r', encoding='utf-8') as f:
|
2010-12-04 22:04:16 -04:00
|
|
|
self.assertEqual(f.read(), 'cheddar')
|
|
|
|
os.remove(dst)
|
|
|
|
finally:
|
|
|
|
shutil.rmtree(TESTFN, ignore_errors=True)
|
2010-04-23 10:03:09 -03:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2010-12-04 22:04:16 -04:00
|
|
|
def test_dont_copy_file_onto_symlink_to_itself(self):
|
|
|
|
# bug 851123.
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
src = os.path.join(TESTFN, 'cheese')
|
|
|
|
dst = os.path.join(TESTFN, 'shop')
|
|
|
|
try:
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(src, 'w', encoding='utf-8') as f:
|
2010-12-04 22:04:16 -04:00
|
|
|
f.write('cheddar')
|
2010-04-23 10:03:09 -03:00
|
|
|
# Using `src` here would mean we end up with a symlink pointing
|
|
|
|
# to TESTFN/TESTFN/cheese, while it should point at
|
|
|
|
# TESTFN/cheese.
|
|
|
|
os.symlink('cheese', dst)
|
2012-10-07 07:49:58 -03:00
|
|
|
self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(src, 'r', encoding='utf-8') as f:
|
2010-10-14 19:11:44 -03:00
|
|
|
self.assertEqual(f.read(), 'cheddar')
|
2010-04-23 10:03:09 -03:00
|
|
|
os.remove(dst)
|
|
|
|
finally:
|
2010-12-04 22:04:16 -04:00
|
|
|
shutil.rmtree(TESTFN, ignore_errors=True)
|
2004-06-19 18:11:35 -03:00
|
|
|
|
2013-11-03 15:31:38 -04:00
|
|
|
# Issue #3002: copyfile and copytree block indefinitely on named pipes
|
|
|
|
@unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
|
2020-11-28 18:06:36 -04:00
|
|
|
@unittest.skipIf(sys.platform == "vxworks",
|
|
|
|
"fifo requires special path on VxWorks")
|
2013-11-03 15:31:38 -04:00
|
|
|
def test_copyfile_named_pipe(self):
|
2017-11-12 12:31:07 -04:00
|
|
|
try:
|
|
|
|
os.mkfifo(TESTFN)
|
|
|
|
except PermissionError as e:
|
|
|
|
self.skipTest('os.mkfifo(): %s' % e)
|
2013-11-03 15:31:38 -04:00
|
|
|
try:
|
|
|
|
self.assertRaises(shutil.SpecialFileError,
|
|
|
|
shutil.copyfile, TESTFN, TESTFN2)
|
|
|
|
self.assertRaises(shutil.SpecialFileError,
|
|
|
|
shutil.copyfile, __file__, TESTFN)
|
|
|
|
finally:
|
|
|
|
os.remove(TESTFN)
|
2009-05-01 18:09:44 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copyfile_return_value(self):
|
|
|
|
# copytree returns its destination path.
|
2010-04-20 05:57:33 -03:00
|
|
|
src_dir = self.mkdtemp()
|
2019-09-26 07:15:08 -03:00
|
|
|
dst_dir = self.mkdtemp()
|
|
|
|
dst_file = os.path.join(dst_dir, 'bar')
|
|
|
|
src_file = os.path.join(src_dir, 'foo')
|
|
|
|
write_file(src_file, 'foo')
|
|
|
|
rv = shutil.copyfile(src_file, dst_file)
|
|
|
|
self.assertTrue(os.path.exists(rv))
|
|
|
|
self.assertEqual(read_file(src_file), read_file(dst_file))
|
2010-04-20 05:57:33 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_copyfile_same_file(self):
|
|
|
|
# copyfile() should raise SameFileError if the source and destination
|
|
|
|
# are the same.
|
2015-07-25 08:53:48 -03:00
|
|
|
src_dir = self.mkdtemp()
|
2019-09-26 07:15:08 -03:00
|
|
|
src_file = os.path.join(src_dir, 'foo')
|
|
|
|
write_file(src_file, 'foo')
|
|
|
|
self.assertRaises(SameFileError, shutil.copyfile, src_file, src_file)
|
|
|
|
# But Error should work too, to stay backward compatible.
|
|
|
|
self.assertRaises(Error, shutil.copyfile, src_file, src_file)
|
|
|
|
# Make sure file is not corrupted.
|
|
|
|
self.assertEqual(read_file(src_file), 'foo')
|
2015-07-25 08:53:48 -03:00
|
|
|
|
2021-07-20 15:16:23 -03:00
|
|
|
@unittest.skipIf(MACOS or SOLARIS or _winapi, 'On MACOS, Solaris and Windows the errors are not confusing (though different)')
|
2022-05-19 06:17:44 -03:00
|
|
|
# gh-92670: The test uses a trailing slash to force the OS consider
|
|
|
|
# the path as a directory, but on AIX the trailing slash has no effect
|
|
|
|
# and is considered as a file.
|
|
|
|
@unittest.skipIf(AIX, 'Not valid on AIX, see gh-92670')
|
2021-07-10 00:47:41 -03:00
|
|
|
def test_copyfile_nonexistent_dir(self):
|
|
|
|
# Issue 43219
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
src_file = os.path.join(src_dir, 'foo')
|
|
|
|
dst = os.path.join(src_dir, 'does_not_exist/')
|
|
|
|
write_file(src_file, 'foo')
|
|
|
|
self.assertRaises(FileNotFoundError, shutil.copyfile, src_file, dst)
|
|
|
|
|
2021-09-21 18:53:07 -03:00
|
|
|
def test_copyfile_copy_dir(self):
|
|
|
|
# Issue 45234
|
|
|
|
# test copy() and copyfile() raising proper exceptions when src and/or
|
|
|
|
# dst are directories
|
|
|
|
src_dir = self.mkdtemp()
|
|
|
|
src_file = os.path.join(src_dir, 'foo')
|
|
|
|
dir2 = self.mkdtemp()
|
|
|
|
dst = os.path.join(src_dir, 'does_not_exist/')
|
|
|
|
write_file(src_file, 'foo')
|
|
|
|
if sys.platform == "win32":
|
|
|
|
err = PermissionError
|
|
|
|
else:
|
|
|
|
err = IsADirectoryError
|
|
|
|
|
|
|
|
self.assertRaises(err, shutil.copyfile, src_dir, dst)
|
|
|
|
self.assertRaises(err, shutil.copyfile, src_file, src_dir)
|
|
|
|
self.assertRaises(err, shutil.copyfile, dir2, src_dir)
|
|
|
|
|
2011-03-16 15:05:35 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
class TestArchives(BaseTest, unittest.TestCase):
|
2011-03-16 15:05:35 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
### shutil.make_archive
|
2011-03-16 15:05:35 -03:00
|
|
|
|
2010-02-23 01:30:31 -04:00
|
|
|
def _tarinfo(self, path):
|
2015-09-06 12:33:19 -03:00
|
|
|
with tarfile.open(path) as tar:
|
2010-02-23 01:30:31 -04:00
|
|
|
names = tar.getnames()
|
|
|
|
names.sort()
|
|
|
|
return tuple(names)
|
|
|
|
|
2015-09-06 12:33:19 -03:00
|
|
|
def _create_files(self, base_dir='dist'):
|
2010-02-23 01:30:31 -04:00
|
|
|
# creating something to tar
|
2015-09-06 12:33:19 -03:00
|
|
|
root_dir = self.mkdtemp()
|
|
|
|
dist = os.path.join(root_dir, base_dir)
|
|
|
|
os.makedirs(dist, exist_ok=True)
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
write_file((dist, 'file1'), 'xxx')
|
|
|
|
write_file((dist, 'file2'), 'xxx')
|
2010-02-23 01:30:31 -04:00
|
|
|
os.mkdir(os.path.join(dist, 'sub'))
|
Clean up test_shutil, to facilitate upcoming improvements (#12721).
The tests now have two convenience functions to wrap os.path.join, open
and read or write instead of four or six slightly different functions.
The new functions accept a tuple of path segments but not a list
anymore, as it makes no sense to use a list here; I have also removed
the default value for the contents in write_file, as I find it better to
have the contents at the call site.
For simple open then read/write calls, I have left the usual idiom (with
open + read/write), as it is short and readable enough.
I’ve also changed some convoluted cleanup code to just use rmtree, and
removed dubious LBYL os.path.exists checks. The tests still pass on my
machine, and leave no file in $TMP. test_shutil is not as clean as it
could be, but I’ll stop here.
Initial patch provided by Hynek Schlawack, in preparation for a new
feature with new tests in #12715.
2011-08-12 14:51:35 -03:00
|
|
|
write_file((dist, 'sub', 'file3'), 'xxx')
|
2010-02-23 01:30:31 -04:00
|
|
|
os.mkdir(os.path.join(dist, 'sub2'))
|
2015-09-06 12:33:19 -03:00
|
|
|
if base_dir:
|
|
|
|
write_file((root_dir, 'outer'), 'xxx')
|
|
|
|
return root_dir, base_dir
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2024-04-22 10:27:47 -03:00
|
|
|
@support.requires_zlib()
|
|
|
|
def test_make_tarfile(self):
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
# Test without base_dir.
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst', 'archive')
|
|
|
|
archive = make_archive(base_name, 'tar', root_dir)
|
|
|
|
# check if the compressed tarball was created
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(tarfile.is_tarfile(archive))
|
|
|
|
with tarfile.open(archive, 'r') as tf:
|
|
|
|
self.assertCountEqual(tf.getnames(),
|
|
|
|
['.', './dist', './dist/sub', './dist/sub2',
|
|
|
|
'./dist/file1', './dist/file2', './dist/sub/file3',
|
|
|
|
'./outer'])
|
|
|
|
|
|
|
|
# Test with base_dir.
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst2', 'archive')
|
|
|
|
archive = make_archive(base_name, 'tar', root_dir, base_dir)
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
|
|
|
|
# check if the uncompressed tarball was created
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(tarfile.is_tarfile(archive))
|
|
|
|
with tarfile.open(archive, 'r') as tf:
|
|
|
|
self.assertCountEqual(tf.getnames(),
|
|
|
|
['dist', 'dist/sub', 'dist/sub2',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3'])
|
|
|
|
|
|
|
|
# Test with multi-component base_dir.
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst3', 'archive')
|
|
|
|
archive = make_archive(base_name, 'tar', root_dir,
|
|
|
|
os.path.join(base_dir, 'sub'))
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(tarfile.is_tarfile(archive))
|
|
|
|
with tarfile.open(archive, 'r') as tf:
|
|
|
|
self.assertCountEqual(tf.getnames(),
|
|
|
|
['dist/sub', 'dist/sub/file3'])
|
|
|
|
|
|
|
|
@support.requires_zlib()
|
|
|
|
def test_make_tarfile_without_rootdir(self):
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
# Test without base_dir.
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'dst', 'archive')
|
|
|
|
base_name = os.path.relpath(base_name, root_dir)
|
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
|
|
|
archive = make_archive(base_name, 'gztar')
|
|
|
|
self.assertEqual(archive, base_name + '.tar.gz')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(tarfile.is_tarfile(archive))
|
|
|
|
with tarfile.open(archive, 'r:gz') as tf:
|
|
|
|
self.assertCountEqual(tf.getnames(),
|
|
|
|
['.', './dist', './dist/sub', './dist/sub2',
|
|
|
|
'./dist/file1', './dist/file2', './dist/sub/file3',
|
|
|
|
'./outer'])
|
|
|
|
|
|
|
|
# Test with base_dir.
|
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
|
|
|
base_name = os.path.join('dst', 'archive')
|
|
|
|
archive = make_archive(base_name, 'tar', base_dir=base_dir)
|
|
|
|
self.assertEqual(archive, base_name + '.tar')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(tarfile.is_tarfile(archive))
|
|
|
|
with tarfile.open(archive, 'r') as tf:
|
|
|
|
self.assertCountEqual(tf.getnames(),
|
|
|
|
['dist', 'dist/sub', 'dist/sub2',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3'])
|
|
|
|
|
|
|
|
def test_make_tarfile_with_explicit_curdir(self):
|
|
|
|
# Test with base_dir=os.curdir.
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst', 'archive')
|
|
|
|
archive = make_archive(base_name, 'tar', root_dir, os.curdir)
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.tar')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(tarfile.is_tarfile(archive))
|
|
|
|
with tarfile.open(archive, 'r') as tf:
|
|
|
|
self.assertCountEqual(tf.getnames(),
|
|
|
|
['.', './dist', './dist/sub', './dist/sub2',
|
|
|
|
'./dist/file1', './dist/file2', './dist/sub/file3',
|
|
|
|
'./outer'])
|
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2015-11-21 08:09:26 -04:00
|
|
|
@unittest.skipUnless(shutil.which('tar'),
|
2010-02-23 01:30:31 -04:00
|
|
|
'Need the tar command to run')
|
|
|
|
def test_tarfile_vs_tar(self):
|
2015-09-06 12:33:19 -03:00
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'archive')
|
2022-06-22 05:47:25 -03:00
|
|
|
with no_chdir:
|
|
|
|
tarball = make_archive(base_name, 'gztar', root_dir, base_dir)
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
# check if the compressed tarball was created
|
2015-09-07 07:55:25 -03:00
|
|
|
self.assertEqual(tarball, base_name + '.tar.gz')
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(tarball))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
# now create another tarball using `tar`
|
2015-09-06 12:33:19 -03:00
|
|
|
tarball2 = os.path.join(root_dir, 'archive2.tar')
|
|
|
|
tar_cmd = ['tar', '-cf', 'archive2.tar', base_dir]
|
2023-12-10 07:38:49 -04:00
|
|
|
if sys.platform == 'darwin':
|
|
|
|
# macOS tar can include extended attributes,
|
|
|
|
# ACLs and other mac specific metadata into the
|
|
|
|
# archive (an recentish version of the OS).
|
|
|
|
#
|
|
|
|
# This feature can be disabled with the
|
|
|
|
# '--no-mac-metadata' option on macOS 11 or
|
|
|
|
# later.
|
|
|
|
import platform
|
|
|
|
if int(platform.mac_ver()[0].split('.')[0]) >= 11:
|
|
|
|
tar_cmd.insert(1, '--no-mac-metadata')
|
2015-11-21 08:09:26 -04:00
|
|
|
subprocess.check_call(tar_cmd, cwd=root_dir,
|
|
|
|
stdout=subprocess.DEVNULL)
|
2015-09-06 12:33:19 -03:00
|
|
|
|
|
|
|
self.assertTrue(os.path.isfile(tarball2))
|
2010-02-23 01:30:31 -04:00
|
|
|
# let's compare both tarballs
|
2010-11-20 15:04:17 -04:00
|
|
|
self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
# trying an uncompressed one
|
2022-06-22 05:47:25 -03:00
|
|
|
with no_chdir:
|
|
|
|
tarball = make_archive(base_name, 'tar', root_dir, base_dir)
|
2015-09-07 07:55:25 -03:00
|
|
|
self.assertEqual(tarball, base_name + '.tar')
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(tarball))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
# now for a dry_run
|
2022-06-22 05:47:25 -03:00
|
|
|
with no_chdir:
|
|
|
|
tarball = make_archive(base_name, 'tar', root_dir, base_dir,
|
|
|
|
dry_run=True)
|
2015-09-07 07:55:25 -03:00
|
|
|
self.assertEqual(tarball, base_name + '.tar')
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(tarball))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2010-02-23 01:30:31 -04:00
|
|
|
def test_make_zipfile(self):
|
2015-09-06 12:33:19 -03:00
|
|
|
root_dir, base_dir = self._create_files()
|
2024-04-22 10:27:47 -03:00
|
|
|
# Test without base_dir.
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst', 'archive')
|
|
|
|
archive = make_archive(base_name, 'zip', root_dir)
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(zipfile.is_zipfile(archive))
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
self.assertCountEqual(zf.namelist(),
|
|
|
|
['dist/', 'dist/sub/', 'dist/sub2/',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3',
|
|
|
|
'outer'])
|
|
|
|
|
|
|
|
# Test with base_dir.
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst2', 'archive')
|
|
|
|
archive = make_archive(base_name, 'zip', root_dir, base_dir)
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(zipfile.is_zipfile(archive))
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
self.assertCountEqual(zf.namelist(),
|
|
|
|
['dist/', 'dist/sub/', 'dist/sub2/',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3'])
|
|
|
|
|
|
|
|
# Test with multi-component base_dir.
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst3', 'archive')
|
|
|
|
archive = make_archive(base_name, 'zip', root_dir,
|
|
|
|
os.path.join(base_dir, 'sub'))
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(zipfile.is_zipfile(archive))
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
self.assertCountEqual(zf.namelist(),
|
|
|
|
['dist/sub/', 'dist/sub/file3'])
|
2015-09-07 13:58:23 -03:00
|
|
|
|
2024-04-22 10:27:47 -03:00
|
|
|
@support.requires_zlib()
|
|
|
|
def test_make_zipfile_without_rootdir(self):
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
# Test without base_dir.
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'dst', 'archive')
|
|
|
|
base_name = os.path.relpath(base_name, root_dir)
|
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
|
|
|
archive = make_archive(base_name, 'zip')
|
|
|
|
self.assertEqual(archive, base_name + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(zipfile.is_zipfile(archive))
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
self.assertCountEqual(zf.namelist(),
|
|
|
|
['dist/', 'dist/sub/', 'dist/sub2/',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3',
|
|
|
|
'outer'])
|
|
|
|
|
|
|
|
# Test with base_dir.
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
|
|
|
base_name = os.path.join('dst', 'archive')
|
|
|
|
archive = make_archive(base_name, 'zip', base_dir=base_dir)
|
|
|
|
self.assertEqual(archive, base_name + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(zipfile.is_zipfile(archive))
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
self.assertCountEqual(zf.namelist(),
|
|
|
|
['dist/', 'dist/sub/', 'dist/sub2/',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3'])
|
2016-10-23 09:55:09 -03:00
|
|
|
|
2024-04-22 10:27:47 -03:00
|
|
|
@support.requires_zlib()
|
|
|
|
def test_make_zipfile_with_explicit_curdir(self):
|
|
|
|
# Test with base_dir=os.curdir.
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
with os_helper.temp_cwd(), no_chdir:
|
|
|
|
base_name = os.path.join('dst', 'archive')
|
|
|
|
archive = make_archive(base_name, 'zip', root_dir, os.curdir)
|
|
|
|
self.assertEqual(archive, os.path.abspath(base_name) + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
self.assertTrue(zipfile.is_zipfile(archive))
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
self.assertCountEqual(zf.namelist(),
|
|
|
|
['dist/', 'dist/sub/', 'dist/sub2/',
|
|
|
|
'dist/file1', 'dist/file2', 'dist/sub/file3',
|
|
|
|
'outer'])
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2015-11-21 08:09:26 -04:00
|
|
|
@unittest.skipUnless(shutil.which('zip'),
|
2015-09-07 23:47:23 -03:00
|
|
|
'Need the zip command to run')
|
|
|
|
def test_zipfile_vs_zip(self):
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'archive')
|
2022-06-22 05:47:25 -03:00
|
|
|
with no_chdir:
|
|
|
|
archive = make_archive(base_name, 'zip', root_dir, base_dir)
|
2015-09-07 23:47:23 -03:00
|
|
|
|
|
|
|
# check if ZIP file was created
|
|
|
|
self.assertEqual(archive, base_name + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
|
|
|
|
# now create another ZIP file using `zip`
|
|
|
|
archive2 = os.path.join(root_dir, 'archive2.zip')
|
|
|
|
zip_cmd = ['zip', '-q', '-r', 'archive2.zip', base_dir]
|
2015-11-21 08:09:26 -04:00
|
|
|
subprocess.check_call(zip_cmd, cwd=root_dir,
|
|
|
|
stdout=subprocess.DEVNULL)
|
2015-09-07 23:47:23 -03:00
|
|
|
|
|
|
|
self.assertTrue(os.path.isfile(archive2))
|
|
|
|
# let's compare both ZIP files
|
|
|
|
with zipfile.ZipFile(archive) as zf:
|
|
|
|
names = zf.namelist()
|
|
|
|
with zipfile.ZipFile(archive2) as zf:
|
|
|
|
names2 = zf.namelist()
|
|
|
|
self.assertEqual(sorted(names), sorted(names2))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2015-11-22 08:49:58 -04:00
|
|
|
@unittest.skipUnless(shutil.which('unzip'),
|
|
|
|
'Need the unzip command to run')
|
|
|
|
def test_unzip_zipfile(self):
|
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'archive')
|
2022-06-22 05:47:25 -03:00
|
|
|
with no_chdir:
|
|
|
|
archive = make_archive(base_name, 'zip', root_dir, base_dir)
|
2015-11-22 08:49:58 -04:00
|
|
|
|
|
|
|
# check if ZIP file was created
|
|
|
|
self.assertEqual(archive, base_name + '.zip')
|
|
|
|
self.assertTrue(os.path.isfile(archive))
|
|
|
|
|
|
|
|
# now check the ZIP file using `unzip -t`
|
|
|
|
zip_cmd = ['unzip', '-t', archive]
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(root_dir):
|
2015-11-22 08:49:58 -04:00
|
|
|
try:
|
|
|
|
subprocess.check_output(zip_cmd, stderr=subprocess.STDOUT)
|
|
|
|
except subprocess.CalledProcessError as exc:
|
|
|
|
details = exc.output.decode(errors="replace")
|
2024-09-25 11:02:18 -03:00
|
|
|
if any(message in details for message in [
|
|
|
|
'unrecognized option: t', # BusyBox
|
|
|
|
'invalid option -- t', # Android
|
|
|
|
]):
|
2018-09-13 14:57:23 -03:00
|
|
|
self.skipTest("unzip doesn't support -t")
|
2015-11-22 08:49:58 -04:00
|
|
|
msg = "{}\n\n**Unzip Output**\n{}"
|
|
|
|
self.fail(msg.format(exc, details))
|
|
|
|
|
2010-02-23 01:30:31 -04:00
|
|
|
def test_make_archive(self):
|
|
|
|
tmpdir = self.mkdtemp()
|
|
|
|
base_name = os.path.join(tmpdir, 'archive')
|
|
|
|
self.assertRaises(ValueError, make_archive, base_name, 'xxx')
|
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2010-02-23 01:30:31 -04:00
|
|
|
def test_make_archive_owner_group(self):
|
|
|
|
# testing make_archive with owner and group, with various combinations
|
|
|
|
# this works even if there's not gid/uid support
|
|
|
|
if UID_GID_SUPPORT:
|
|
|
|
group = grp.getgrgid(0)[0]
|
|
|
|
owner = pwd.getpwuid(0)[0]
|
|
|
|
else:
|
|
|
|
group = owner = 'root'
|
|
|
|
|
2015-09-06 12:33:19 -03:00
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'archive')
|
2010-02-23 01:30:31 -04:00
|
|
|
res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
|
|
|
|
group=group)
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(res))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
res = make_archive(base_name, 'zip', root_dir, base_dir)
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(res))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
res = make_archive(base_name, 'tar', root_dir, base_dir,
|
|
|
|
owner=owner, group=group)
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(res))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
res = make_archive(base_name, 'tar', root_dir, base_dir,
|
|
|
|
owner='kjhkjhkjg', group='oihohoh')
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(res))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2010-04-28 14:51:36 -03:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2010-02-23 01:30:31 -04:00
|
|
|
@unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
|
|
|
|
def test_tarfile_root_owner(self):
|
2015-09-06 12:33:19 -03:00
|
|
|
root_dir, base_dir = self._create_files()
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'archive')
|
2010-02-23 01:30:31 -04:00
|
|
|
group = grp.getgrgid(0)[0]
|
|
|
|
owner = pwd.getpwuid(0)[0]
|
2022-06-22 05:47:25 -03:00
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
2015-09-06 12:33:19 -03:00
|
|
|
archive_name = make_archive(base_name, 'gztar', root_dir, 'dist',
|
|
|
|
owner=owner, group=group)
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
# check if the compressed tarball was created
|
2015-09-06 12:33:19 -03:00
|
|
|
self.assertTrue(os.path.isfile(archive_name))
|
2010-02-23 01:30:31 -04:00
|
|
|
|
|
|
|
# now checks the rights
|
|
|
|
archive = tarfile.open(archive_name)
|
|
|
|
try:
|
|
|
|
for member in archive.getmembers():
|
2010-11-20 15:04:17 -04:00
|
|
|
self.assertEqual(member.uid, 0)
|
|
|
|
self.assertEqual(member.gid, 0)
|
2010-02-23 01:30:31 -04:00
|
|
|
finally:
|
|
|
|
archive.close()
|
|
|
|
|
2022-10-05 06:48:59 -03:00
|
|
|
def test_make_archive_cwd_default(self):
|
|
|
|
current_dir = os.getcwd()
|
|
|
|
def archiver(base_name, base_dir, **kw):
|
|
|
|
self.assertNotIn('root_dir', kw)
|
|
|
|
self.assertEqual(base_name, 'basename')
|
|
|
|
self.assertEqual(os.getcwd(), current_dir)
|
|
|
|
raise RuntimeError()
|
|
|
|
|
|
|
|
register_archive_format('xxx', archiver, [], 'xxx file')
|
|
|
|
try:
|
|
|
|
with no_chdir:
|
|
|
|
with self.assertRaises(RuntimeError):
|
|
|
|
make_archive('basename', 'xxx')
|
|
|
|
self.assertEqual(os.getcwd(), current_dir)
|
|
|
|
finally:
|
|
|
|
unregister_archive_format('xxx')
|
|
|
|
|
2010-02-23 01:30:31 -04:00
|
|
|
def test_make_archive_cwd(self):
|
|
|
|
current_dir = os.getcwd()
|
2022-06-22 05:47:25 -03:00
|
|
|
root_dir = self.mkdtemp()
|
2022-10-05 06:48:59 -03:00
|
|
|
def archiver(base_name, base_dir, **kw):
|
|
|
|
self.assertNotIn('root_dir', kw)
|
|
|
|
self.assertEqual(base_name, os.path.join(current_dir, 'basename'))
|
|
|
|
self.assertEqual(os.getcwd(), root_dir)
|
2010-02-23 01:30:31 -04:00
|
|
|
raise RuntimeError()
|
2022-06-22 05:47:25 -03:00
|
|
|
dirs = []
|
|
|
|
def _chdir(path):
|
|
|
|
dirs.append(path)
|
|
|
|
orig_chdir(path)
|
2010-02-23 01:30:31 -04:00
|
|
|
|
2022-10-05 06:48:59 -03:00
|
|
|
register_archive_format('xxx', archiver, [], 'xxx file')
|
2010-02-23 01:30:31 -04:00
|
|
|
try:
|
2022-06-22 05:47:25 -03:00
|
|
|
with support.swap_attr(os, 'chdir', _chdir) as orig_chdir:
|
2022-10-05 06:48:59 -03:00
|
|
|
with self.assertRaises(RuntimeError):
|
|
|
|
make_archive('basename', 'xxx', root_dir=root_dir)
|
2010-11-20 15:04:17 -04:00
|
|
|
self.assertEqual(os.getcwd(), current_dir)
|
2022-06-22 05:47:25 -03:00
|
|
|
self.assertEqual(dirs, [root_dir, current_dir])
|
2010-02-23 01:30:31 -04:00
|
|
|
finally:
|
|
|
|
unregister_archive_format('xxx')
|
|
|
|
|
2022-10-05 06:48:59 -03:00
|
|
|
def test_make_archive_cwd_supports_root_dir(self):
|
|
|
|
current_dir = os.getcwd()
|
|
|
|
root_dir = self.mkdtemp()
|
|
|
|
def archiver(base_name, base_dir, **kw):
|
|
|
|
self.assertEqual(base_name, 'basename')
|
|
|
|
self.assertEqual(kw['root_dir'], root_dir)
|
|
|
|
self.assertEqual(os.getcwd(), current_dir)
|
|
|
|
raise RuntimeError()
|
|
|
|
archiver.supports_root_dir = True
|
|
|
|
|
|
|
|
register_archive_format('xxx', archiver, [], 'xxx file')
|
|
|
|
try:
|
|
|
|
with no_chdir:
|
|
|
|
with self.assertRaises(RuntimeError):
|
|
|
|
make_archive('basename', 'xxx', root_dir=root_dir)
|
|
|
|
self.assertEqual(os.getcwd(), current_dir)
|
|
|
|
finally:
|
|
|
|
unregister_archive_format('xxx')
|
|
|
|
|
2014-11-27 18:48:46 -04:00
|
|
|
def test_make_tarfile_in_curdir(self):
|
2024-04-22 10:27:47 -03:00
|
|
|
# Issue #21280: Test with the archive in the current directory.
|
2014-11-27 18:48:46 -04:00
|
|
|
root_dir = self.mkdtemp()
|
2022-06-22 05:47:25 -03:00
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
2024-04-22 10:27:47 -03:00
|
|
|
# root_dir must be None, so the archive path is relative.
|
2014-11-27 18:48:46 -04:00
|
|
|
self.assertEqual(make_archive('test', 'tar'), 'test.tar')
|
|
|
|
self.assertTrue(os.path.isfile('test.tar'))
|
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2014-11-27 18:48:46 -04:00
|
|
|
def test_make_zipfile_in_curdir(self):
|
2024-04-22 10:27:47 -03:00
|
|
|
# Issue #21280: Test with the archive in the current directory.
|
2014-11-27 18:48:46 -04:00
|
|
|
root_dir = self.mkdtemp()
|
2022-06-22 05:47:25 -03:00
|
|
|
with os_helper.change_cwd(root_dir), no_chdir:
|
2024-04-22 10:27:47 -03:00
|
|
|
# root_dir must be None, so the archive path is relative.
|
2014-11-27 18:48:46 -04:00
|
|
|
self.assertEqual(make_archive('test', 'zip'), 'test.zip')
|
|
|
|
self.assertTrue(os.path.isfile('test.zip'))
|
|
|
|
|
2010-02-23 01:30:31 -04:00
|
|
|
def test_register_archive_format(self):
|
|
|
|
|
|
|
|
self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
|
|
|
|
self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
|
|
|
|
1)
|
|
|
|
self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
|
|
|
|
[(1, 2), (1, 2, 3)])
|
|
|
|
|
|
|
|
register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
|
|
|
|
formats = [name for name, params in get_archive_formats()]
|
|
|
|
self.assertIn('xxx', formats)
|
|
|
|
|
|
|
|
unregister_archive_format('xxx')
|
|
|
|
formats = [name for name, params in get_archive_formats()]
|
|
|
|
self.assertNotIn('xxx', formats)
|
|
|
|
|
2023-08-16 04:00:03 -03:00
|
|
|
def test_make_tarfile_rootdir_nodir(self):
|
2024-04-22 10:27:47 -03:00
|
|
|
# GH-99203: Test with root_dir is not a real directory.
|
2023-08-16 04:00:03 -03:00
|
|
|
self.addCleanup(os_helper.unlink, f'{TESTFN}.tar')
|
|
|
|
for dry_run in (False, True):
|
|
|
|
with self.subTest(dry_run=dry_run):
|
2024-04-22 10:27:47 -03:00
|
|
|
# root_dir does not exist.
|
2023-08-16 04:00:03 -03:00
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
nonexisting_file = os.path.join(tmp_dir, 'nonexisting')
|
|
|
|
with self.assertRaises(FileNotFoundError) as cm:
|
|
|
|
make_archive(TESTFN, 'tar', nonexisting_file, dry_run=dry_run)
|
|
|
|
self.assertEqual(cm.exception.errno, errno.ENOENT)
|
|
|
|
self.assertEqual(cm.exception.filename, nonexisting_file)
|
|
|
|
self.assertFalse(os.path.exists(f'{TESTFN}.tar'))
|
|
|
|
|
2024-04-22 10:27:47 -03:00
|
|
|
# root_dir is a file.
|
2023-08-16 04:00:03 -03:00
|
|
|
tmp_fd, tmp_file = tempfile.mkstemp(dir=tmp_dir)
|
|
|
|
os.close(tmp_fd)
|
|
|
|
with self.assertRaises(NotADirectoryError) as cm:
|
|
|
|
make_archive(TESTFN, 'tar', tmp_file, dry_run=dry_run)
|
|
|
|
self.assertEqual(cm.exception.errno, errno.ENOTDIR)
|
|
|
|
self.assertEqual(cm.exception.filename, tmp_file)
|
|
|
|
self.assertFalse(os.path.exists(f'{TESTFN}.tar'))
|
|
|
|
|
|
|
|
@support.requires_zlib()
|
|
|
|
def test_make_zipfile_rootdir_nodir(self):
|
2024-04-22 10:27:47 -03:00
|
|
|
# GH-99203: Test with root_dir is not a real directory.
|
2023-08-16 04:00:03 -03:00
|
|
|
self.addCleanup(os_helper.unlink, f'{TESTFN}.zip')
|
|
|
|
for dry_run in (False, True):
|
|
|
|
with self.subTest(dry_run=dry_run):
|
2024-04-22 10:27:47 -03:00
|
|
|
# root_dir does not exist.
|
2023-08-16 04:00:03 -03:00
|
|
|
tmp_dir = self.mkdtemp()
|
|
|
|
nonexisting_file = os.path.join(tmp_dir, 'nonexisting')
|
|
|
|
with self.assertRaises(FileNotFoundError) as cm:
|
|
|
|
make_archive(TESTFN, 'zip', nonexisting_file, dry_run=dry_run)
|
|
|
|
self.assertEqual(cm.exception.errno, errno.ENOENT)
|
|
|
|
self.assertEqual(cm.exception.filename, nonexisting_file)
|
|
|
|
self.assertFalse(os.path.exists(f'{TESTFN}.zip'))
|
|
|
|
|
2024-04-22 10:27:47 -03:00
|
|
|
# root_dir is a file.
|
2023-08-16 04:00:03 -03:00
|
|
|
tmp_fd, tmp_file = tempfile.mkstemp(dir=tmp_dir)
|
|
|
|
os.close(tmp_fd)
|
|
|
|
with self.assertRaises(NotADirectoryError) as cm:
|
|
|
|
make_archive(TESTFN, 'zip', tmp_file, dry_run=dry_run)
|
|
|
|
self.assertEqual(cm.exception.errno, errno.ENOTDIR)
|
|
|
|
self.assertEqual(cm.exception.filename, tmp_file)
|
|
|
|
self.assertFalse(os.path.exists(f'{TESTFN}.zip'))
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
### shutil.unpack_archive
|
|
|
|
|
2023-04-24 05:58:06 -03:00
|
|
|
def check_unpack_archive(self, format, **kwargs):
|
|
|
|
self.check_unpack_archive_with_converter(
|
|
|
|
format, lambda path: path, **kwargs)
|
|
|
|
self.check_unpack_archive_with_converter(
|
2024-05-16 04:25:10 -03:00
|
|
|
format, FakePath, **kwargs)
|
2023-04-24 05:58:06 -03:00
|
|
|
self.check_unpack_archive_with_converter(format, FakePath, **kwargs)
|
2017-05-05 18:27:12 -03:00
|
|
|
|
2023-04-24 05:58:06 -03:00
|
|
|
def check_unpack_archive_with_converter(self, format, converter, **kwargs):
|
2015-09-06 12:33:19 -03:00
|
|
|
root_dir, base_dir = self._create_files()
|
2015-09-07 23:47:23 -03:00
|
|
|
expected = rlistdir(root_dir)
|
|
|
|
expected.remove('outer')
|
2016-12-16 12:58:33 -04:00
|
|
|
|
|
|
|
base_name = os.path.join(self.mkdtemp(), 'archive')
|
|
|
|
filename = make_archive(base_name, format, root_dir, base_dir)
|
|
|
|
|
|
|
|
# let's try to unpack it now
|
|
|
|
tmpdir2 = self.mkdtemp()
|
2023-04-24 05:58:06 -03:00
|
|
|
unpack_archive(converter(filename), converter(tmpdir2), **kwargs)
|
2016-12-16 12:58:33 -04:00
|
|
|
self.assertEqual(rlistdir(tmpdir2), expected)
|
|
|
|
|
|
|
|
# and again, this time with the format specified
|
|
|
|
tmpdir3 = self.mkdtemp()
|
2023-04-24 05:58:06 -03:00
|
|
|
unpack_archive(converter(filename), converter(tmpdir3), format=format,
|
|
|
|
**kwargs)
|
2016-12-16 12:58:33 -04:00
|
|
|
self.assertEqual(rlistdir(tmpdir3), expected)
|
|
|
|
|
2023-04-24 05:58:06 -03:00
|
|
|
with self.assertRaises(shutil.ReadError):
|
|
|
|
unpack_archive(converter(TESTFN), **kwargs)
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
unpack_archive(converter(TESTFN), format='xxx', **kwargs)
|
|
|
|
|
|
|
|
def check_unpack_tarball(self, format):
|
|
|
|
self.check_unpack_archive(format, filter='fully_trusted')
|
|
|
|
self.check_unpack_archive(format, filter='data')
|
2011-03-16 14:52:20 -03:00
|
|
|
|
2016-12-16 12:58:33 -04:00
|
|
|
def test_unpack_archive_tar(self):
|
2023-04-24 05:58:06 -03:00
|
|
|
self.check_unpack_tarball('tar')
|
2016-12-16 12:58:33 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2016-12-16 12:58:33 -04:00
|
|
|
def test_unpack_archive_gztar(self):
|
2023-04-24 05:58:06 -03:00
|
|
|
self.check_unpack_tarball('gztar')
|
2016-12-16 12:58:33 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_bz2()
|
2016-12-16 12:58:33 -04:00
|
|
|
def test_unpack_archive_bztar(self):
|
2023-04-24 05:58:06 -03:00
|
|
|
self.check_unpack_tarball('bztar')
|
2016-12-16 12:58:33 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_lzma()
|
2019-02-18 07:02:44 -04:00
|
|
|
@unittest.skipIf(AIX and not _maxdataOK(), "AIX MAXDATA must be 0x20000000 or larger")
|
2016-12-16 12:58:33 -04:00
|
|
|
def test_unpack_archive_xztar(self):
|
2023-04-24 05:58:06 -03:00
|
|
|
self.check_unpack_tarball('xztar')
|
2016-12-16 12:58:33 -04:00
|
|
|
|
2020-05-18 19:02:57 -03:00
|
|
|
@support.requires_zlib()
|
2016-12-16 12:58:33 -04:00
|
|
|
def test_unpack_archive_zip(self):
|
|
|
|
self.check_unpack_archive('zip')
|
2023-04-24 05:58:06 -03:00
|
|
|
with self.assertRaises(TypeError):
|
|
|
|
self.check_unpack_archive('zip', filter='data')
|
2016-12-16 12:58:33 -04:00
|
|
|
|
2016-07-27 22:11:04 -03:00
|
|
|
def test_unpack_registry(self):
|
2010-04-28 14:51:36 -03:00
|
|
|
|
|
|
|
formats = get_unpack_formats()
|
|
|
|
|
|
|
|
def _boo(filename, extract_dir, extra):
|
2010-11-20 15:04:17 -04:00
|
|
|
self.assertEqual(extra, 1)
|
|
|
|
self.assertEqual(filename, 'stuff.boo')
|
|
|
|
self.assertEqual(extract_dir, 'xx')
|
2010-04-28 14:51:36 -03:00
|
|
|
|
|
|
|
register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
|
|
|
|
unpack_archive('stuff.boo', 'xx')
|
|
|
|
|
|
|
|
# trying to register a .boo unpacker again
|
|
|
|
self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
|
|
|
|
['.boo'], _boo)
|
|
|
|
|
|
|
|
# should work now
|
|
|
|
unregister_unpack_format('Boo')
|
|
|
|
register_unpack_format('Boo2', ['.boo'], _boo)
|
|
|
|
self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
|
|
|
|
self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
|
|
|
|
|
|
|
|
# let's leave a clean state
|
|
|
|
unregister_unpack_format('Boo2')
|
2010-11-20 15:04:17 -04:00
|
|
|
self.assertEqual(get_unpack_formats(), formats)
|
2010-04-28 14:51:36 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
|
|
|
|
class TestMisc(BaseTest, unittest.TestCase):
|
|
|
|
|
2011-07-01 08:55:36 -03:00
|
|
|
@unittest.skipUnless(hasattr(shutil, 'disk_usage'),
|
|
|
|
"disk_usage not available on this platform")
|
|
|
|
def test_disk_usage(self):
|
2017-07-06 21:11:27 -03:00
|
|
|
usage = shutil.disk_usage(os.path.dirname(__file__))
|
2018-12-11 07:05:21 -04:00
|
|
|
for attr in ('total', 'used', 'free'):
|
|
|
|
self.assertIsInstance(getattr(usage, attr), int)
|
2011-07-02 11:45:45 -03:00
|
|
|
self.assertGreater(usage.total, 0)
|
|
|
|
self.assertGreater(usage.used, 0)
|
|
|
|
self.assertGreaterEqual(usage.free, 0)
|
|
|
|
self.assertGreaterEqual(usage.total, usage.used)
|
|
|
|
self.assertGreater(usage.total, usage.free)
|
2011-07-01 08:55:36 -03:00
|
|
|
|
2018-12-11 07:05:21 -04:00
|
|
|
# bpo-32557: Check that disk_usage() also accepts a filename
|
|
|
|
shutil.disk_usage(__file__)
|
|
|
|
|
2011-08-22 18:28:27 -03:00
|
|
|
@unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
|
|
|
|
@unittest.skipUnless(hasattr(os, 'chown'), 'requires os.chown')
|
|
|
|
def test_chown(self):
|
|
|
|
dirname = self.mkdtemp()
|
|
|
|
filename = tempfile.mktemp(dir=dirname)
|
2024-04-22 15:23:36 -03:00
|
|
|
linkname = os.path.join(dirname, "chown_link")
|
2011-08-22 18:28:27 -03:00
|
|
|
write_file(filename, 'testing chown function')
|
2024-04-22 15:23:36 -03:00
|
|
|
os.symlink(filename, linkname)
|
2011-08-22 18:28:27 -03:00
|
|
|
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
shutil.chown(filename)
|
|
|
|
|
|
|
|
with self.assertRaises(LookupError):
|
2016-08-30 14:47:49 -03:00
|
|
|
shutil.chown(filename, user='non-existing username')
|
2011-08-22 18:28:27 -03:00
|
|
|
|
|
|
|
with self.assertRaises(LookupError):
|
2016-08-30 14:47:49 -03:00
|
|
|
shutil.chown(filename, group='non-existing groupname')
|
2011-08-22 18:28:27 -03:00
|
|
|
|
|
|
|
with self.assertRaises(TypeError):
|
|
|
|
shutil.chown(filename, b'spam')
|
|
|
|
|
|
|
|
with self.assertRaises(TypeError):
|
|
|
|
shutil.chown(filename, 3.14)
|
|
|
|
|
|
|
|
uid = os.getuid()
|
|
|
|
gid = os.getgid()
|
|
|
|
|
|
|
|
def check_chown(path, uid=None, gid=None):
|
2024-04-22 15:23:36 -03:00
|
|
|
s = os.stat(path)
|
2011-08-22 18:28:27 -03:00
|
|
|
if uid is not None:
|
|
|
|
self.assertEqual(uid, s.st_uid)
|
|
|
|
if gid is not None:
|
|
|
|
self.assertEqual(gid, s.st_gid)
|
|
|
|
|
|
|
|
shutil.chown(filename, uid, gid)
|
|
|
|
check_chown(filename, uid, gid)
|
|
|
|
shutil.chown(filename, uid)
|
|
|
|
check_chown(filename, uid)
|
|
|
|
shutil.chown(filename, user=uid)
|
|
|
|
check_chown(filename, uid)
|
|
|
|
shutil.chown(filename, group=gid)
|
2011-08-22 18:55:39 -03:00
|
|
|
check_chown(filename, gid=gid)
|
2011-08-22 18:28:27 -03:00
|
|
|
|
|
|
|
shutil.chown(dirname, uid, gid)
|
|
|
|
check_chown(dirname, uid, gid)
|
|
|
|
shutil.chown(dirname, uid)
|
|
|
|
check_chown(dirname, uid)
|
|
|
|
shutil.chown(dirname, user=uid)
|
|
|
|
check_chown(dirname, uid)
|
|
|
|
shutil.chown(dirname, group=gid)
|
2011-08-22 18:55:39 -03:00
|
|
|
check_chown(dirname, gid=gid)
|
2011-08-22 18:28:27 -03:00
|
|
|
|
2020-03-17 13:51:44 -03:00
|
|
|
try:
|
|
|
|
user = pwd.getpwuid(uid)[0]
|
|
|
|
group = grp.getgrgid(gid)[0]
|
|
|
|
except KeyError:
|
|
|
|
# On some systems uid/gid cannot be resolved.
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
shutil.chown(filename, user, group)
|
|
|
|
check_chown(filename, uid, gid)
|
|
|
|
shutil.chown(dirname, user, group)
|
|
|
|
check_chown(dirname, uid, gid)
|
2011-08-22 18:28:27 -03:00
|
|
|
|
2024-04-22 15:23:36 -03:00
|
|
|
dirfd = os.open(dirname, os.O_RDONLY)
|
|
|
|
self.addCleanup(os.close, dirfd)
|
|
|
|
basename = os.path.basename(filename)
|
|
|
|
baselinkname = os.path.basename(linkname)
|
|
|
|
shutil.chown(basename, uid, gid, dir_fd=dirfd)
|
|
|
|
check_chown(filename, uid, gid)
|
|
|
|
shutil.chown(basename, uid, dir_fd=dirfd)
|
|
|
|
check_chown(filename, uid)
|
|
|
|
shutil.chown(basename, group=gid, dir_fd=dirfd)
|
|
|
|
check_chown(filename, gid=gid)
|
|
|
|
shutil.chown(basename, uid, gid, dir_fd=dirfd, follow_symlinks=True)
|
|
|
|
check_chown(filename, uid, gid)
|
|
|
|
shutil.chown(basename, uid, gid, dir_fd=dirfd, follow_symlinks=False)
|
|
|
|
check_chown(filename, uid, gid)
|
|
|
|
shutil.chown(linkname, uid, follow_symlinks=True)
|
|
|
|
check_chown(filename, uid)
|
|
|
|
shutil.chown(baselinkname, group=gid, dir_fd=dirfd, follow_symlinks=False)
|
|
|
|
check_chown(filename, gid=gid)
|
|
|
|
shutil.chown(baselinkname, uid, gid, dir_fd=dirfd, follow_symlinks=True)
|
|
|
|
check_chown(filename, uid, gid)
|
|
|
|
|
|
|
|
with self.assertRaises(TypeError):
|
|
|
|
shutil.chown(filename, uid, dir_fd=dirname)
|
|
|
|
|
|
|
|
with self.assertRaises(FileNotFoundError):
|
|
|
|
shutil.chown('missingfile', uid, gid, dir_fd=dirfd)
|
|
|
|
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
shutil.chown(filename, dir_fd=dirfd)
|
|
|
|
|
Merged revisions 60124-60142 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r60131 | georg.brandl | 2008-01-20 12:13:29 +0100 (Sun, 20 Jan 2008) | 3 lines
#1351692: in pprint, always call format() for dict and list items to enable
custom formatting of contents via subclassing PrettyPrinter.
........
r60133 | georg.brandl | 2008-01-20 12:43:03 +0100 (Sun, 20 Jan 2008) | 2 lines
#1178141: add addinfourl.code to get http status code from urllib.
........
r60134 | georg.brandl | 2008-01-20 13:05:43 +0100 (Sun, 20 Jan 2008) | 4 lines
#856047: respect the ``no_proxy`` env var when checking for proxies
in urllib and using the other ``_proxy`` env vars.
Original patch by Donovan Baarda.
........
r60135 | georg.brandl | 2008-01-20 13:18:17 +0100 (Sun, 20 Jan 2008) | 4 lines
#1664522: in urllib, don't read non-existing directories in ftp mode,
returning a 0-byte file -- raise an IOError instead.
Original patch from Phil Knirsch.
........
r60136 | georg.brandl | 2008-01-20 13:57:47 +0100 (Sun, 20 Jan 2008) | 2 lines
#799369: document possible sys.platform values.
........
r60137 | georg.brandl | 2008-01-20 14:08:37 +0100 (Sun, 20 Jan 2008) | 2 lines
#652749: document the constants added to the builtins by site.py.
........
r60138 | georg.brandl | 2008-01-20 14:59:46 +0100 (Sun, 20 Jan 2008) | 2 lines
#1648: add sys.gettrace() and sys.getprofile().
........
r60139 | georg.brandl | 2008-01-20 15:17:42 +0100 (Sun, 20 Jan 2008) | 2 lines
#1669: don't allow shutil.rmtree() to be called on a symlink.
........
r60140 | georg.brandl | 2008-01-20 15:20:02 +0100 (Sun, 20 Jan 2008) | 2 lines
Fix test_pyclbr after urllib change.
........
r60141 | christian.heimes | 2008-01-20 15:28:28 +0100 (Sun, 20 Jan 2008) | 1 line
Fixed a wrong assumption in configure.in and Include/pyport.h. The is finite function is not called isfinite() but finite(). Sorry, my fault. :)
........
r60142 | georg.brandl | 2008-01-20 15:31:27 +0100 (Sun, 20 Jan 2008) | 2 lines
#1876: fix typos in test_operator.
........
2008-01-20 11:14:11 -04:00
|
|
|
|
2024-02-04 20:04:57 -04:00
|
|
|
@support.requires_subprocess()
|
2019-09-26 07:15:08 -03:00
|
|
|
class TestWhich(BaseTest, unittest.TestCase):
|
2012-06-22 18:00:30 -03:00
|
|
|
|
|
|
|
def setUp(self):
|
2019-11-15 13:49:21 -04:00
|
|
|
self.temp_dir = self.mkdtemp(prefix="Tmp")
|
2012-06-22 18:00:30 -03:00
|
|
|
# Give the temp_file an ".exe" suffix for all.
|
|
|
|
# It's needed on Windows and not harmful on other platforms.
|
|
|
|
self.temp_file = tempfile.NamedTemporaryFile(dir=self.temp_dir,
|
2013-01-21 09:00:27 -04:00
|
|
|
prefix="Tmp",
|
|
|
|
suffix=".Exe")
|
2012-06-22 18:00:30 -03:00
|
|
|
os.chmod(self.temp_file.name, stat.S_IXUSR)
|
|
|
|
self.addCleanup(self.temp_file.close)
|
|
|
|
self.dir, self.file = os.path.split(self.temp_file.name)
|
2019-02-13 07:25:10 -04:00
|
|
|
self.env_path = self.dir
|
|
|
|
self.curdir = os.curdir
|
|
|
|
self.ext = ".EXE"
|
2012-06-22 18:00:30 -03:00
|
|
|
|
2023-10-02 05:27:30 -03:00
|
|
|
def to_text_type(self, s):
|
|
|
|
'''
|
|
|
|
In this class we're testing with str, so convert s to a str
|
|
|
|
'''
|
|
|
|
if isinstance(s, bytes):
|
|
|
|
return s.decode()
|
|
|
|
return s
|
|
|
|
|
2012-06-22 18:00:30 -03:00
|
|
|
def test_basic(self):
|
|
|
|
# Given an EXE in a directory, it should be returned.
|
|
|
|
rv = shutil.which(self.file, path=self.dir)
|
|
|
|
self.assertEqual(rv, self.temp_file.name)
|
|
|
|
|
2013-01-23 04:44:21 -04:00
|
|
|
def test_absolute_cmd(self):
|
2012-06-22 18:00:30 -03:00
|
|
|
# When given the fully qualified path to an executable that exists,
|
|
|
|
# it should be returned.
|
|
|
|
rv = shutil.which(self.temp_file.name, path=self.temp_dir)
|
2013-01-23 04:44:21 -04:00
|
|
|
self.assertEqual(rv, self.temp_file.name)
|
|
|
|
|
|
|
|
def test_relative_cmd(self):
|
|
|
|
# When given the relative path with a directory part to an executable
|
|
|
|
# that exists, it should be returned.
|
|
|
|
base_dir, tail_dir = os.path.split(self.dir)
|
|
|
|
relpath = os.path.join(tail_dir, self.file)
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(path=base_dir):
|
2013-01-23 04:44:21 -04:00
|
|
|
rv = shutil.which(relpath, path=self.temp_dir)
|
|
|
|
self.assertEqual(rv, relpath)
|
|
|
|
# But it shouldn't be searched in PATH directories (issue #16957).
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(path=self.dir):
|
2013-01-23 04:44:21 -04:00
|
|
|
rv = shutil.which(relpath, path=base_dir)
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
2023-04-04 19:24:13 -03:00
|
|
|
@unittest.skipUnless(sys.platform != "win32",
|
|
|
|
"test is for non win32")
|
|
|
|
def test_cwd_non_win32(self):
|
2013-01-23 04:44:21 -04:00
|
|
|
# Issue #16957
|
|
|
|
base_dir = os.path.dirname(self.dir)
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(path=self.dir):
|
2013-01-23 04:44:21 -04:00
|
|
|
rv = shutil.which(self.file, path=base_dir)
|
2023-04-04 19:24:13 -03:00
|
|
|
# non-win32: shouldn't match in the current directory.
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
|
|
|
@unittest.skipUnless(sys.platform == "win32",
|
|
|
|
"test is for win32")
|
|
|
|
def test_cwd_win32(self):
|
|
|
|
base_dir = os.path.dirname(self.dir)
|
|
|
|
with os_helper.change_cwd(path=self.dir):
|
|
|
|
with unittest.mock.patch('shutil._win_path_needs_curdir', return_value=True):
|
|
|
|
rv = shutil.which(self.file, path=base_dir)
|
|
|
|
# Current directory implicitly on PATH
|
2019-02-13 07:25:10 -04:00
|
|
|
self.assertEqual(rv, os.path.join(self.curdir, self.file))
|
2023-04-04 19:24:13 -03:00
|
|
|
with unittest.mock.patch('shutil._win_path_needs_curdir', return_value=False):
|
|
|
|
rv = shutil.which(self.file, path=base_dir)
|
|
|
|
# Current directory not on PATH
|
2013-01-23 04:44:21 -04:00
|
|
|
self.assertIsNone(rv)
|
2012-06-22 18:00:30 -03:00
|
|
|
|
2023-04-04 19:24:13 -03:00
|
|
|
@unittest.skipUnless(sys.platform == "win32",
|
|
|
|
"test is for win32")
|
|
|
|
def test_cwd_win32_added_before_all_other_path(self):
|
|
|
|
base_dir = pathlib.Path(os.fsdecode(self.dir))
|
|
|
|
|
|
|
|
elsewhere_in_path_dir = base_dir / 'dir1'
|
|
|
|
elsewhere_in_path_dir.mkdir()
|
|
|
|
match_elsewhere_in_path = elsewhere_in_path_dir / 'hello.exe'
|
|
|
|
match_elsewhere_in_path.touch()
|
|
|
|
|
|
|
|
exe_in_cwd = base_dir / 'hello.exe'
|
|
|
|
exe_in_cwd.touch()
|
|
|
|
|
|
|
|
with os_helper.change_cwd(path=base_dir):
|
|
|
|
with unittest.mock.patch('shutil._win_path_needs_curdir', return_value=True):
|
|
|
|
rv = shutil.which('hello.exe', path=elsewhere_in_path_dir)
|
|
|
|
|
|
|
|
self.assertEqual(os.path.abspath(rv), os.path.abspath(exe_in_cwd))
|
|
|
|
|
|
|
|
@unittest.skipUnless(sys.platform == "win32",
|
|
|
|
"test is for win32")
|
|
|
|
def test_pathext_match_before_path_full_match(self):
|
|
|
|
base_dir = pathlib.Path(os.fsdecode(self.dir))
|
|
|
|
dir1 = base_dir / 'dir1'
|
|
|
|
dir2 = base_dir / 'dir2'
|
|
|
|
dir1.mkdir()
|
|
|
|
dir2.mkdir()
|
|
|
|
|
|
|
|
pathext_match = dir1 / 'hello.com.exe'
|
|
|
|
path_match = dir2 / 'hello.com'
|
|
|
|
pathext_match.touch()
|
|
|
|
path_match.touch()
|
|
|
|
|
|
|
|
test_path = os.pathsep.join([str(dir1), str(dir2)])
|
|
|
|
assert os.path.basename(shutil.which(
|
|
|
|
'hello.com', path=test_path, mode = os.F_OK
|
|
|
|
)).lower() == 'hello.com.exe'
|
|
|
|
|
2022-06-27 15:27:19 -03:00
|
|
|
@os_helper.skip_if_dac_override
|
2012-06-22 18:00:30 -03:00
|
|
|
def test_non_matching_mode(self):
|
|
|
|
# Set the file read-only and ask for writeable files.
|
|
|
|
os.chmod(self.temp_file.name, stat.S_IREAD)
|
2013-05-28 09:50:15 -03:00
|
|
|
if os.access(self.temp_file.name, os.W_OK):
|
|
|
|
self.skipTest("can't set the file read-only")
|
2012-06-22 18:00:30 -03:00
|
|
|
rv = shutil.which(self.file, path=self.dir, mode=os.W_OK)
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
2013-01-23 04:44:21 -04:00
|
|
|
def test_relative_path(self):
|
2012-06-22 18:33:05 -03:00
|
|
|
base_dir, tail_dir = os.path.split(self.dir)
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(path=base_dir):
|
2012-06-22 18:33:05 -03:00
|
|
|
rv = shutil.which(self.file, path=tail_dir)
|
|
|
|
self.assertEqual(rv, os.path.join(tail_dir, self.file))
|
|
|
|
|
2012-06-22 18:00:30 -03:00
|
|
|
def test_nonexistent_file(self):
|
|
|
|
# Return None when no matching executable file is found on the path.
|
|
|
|
rv = shutil.which("foo.exe", path=self.dir)
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
|
|
|
@unittest.skipUnless(sys.platform == "win32",
|
|
|
|
"pathext check is Windows-only")
|
|
|
|
def test_pathext_checking(self):
|
|
|
|
# Ask for the file without the ".exe" extension, then ensure that
|
|
|
|
# it gets found properly with the extension.
|
2013-01-24 14:03:49 -04:00
|
|
|
rv = shutil.which(self.file[:-4], path=self.dir)
|
2019-02-13 07:25:10 -04:00
|
|
|
self.assertEqual(rv, self.temp_file.name[:-4] + self.ext)
|
2012-06-22 18:00:30 -03:00
|
|
|
|
2013-04-16 12:05:03 -03:00
|
|
|
def test_environ_path(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2019-02-13 07:25:10 -04:00
|
|
|
env['PATH'] = self.env_path
|
2013-04-16 12:05:03 -03:00
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertEqual(rv, self.temp_file.name)
|
|
|
|
|
2019-04-17 11:26:36 -03:00
|
|
|
def test_environ_path_empty(self):
|
|
|
|
# PATH='': no match
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2019-04-17 11:26:36 -03:00
|
|
|
env['PATH'] = ''
|
|
|
|
with unittest.mock.patch('os.confstr', return_value=self.dir, \
|
|
|
|
create=True), \
|
|
|
|
support.swap_attr(os, 'defpath', self.dir), \
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.change_cwd(self.dir):
|
2019-04-17 11:26:36 -03:00
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
|
|
|
def test_environ_path_cwd(self):
|
|
|
|
expected_cwd = os.path.basename(self.temp_file.name)
|
|
|
|
if sys.platform == "win32":
|
|
|
|
curdir = os.curdir
|
|
|
|
if isinstance(expected_cwd, bytes):
|
|
|
|
curdir = os.fsencode(curdir)
|
|
|
|
expected_cwd = os.path.join(curdir, expected_cwd)
|
|
|
|
|
|
|
|
# PATH=':': explicitly looks in the current directory
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2019-04-17 11:26:36 -03:00
|
|
|
env['PATH'] = os.pathsep
|
|
|
|
with unittest.mock.patch('os.confstr', return_value=self.dir, \
|
|
|
|
create=True), \
|
|
|
|
support.swap_attr(os, 'defpath', self.dir):
|
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
|
|
|
# look in current directory
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(self.dir):
|
2019-04-17 11:26:36 -03:00
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertEqual(rv, expected_cwd)
|
|
|
|
|
|
|
|
def test_environ_path_missing(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2019-04-17 11:26:36 -03:00
|
|
|
env.pop('PATH', None)
|
|
|
|
|
|
|
|
# without confstr
|
|
|
|
with unittest.mock.patch('os.confstr', side_effect=ValueError, \
|
|
|
|
create=True), \
|
|
|
|
support.swap_attr(os, 'defpath', self.dir):
|
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertEqual(rv, self.temp_file.name)
|
|
|
|
|
|
|
|
# with confstr
|
|
|
|
with unittest.mock.patch('os.confstr', return_value=self.dir, \
|
|
|
|
create=True), \
|
|
|
|
support.swap_attr(os, 'defpath', ''):
|
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertEqual(rv, self.temp_file.name)
|
|
|
|
|
2013-04-16 12:05:03 -03:00
|
|
|
def test_empty_path(self):
|
|
|
|
base_dir = os.path.dirname(self.dir)
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.change_cwd(path=self.dir), \
|
|
|
|
os_helper.EnvironmentVarGuard() as env:
|
2019-02-13 07:25:10 -04:00
|
|
|
env['PATH'] = self.env_path
|
2013-04-16 12:05:03 -03:00
|
|
|
rv = shutil.which(self.file, path='')
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
|
|
|
def test_empty_path_no_PATH(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2013-04-16 12:05:03 -03:00
|
|
|
env.pop('PATH', None)
|
|
|
|
rv = shutil.which(self.file)
|
|
|
|
self.assertIsNone(rv)
|
|
|
|
|
2019-04-17 11:26:36 -03:00
|
|
|
@unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
|
|
|
|
def test_pathext(self):
|
2023-10-02 05:27:30 -03:00
|
|
|
ext = self.to_text_type(".xyz")
|
2019-04-17 11:26:36 -03:00
|
|
|
temp_filexyz = tempfile.NamedTemporaryFile(dir=self.temp_dir,
|
2023-10-02 05:27:30 -03:00
|
|
|
prefix=self.to_text_type("Tmp2"), suffix=ext)
|
2019-04-17 11:26:36 -03:00
|
|
|
os.chmod(temp_filexyz.name, stat.S_IXUSR)
|
|
|
|
self.addCleanup(temp_filexyz.close)
|
|
|
|
|
|
|
|
# strip path and extension
|
|
|
|
program = os.path.basename(temp_filexyz.name)
|
|
|
|
program = os.path.splitext(program)[0]
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2023-10-02 05:27:30 -03:00
|
|
|
env['PATHEXT'] = ext if isinstance(ext, str) else ext.decode()
|
2019-04-17 11:26:36 -03:00
|
|
|
rv = shutil.which(program, path=self.temp_dir)
|
|
|
|
self.assertEqual(rv, temp_filexyz.name)
|
|
|
|
|
2020-10-23 07:08:24 -03:00
|
|
|
# Issue 40592: See https://bugs.python.org/issue40592
|
|
|
|
@unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
|
|
|
|
def test_pathext_with_empty_str(self):
|
2023-10-02 05:27:30 -03:00
|
|
|
ext = self.to_text_type(".xyz")
|
2020-10-23 07:08:24 -03:00
|
|
|
temp_filexyz = tempfile.NamedTemporaryFile(dir=self.temp_dir,
|
2023-10-02 05:27:30 -03:00
|
|
|
prefix=self.to_text_type("Tmp2"), suffix=ext)
|
2020-10-23 07:08:24 -03:00
|
|
|
self.addCleanup(temp_filexyz.close)
|
|
|
|
|
|
|
|
# strip path and extension
|
|
|
|
program = os.path.basename(temp_filexyz.name)
|
|
|
|
program = os.path.splitext(program)[0]
|
|
|
|
|
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2023-10-02 05:27:30 -03:00
|
|
|
env['PATHEXT'] = f"{ext if isinstance(ext, str) else ext.decode()};" # note the ;
|
2020-10-23 07:08:24 -03:00
|
|
|
rv = shutil.which(program, path=self.temp_dir)
|
|
|
|
self.assertEqual(rv, temp_filexyz.name)
|
|
|
|
|
2023-04-04 19:24:13 -03:00
|
|
|
# See GH-75586
|
|
|
|
@unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
|
|
|
|
def test_pathext_applied_on_files_in_path(self):
|
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2023-10-02 05:27:30 -03:00
|
|
|
env["PATH"] = self.temp_dir if isinstance(self.temp_dir, str) else self.temp_dir.decode()
|
2023-04-04 19:24:13 -03:00
|
|
|
env["PATHEXT"] = ".test"
|
|
|
|
|
2023-10-02 05:27:30 -03:00
|
|
|
test_path = os.path.join(self.temp_dir, self.to_text_type("test_program.test"))
|
|
|
|
open(test_path, 'w').close()
|
|
|
|
os.chmod(test_path, 0o755)
|
2023-04-04 19:24:13 -03:00
|
|
|
|
2023-10-02 05:27:30 -03:00
|
|
|
self.assertEqual(shutil.which(self.to_text_type("test_program")), test_path)
|
2023-04-04 19:24:13 -03:00
|
|
|
|
|
|
|
# See GH-75586
|
|
|
|
@unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
|
|
|
|
def test_win_path_needs_curdir(self):
|
|
|
|
with unittest.mock.patch('_winapi.NeedCurrentDirectoryForExePath', return_value=True) as need_curdir_mock:
|
|
|
|
self.assertTrue(shutil._win_path_needs_curdir('dontcare', os.X_OK))
|
|
|
|
need_curdir_mock.assert_called_once_with('dontcare')
|
|
|
|
need_curdir_mock.reset_mock()
|
|
|
|
self.assertTrue(shutil._win_path_needs_curdir('dontcare', 0))
|
|
|
|
need_curdir_mock.assert_not_called()
|
|
|
|
|
|
|
|
with unittest.mock.patch('_winapi.NeedCurrentDirectoryForExePath', return_value=False) as need_curdir_mock:
|
|
|
|
self.assertFalse(shutil._win_path_needs_curdir('dontcare', os.X_OK))
|
|
|
|
need_curdir_mock.assert_called_once_with('dontcare')
|
|
|
|
|
2023-10-02 05:27:30 -03:00
|
|
|
# See GH-109590
|
|
|
|
@unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
|
|
|
|
def test_pathext_preferred_for_execute(self):
|
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
|
|
|
env["PATH"] = self.temp_dir if isinstance(self.temp_dir, str) else self.temp_dir.decode()
|
|
|
|
env["PATHEXT"] = ".test"
|
|
|
|
|
|
|
|
exe = os.path.join(self.temp_dir, self.to_text_type("test.exe"))
|
|
|
|
open(exe, 'w').close()
|
|
|
|
os.chmod(exe, 0o755)
|
|
|
|
|
|
|
|
# default behavior allows a direct match if nothing in PATHEXT matches
|
|
|
|
self.assertEqual(shutil.which(self.to_text_type("test.exe")), exe)
|
|
|
|
|
|
|
|
dot_test = os.path.join(self.temp_dir, self.to_text_type("test.exe.test"))
|
|
|
|
open(dot_test, 'w').close()
|
|
|
|
os.chmod(dot_test, 0o755)
|
|
|
|
|
|
|
|
# now we have a PATHEXT match, so it take precedence
|
|
|
|
self.assertEqual(shutil.which(self.to_text_type("test.exe")), dot_test)
|
|
|
|
|
|
|
|
# but if we don't use os.X_OK we don't change the order based off PATHEXT
|
|
|
|
# and therefore get the direct match.
|
|
|
|
self.assertEqual(shutil.which(self.to_text_type("test.exe"), mode=os.F_OK), exe)
|
|
|
|
|
|
|
|
# See GH-109590
|
|
|
|
@unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
|
|
|
|
def test_pathext_given_extension_preferred(self):
|
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
|
|
|
env["PATH"] = self.temp_dir if isinstance(self.temp_dir, str) else self.temp_dir.decode()
|
|
|
|
env["PATHEXT"] = ".exe2;.exe"
|
|
|
|
|
|
|
|
exe = os.path.join(self.temp_dir, self.to_text_type("test.exe"))
|
|
|
|
open(exe, 'w').close()
|
|
|
|
os.chmod(exe, 0o755)
|
|
|
|
|
|
|
|
exe2 = os.path.join(self.temp_dir, self.to_text_type("test.exe2"))
|
|
|
|
open(exe2, 'w').close()
|
|
|
|
os.chmod(exe2, 0o755)
|
|
|
|
|
|
|
|
# even though .exe2 is preferred in PATHEXT, we matched directly to test.exe
|
|
|
|
self.assertEqual(shutil.which(self.to_text_type("test.exe")), exe)
|
|
|
|
self.assertEqual(shutil.which(self.to_text_type("test")), exe2)
|
|
|
|
|
2012-06-22 18:00:30 -03:00
|
|
|
|
2019-02-13 07:25:10 -04:00
|
|
|
class TestWhichBytes(TestWhich):
|
|
|
|
def setUp(self):
|
|
|
|
TestWhich.setUp(self)
|
|
|
|
self.dir = os.fsencode(self.dir)
|
|
|
|
self.file = os.fsencode(self.file)
|
|
|
|
self.temp_file.name = os.fsencode(self.temp_file.name)
|
2023-10-02 05:27:30 -03:00
|
|
|
self.temp_dir = os.fsencode(self.temp_dir)
|
2019-02-13 07:25:10 -04:00
|
|
|
self.curdir = os.fsencode(self.curdir)
|
|
|
|
self.ext = os.fsencode(self.ext)
|
|
|
|
|
2023-10-02 05:27:30 -03:00
|
|
|
def to_text_type(self, s):
|
|
|
|
'''
|
|
|
|
In this class we're testing with bytes, so convert s to a bytes
|
|
|
|
'''
|
|
|
|
if isinstance(s, str):
|
|
|
|
return s.encode()
|
|
|
|
return s
|
|
|
|
|
2019-02-13 07:25:10 -04:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
class TestMove(BaseTest, unittest.TestCase):
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
filename = "foo"
|
2019-09-26 07:15:08 -03:00
|
|
|
self.src_dir = self.mkdtemp()
|
|
|
|
self.dst_dir = self.mkdtemp()
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
self.src_file = os.path.join(self.src_dir, filename)
|
|
|
|
self.dst_file = os.path.join(self.dst_dir, filename)
|
|
|
|
with open(self.src_file, "wb") as f:
|
|
|
|
f.write(b"spam")
|
|
|
|
|
|
|
|
def _check_move_file(self, src, dst, real_dst):
|
2010-10-14 19:11:44 -03:00
|
|
|
with open(src, "rb") as f:
|
|
|
|
contents = f.read()
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
shutil.move(src, dst)
|
2010-10-14 19:11:44 -03:00
|
|
|
with open(real_dst, "rb") as f:
|
|
|
|
self.assertEqual(contents, f.read())
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
self.assertFalse(os.path.exists(src))
|
|
|
|
|
|
|
|
def _check_move_dir(self, src, dst, real_dst):
|
|
|
|
contents = sorted(os.listdir(src))
|
|
|
|
shutil.move(src, dst)
|
|
|
|
self.assertEqual(contents, sorted(os.listdir(real_dst)))
|
|
|
|
self.assertFalse(os.path.exists(src))
|
|
|
|
|
|
|
|
def test_move_file(self):
|
|
|
|
# Move a file to another location on the same filesystem.
|
|
|
|
self._check_move_file(self.src_file, self.dst_file, self.dst_file)
|
|
|
|
|
|
|
|
def test_move_file_to_dir(self):
|
|
|
|
# Move a file inside an existing dir on the same filesystem.
|
|
|
|
self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
|
|
|
|
|
bpo-32689: Updates shutil.move to allow for Path objects to be used as source arg (GH-15326)
Important work originally done by @emilyemorehouse two years ago and nearly ready to go in.
This bug has affected many people and in some cases has been a dealbreaker to the adoption of the otherwise wonderful pathlib and PEP519. https://stackoverflow.com/questions/33625931/copy-file-with-pathlib-in-python.
This adds the outstanding test request from that PR @vstinner (https://github.com/python/cpython/pull/5393).
Test fails without the change, passes with it, along with every other test in test_shutil.
Some variants were experimented with to make the one line change and the most performant one was picked.
# Added Test for PathLike directory destination, the current fail case
```
Lib/test/test_shutil.py::TestMove::test_move_file_pathlike FAILED [100%]
============================================================== FAILURES ===============================================================
__________________________________________________ TestMove.test_move_file_pathlike ___________________________________________________
self = <test.test_shutil.TestMove testMethod=test_move_file_pathlike>
def test_move_file_pathlike(self):
# Move a file to another location on the same filesystem.
src = pathlib.Path(self.src_file)
> self._check_move_file(src, self.dst_dir, self.dst_file)
Lib/test/test_shutil.py:1563:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Lib/test/test_shutil.py:1545: in _check_move_file
shutil.move(src, dst)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py:562: in move
real_dst = os.path.join(dst, _basename(src))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
path = PosixPath('/var/folders/r2/psq74t5x3nbfzlph8bh2pvdw0000gn/T/tmp9ie0wh9_/foo')
def _basename(path):
# A basename() variant which first strips the trailing slash, if present.
# Thus we always get the last component of the path, even for directories.
sep = os.path.sep + (os.path.altsep or '')
> return os.path.basename(path.rstrip(sep))
E AttributeError: 'PosixPath' object has no attribute 'rstrip'
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py:526: AttributeError
============================================== 1 failed, 102 deselected in 0.30 seconds ===============================================
```
After change:
```
========================================================= test session starts =========================================================
platform darwin -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /Users/maxwellmckinnon/.venvs/TA3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/maxwellmckinnon/dev/cpython
plugins: cov-2.7.1, mock-1.10.4
collected 103 items / 102 deselected / 1 selected
Lib/test/test_shutil.py::TestMove::test_move_file_pathlike PASSED [100%]
============================================== 1 passed, 102 deselected in 0.06 seconds ===============================================
```
Running all the tests in test_shutil.py
```
╰─ pytest Lib/test/test_shutil.py -v
========================================================= test session starts =========================================================
platform darwin -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /Users/maxwellmckinnon/.venvs/TA3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/maxwellmckinnon/dev/cpython
plugins: cov-2.7.1, mock-1.10.4
collected 103 items
Lib/test/test_shutil.py::TestShutil::test_chown PASSED [ 0%]
Lib/test/test_shutil.py::TestShutil::test_copy PASSED [ 1%]
...
Lib/test/test_shutil.py::TermsizeTests::test_stty_match SKIPPED [ 99%]
Lib/test/test_shutil.py::PublicAPITests::test_module_all_attribute PASSED [100%]
================================================ 96 passed, 7 skipped in 1.25 seconds =================================================
```
# Performance Considerations
Is it considered poor form to get rid of _basename altogether and make use of pathlib in the move function? I'm not sure if the idea is for all these modules to strictly avoid circular dependencies. They are already using os.path which is just as much a citizen in 3.8 as pathlib right?
e.g.
`real_dst = os.path.join(dst, _basename(src))`
becomes
`real_dst = Path(dst) / Path(src).name`
I've looked around and familiarized myself, and I now think importing pathlib here is fine. My only remaining concern is that of performance.
Here's the performance difference for this step.
```
In [46]: %timeit real_dst = os.path.join("a/b/c", _basename('b/'))
2.71 µs ± 62.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [47]: %timeit real_dst = Path("a/b/c") / Path('b/').name
12.4 µs ± 65.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
```
Is 10us significant or insignificant compared to the least expensive operation this function will do? I don't know. Let's find out.
```
In [55]: %timeit os.rename('/tmp/a/a.txt', '/tmp/a/b.txt'); os.rename('/tmp/a/b.txt', '/tmp/a/a.txt')
124 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
62us to rename. 10us seems significant enough that we wouldn't want to favor the Path sugar suggestion. 16% speed decrease from adding the 10us.
What do people think? I was hoping to get to use pathlib.Path here, but I suspect for this low level move, it should be as fast as possible, and 16% is not worth one line of sugary code to me.
https://bugs.python.org/issue32689
Automerge-Triggered-By: @gvanrossum
2019-09-30 23:41:16 -03:00
|
|
|
def test_move_file_to_dir_pathlike_src(self):
|
|
|
|
# Move a pathlike file to another location on the same filesystem.
|
2024-05-16 04:25:10 -03:00
|
|
|
src = FakePath(self.src_file)
|
bpo-32689: Updates shutil.move to allow for Path objects to be used as source arg (GH-15326)
Important work originally done by @emilyemorehouse two years ago and nearly ready to go in.
This bug has affected many people and in some cases has been a dealbreaker to the adoption of the otherwise wonderful pathlib and PEP519. https://stackoverflow.com/questions/33625931/copy-file-with-pathlib-in-python.
This adds the outstanding test request from that PR @vstinner (https://github.com/python/cpython/pull/5393).
Test fails without the change, passes with it, along with every other test in test_shutil.
Some variants were experimented with to make the one line change and the most performant one was picked.
# Added Test for PathLike directory destination, the current fail case
```
Lib/test/test_shutil.py::TestMove::test_move_file_pathlike FAILED [100%]
============================================================== FAILURES ===============================================================
__________________________________________________ TestMove.test_move_file_pathlike ___________________________________________________
self = <test.test_shutil.TestMove testMethod=test_move_file_pathlike>
def test_move_file_pathlike(self):
# Move a file to another location on the same filesystem.
src = pathlib.Path(self.src_file)
> self._check_move_file(src, self.dst_dir, self.dst_file)
Lib/test/test_shutil.py:1563:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Lib/test/test_shutil.py:1545: in _check_move_file
shutil.move(src, dst)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py:562: in move
real_dst = os.path.join(dst, _basename(src))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
path = PosixPath('/var/folders/r2/psq74t5x3nbfzlph8bh2pvdw0000gn/T/tmp9ie0wh9_/foo')
def _basename(path):
# A basename() variant which first strips the trailing slash, if present.
# Thus we always get the last component of the path, even for directories.
sep = os.path.sep + (os.path.altsep or '')
> return os.path.basename(path.rstrip(sep))
E AttributeError: 'PosixPath' object has no attribute 'rstrip'
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py:526: AttributeError
============================================== 1 failed, 102 deselected in 0.30 seconds ===============================================
```
After change:
```
========================================================= test session starts =========================================================
platform darwin -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /Users/maxwellmckinnon/.venvs/TA3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/maxwellmckinnon/dev/cpython
plugins: cov-2.7.1, mock-1.10.4
collected 103 items / 102 deselected / 1 selected
Lib/test/test_shutil.py::TestMove::test_move_file_pathlike PASSED [100%]
============================================== 1 passed, 102 deselected in 0.06 seconds ===============================================
```
Running all the tests in test_shutil.py
```
╰─ pytest Lib/test/test_shutil.py -v
========================================================= test session starts =========================================================
platform darwin -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /Users/maxwellmckinnon/.venvs/TA3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/maxwellmckinnon/dev/cpython
plugins: cov-2.7.1, mock-1.10.4
collected 103 items
Lib/test/test_shutil.py::TestShutil::test_chown PASSED [ 0%]
Lib/test/test_shutil.py::TestShutil::test_copy PASSED [ 1%]
...
Lib/test/test_shutil.py::TermsizeTests::test_stty_match SKIPPED [ 99%]
Lib/test/test_shutil.py::PublicAPITests::test_module_all_attribute PASSED [100%]
================================================ 96 passed, 7 skipped in 1.25 seconds =================================================
```
# Performance Considerations
Is it considered poor form to get rid of _basename altogether and make use of pathlib in the move function? I'm not sure if the idea is for all these modules to strictly avoid circular dependencies. They are already using os.path which is just as much a citizen in 3.8 as pathlib right?
e.g.
`real_dst = os.path.join(dst, _basename(src))`
becomes
`real_dst = Path(dst) / Path(src).name`
I've looked around and familiarized myself, and I now think importing pathlib here is fine. My only remaining concern is that of performance.
Here's the performance difference for this step.
```
In [46]: %timeit real_dst = os.path.join("a/b/c", _basename('b/'))
2.71 µs ± 62.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [47]: %timeit real_dst = Path("a/b/c") / Path('b/').name
12.4 µs ± 65.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
```
Is 10us significant or insignificant compared to the least expensive operation this function will do? I don't know. Let's find out.
```
In [55]: %timeit os.rename('/tmp/a/a.txt', '/tmp/a/b.txt'); os.rename('/tmp/a/b.txt', '/tmp/a/a.txt')
124 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
62us to rename. 10us seems significant enough that we wouldn't want to favor the Path sugar suggestion. 16% speed decrease from adding the 10us.
What do people think? I was hoping to get to use pathlib.Path here, but I suspect for this low level move, it should be as fast as possible, and 16% is not worth one line of sugary code to me.
https://bugs.python.org/issue32689
Automerge-Triggered-By: @gvanrossum
2019-09-30 23:41:16 -03:00
|
|
|
self._check_move_file(src, self.dst_dir, self.dst_file)
|
|
|
|
|
|
|
|
def test_move_file_to_dir_pathlike_dst(self):
|
|
|
|
# Move a file to another pathlike location on the same filesystem.
|
2024-05-16 04:25:10 -03:00
|
|
|
dst = FakePath(self.dst_dir)
|
bpo-32689: Updates shutil.move to allow for Path objects to be used as source arg (GH-15326)
Important work originally done by @emilyemorehouse two years ago and nearly ready to go in.
This bug has affected many people and in some cases has been a dealbreaker to the adoption of the otherwise wonderful pathlib and PEP519. https://stackoverflow.com/questions/33625931/copy-file-with-pathlib-in-python.
This adds the outstanding test request from that PR @vstinner (https://github.com/python/cpython/pull/5393).
Test fails without the change, passes with it, along with every other test in test_shutil.
Some variants were experimented with to make the one line change and the most performant one was picked.
# Added Test for PathLike directory destination, the current fail case
```
Lib/test/test_shutil.py::TestMove::test_move_file_pathlike FAILED [100%]
============================================================== FAILURES ===============================================================
__________________________________________________ TestMove.test_move_file_pathlike ___________________________________________________
self = <test.test_shutil.TestMove testMethod=test_move_file_pathlike>
def test_move_file_pathlike(self):
# Move a file to another location on the same filesystem.
src = pathlib.Path(self.src_file)
> self._check_move_file(src, self.dst_dir, self.dst_file)
Lib/test/test_shutil.py:1563:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Lib/test/test_shutil.py:1545: in _check_move_file
shutil.move(src, dst)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py:562: in move
real_dst = os.path.join(dst, _basename(src))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
path = PosixPath('/var/folders/r2/psq74t5x3nbfzlph8bh2pvdw0000gn/T/tmp9ie0wh9_/foo')
def _basename(path):
# A basename() variant which first strips the trailing slash, if present.
# Thus we always get the last component of the path, even for directories.
sep = os.path.sep + (os.path.altsep or '')
> return os.path.basename(path.rstrip(sep))
E AttributeError: 'PosixPath' object has no attribute 'rstrip'
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py:526: AttributeError
============================================== 1 failed, 102 deselected in 0.30 seconds ===============================================
```
After change:
```
========================================================= test session starts =========================================================
platform darwin -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /Users/maxwellmckinnon/.venvs/TA3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/maxwellmckinnon/dev/cpython
plugins: cov-2.7.1, mock-1.10.4
collected 103 items / 102 deselected / 1 selected
Lib/test/test_shutil.py::TestMove::test_move_file_pathlike PASSED [100%]
============================================== 1 passed, 102 deselected in 0.06 seconds ===============================================
```
Running all the tests in test_shutil.py
```
╰─ pytest Lib/test/test_shutil.py -v
========================================================= test session starts =========================================================
platform darwin -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /Users/maxwellmckinnon/.venvs/TA3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/maxwellmckinnon/dev/cpython
plugins: cov-2.7.1, mock-1.10.4
collected 103 items
Lib/test/test_shutil.py::TestShutil::test_chown PASSED [ 0%]
Lib/test/test_shutil.py::TestShutil::test_copy PASSED [ 1%]
...
Lib/test/test_shutil.py::TermsizeTests::test_stty_match SKIPPED [ 99%]
Lib/test/test_shutil.py::PublicAPITests::test_module_all_attribute PASSED [100%]
================================================ 96 passed, 7 skipped in 1.25 seconds =================================================
```
# Performance Considerations
Is it considered poor form to get rid of _basename altogether and make use of pathlib in the move function? I'm not sure if the idea is for all these modules to strictly avoid circular dependencies. They are already using os.path which is just as much a citizen in 3.8 as pathlib right?
e.g.
`real_dst = os.path.join(dst, _basename(src))`
becomes
`real_dst = Path(dst) / Path(src).name`
I've looked around and familiarized myself, and I now think importing pathlib here is fine. My only remaining concern is that of performance.
Here's the performance difference for this step.
```
In [46]: %timeit real_dst = os.path.join("a/b/c", _basename('b/'))
2.71 µs ± 62.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [47]: %timeit real_dst = Path("a/b/c") / Path('b/').name
12.4 µs ± 65.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
```
Is 10us significant or insignificant compared to the least expensive operation this function will do? I don't know. Let's find out.
```
In [55]: %timeit os.rename('/tmp/a/a.txt', '/tmp/a/b.txt'); os.rename('/tmp/a/b.txt', '/tmp/a/a.txt')
124 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
62us to rename. 10us seems significant enough that we wouldn't want to favor the Path sugar suggestion. 16% speed decrease from adding the 10us.
What do people think? I was hoping to get to use pathlib.Path here, but I suspect for this low level move, it should be as fast as possible, and 16% is not worth one line of sugary code to me.
https://bugs.python.org/issue32689
Automerge-Triggered-By: @gvanrossum
2019-09-30 23:41:16 -03:00
|
|
|
self._check_move_file(self.src_file, dst, self.dst_file)
|
|
|
|
|
2011-03-16 15:05:35 -03:00
|
|
|
@mock_rename
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
def test_move_file_other_fs(self):
|
|
|
|
# Move a file to an existing dir on another filesystem.
|
2011-03-16 15:05:35 -03:00
|
|
|
self.test_move_file()
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
2011-03-16 15:05:35 -03:00
|
|
|
@mock_rename
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
def test_move_file_to_dir_other_fs(self):
|
|
|
|
# Move a file to another location on another filesystem.
|
2011-03-16 15:05:35 -03:00
|
|
|
self.test_move_file_to_dir()
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
|
|
|
def test_move_dir(self):
|
|
|
|
# Move a dir to another location on the same filesystem.
|
2019-11-15 13:49:21 -04:00
|
|
|
dst_dir = tempfile.mktemp(dir=self.mkdtemp())
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
try:
|
|
|
|
self._check_move_dir(self.src_dir, dst_dir, dst_dir)
|
|
|
|
finally:
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.rmtree(dst_dir)
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
2011-03-16 15:05:35 -03:00
|
|
|
@mock_rename
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
def test_move_dir_other_fs(self):
|
|
|
|
# Move a dir to another location on another filesystem.
|
2011-03-16 15:05:35 -03:00
|
|
|
self.test_move_dir()
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
|
|
|
def test_move_dir_to_dir(self):
|
|
|
|
# Move a dir inside an existing dir on the same filesystem.
|
|
|
|
self._check_move_dir(self.src_dir, self.dst_dir,
|
|
|
|
os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
|
|
|
|
|
2011-03-16 15:05:35 -03:00
|
|
|
@mock_rename
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
def test_move_dir_to_dir_other_fs(self):
|
|
|
|
# Move a dir inside an existing dir on another filesystem.
|
2011-03-16 15:05:35 -03:00
|
|
|
self.test_move_dir_to_dir()
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
2014-02-11 04:30:59 -04:00
|
|
|
def test_move_dir_sep_to_dir(self):
|
|
|
|
self._check_move_dir(self.src_dir + os.path.sep, self.dst_dir,
|
|
|
|
os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
|
|
|
|
|
|
|
|
@unittest.skipUnless(os.path.altsep, 'requires os.path.altsep')
|
|
|
|
def test_move_dir_altsep_to_dir(self):
|
|
|
|
self._check_move_dir(self.src_dir + os.path.altsep, self.dst_dir,
|
|
|
|
os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
|
|
|
|
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
def test_existing_file_inside_dest_dir(self):
|
|
|
|
# A file with the same name inside the destination dir already exists.
|
|
|
|
with open(self.dst_file, "wb"):
|
|
|
|
pass
|
|
|
|
self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
|
|
|
|
|
|
|
|
def test_dont_move_dir_in_itself(self):
|
|
|
|
# Moving a dir inside itself raises an Error.
|
|
|
|
dst = os.path.join(self.src_dir, "bar")
|
|
|
|
self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
|
|
|
|
|
2009-01-29 16:26:59 -04:00
|
|
|
def test_destinsrc_false_negative(self):
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
try:
|
|
|
|
for src, dst in [('srcdir', 'srcdir/dest')]:
|
|
|
|
src = os.path.join(TESTFN, src)
|
|
|
|
dst = os.path.join(TESTFN, dst)
|
2009-06-30 20:06:06 -03:00
|
|
|
self.assertTrue(shutil._destinsrc(src, dst),
|
2009-02-20 00:09:19 -04:00
|
|
|
msg='_destinsrc() wrongly concluded that '
|
2009-01-29 16:26:59 -04:00
|
|
|
'dst (%s) is not in src (%s)' % (dst, src))
|
|
|
|
finally:
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.rmtree(TESTFN)
|
Merged revisions 61520,61523-61528,61532 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61520 | thomas.heller | 2008-03-18 16:03:17 +0100 (Di, 18 Mär 2008) | 5 lines
Include <alloca.h> on Solaris, see issue #1506.
It would probably be better to have a configure test for that, but
this is outside of my configure expertise.
........
r61523 | brett.cannon | 2008-03-18 16:35:58 +0100 (Di, 18 Mär 2008) | 5 lines
Remove all traces of HAVE_STRERROR.
The removal of strerror.c led to the function check being removed from
configure.in.
........
r61524 | brett.cannon | 2008-03-18 16:52:00 +0100 (Di, 18 Mär 2008) | 2 lines
Fix test_errno to only check for error numbers that are defined by Standard C.
........
r61525 | steven.bethard | 2008-03-18 17:00:19 +0100 (Di, 18 Mär 2008) | 1 line
Use test_support.unlink instead of os.unlink in tearDown(). (Seems to fix an occasional failure in Windows Vista.)
........
r61526 | brett.cannon | 2008-03-18 17:47:51 +0100 (Di, 18 Mär 2008) | 3 lines
Cast the arguments to PyString_AsStringAndSize() to silence compiler warnings
on OS X.
........
r61527 | sean.reifschneider | 2008-03-18 18:24:12 +0100 (Di, 18 Mär 2008) | 3 lines
Issue 1577: shutil.move() where destination is a directory was doing a
copy, now it is doing a os.rename() if it's on the same file-system.
........
r61528 | brett.cannon | 2008-03-18 18:25:13 +0100 (Di, 18 Mär 2008) | 12 lines
Add Tools/scripts/patchcheck.py. Invoked from ``make check``, the script does
some verification:
- Runs reindent.py on all .py files.
- Checks if any changes in Doc exist.
- Whether Misc/ACKS was changed.
- Whether Misc/NEWS was changed.
The hope is that ``make check`` can become a command anybody can run to get
reminders about what all the requisite steps needed to create a proper
patch/checkin.
........
r61532 | neal.norwitz | 2008-03-18 18:58:02 +0100 (Di, 18 Mär 2008) | 1 line
Get regrtest working when re-running tests
........
2008-03-18 15:26:33 -03:00
|
|
|
|
2009-01-29 16:26:59 -04:00
|
|
|
def test_destinsrc_false_positive(self):
|
|
|
|
os.mkdir(TESTFN)
|
|
|
|
try:
|
|
|
|
for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
|
|
|
|
src = os.path.join(TESTFN, src)
|
|
|
|
dst = os.path.join(TESTFN, dst)
|
2009-06-30 20:06:06 -03:00
|
|
|
self.assertFalse(shutil._destinsrc(src, dst),
|
2009-02-20 00:09:19 -04:00
|
|
|
msg='_destinsrc() wrongly concluded that '
|
2009-01-29 16:26:59 -04:00
|
|
|
'dst (%s) is in src (%s)' % (dst, src))
|
|
|
|
finally:
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.rmtree(TESTFN)
|
Merged revisions 60124-60142 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r60131 | georg.brandl | 2008-01-20 12:13:29 +0100 (Sun, 20 Jan 2008) | 3 lines
#1351692: in pprint, always call format() for dict and list items to enable
custom formatting of contents via subclassing PrettyPrinter.
........
r60133 | georg.brandl | 2008-01-20 12:43:03 +0100 (Sun, 20 Jan 2008) | 2 lines
#1178141: add addinfourl.code to get http status code from urllib.
........
r60134 | georg.brandl | 2008-01-20 13:05:43 +0100 (Sun, 20 Jan 2008) | 4 lines
#856047: respect the ``no_proxy`` env var when checking for proxies
in urllib and using the other ``_proxy`` env vars.
Original patch by Donovan Baarda.
........
r60135 | georg.brandl | 2008-01-20 13:18:17 +0100 (Sun, 20 Jan 2008) | 4 lines
#1664522: in urllib, don't read non-existing directories in ftp mode,
returning a 0-byte file -- raise an IOError instead.
Original patch from Phil Knirsch.
........
r60136 | georg.brandl | 2008-01-20 13:57:47 +0100 (Sun, 20 Jan 2008) | 2 lines
#799369: document possible sys.platform values.
........
r60137 | georg.brandl | 2008-01-20 14:08:37 +0100 (Sun, 20 Jan 2008) | 2 lines
#652749: document the constants added to the builtins by site.py.
........
r60138 | georg.brandl | 2008-01-20 14:59:46 +0100 (Sun, 20 Jan 2008) | 2 lines
#1648: add sys.gettrace() and sys.getprofile().
........
r60139 | georg.brandl | 2008-01-20 15:17:42 +0100 (Sun, 20 Jan 2008) | 2 lines
#1669: don't allow shutil.rmtree() to be called on a symlink.
........
r60140 | georg.brandl | 2008-01-20 15:20:02 +0100 (Sun, 20 Jan 2008) | 2 lines
Fix test_pyclbr after urllib change.
........
r60141 | christian.heimes | 2008-01-20 15:28:28 +0100 (Sun, 20 Jan 2008) | 1 line
Fixed a wrong assumption in configure.in and Include/pyport.h. The is finite function is not called isfinite() but finite(). Sorry, my fault. :)
........
r60142 | georg.brandl | 2008-01-20 15:31:27 +0100 (Sun, 20 Jan 2008) | 2 lines
#1876: fix typos in test_operator.
........
2008-01-20 11:14:11 -04:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2012-01-06 15:16:19 -04:00
|
|
|
@mock_rename
|
|
|
|
def test_move_file_symlink(self):
|
|
|
|
dst = os.path.join(self.src_dir, 'bar')
|
|
|
|
os.symlink(self.src_file, dst)
|
|
|
|
shutil.move(dst, self.dst_file)
|
|
|
|
self.assertTrue(os.path.islink(self.dst_file))
|
|
|
|
self.assertTrue(os.path.samefile(self.src_file, self.dst_file))
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2012-01-06 15:16:19 -04:00
|
|
|
@mock_rename
|
|
|
|
def test_move_file_symlink_to_dir(self):
|
|
|
|
filename = "bar"
|
|
|
|
dst = os.path.join(self.src_dir, filename)
|
|
|
|
os.symlink(self.src_file, dst)
|
|
|
|
shutil.move(dst, self.dst_dir)
|
|
|
|
final_link = os.path.join(self.dst_dir, filename)
|
|
|
|
self.assertTrue(os.path.islink(final_link))
|
|
|
|
self.assertTrue(os.path.samefile(self.src_file, final_link))
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2012-01-06 15:16:19 -04:00
|
|
|
@mock_rename
|
|
|
|
def test_move_dangling_symlink(self):
|
|
|
|
src = os.path.join(self.src_dir, 'baz')
|
|
|
|
dst = os.path.join(self.src_dir, 'bar')
|
|
|
|
os.symlink(src, dst)
|
|
|
|
dst_link = os.path.join(self.dst_dir, 'quux')
|
|
|
|
shutil.move(dst, dst_link)
|
|
|
|
self.assertTrue(os.path.islink(dst_link))
|
2019-08-21 17:43:06 -03:00
|
|
|
self.assertEqual(os.path.realpath(src), os.path.realpath(dst_link))
|
2012-01-06 15:16:19 -04:00
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
@os_helper.skip_unless_symlink
|
2012-01-06 15:16:19 -04:00
|
|
|
@mock_rename
|
|
|
|
def test_move_dir_symlink(self):
|
|
|
|
src = os.path.join(self.src_dir, 'baz')
|
|
|
|
dst = os.path.join(self.src_dir, 'bar')
|
|
|
|
os.mkdir(src)
|
|
|
|
os.symlink(src, dst)
|
|
|
|
dst_link = os.path.join(self.dst_dir, 'quux')
|
|
|
|
shutil.move(dst, dst_link)
|
|
|
|
self.assertTrue(os.path.islink(dst_link))
|
|
|
|
self.assertTrue(os.path.samefile(src, dst_link))
|
|
|
|
|
2012-06-18 20:41:07 -03:00
|
|
|
def test_move_return_value(self):
|
|
|
|
rv = shutil.move(self.src_file, self.dst_dir)
|
|
|
|
self.assertEqual(rv,
|
|
|
|
os.path.join(self.dst_dir, os.path.basename(self.src_file)))
|
|
|
|
|
|
|
|
def test_move_as_rename_return_value(self):
|
|
|
|
rv = shutil.move(self.src_file, os.path.join(self.dst_dir, 'bar'))
|
|
|
|
self.assertEqual(rv, os.path.join(self.dst_dir, 'bar'))
|
|
|
|
|
2014-06-11 15:40:13 -03:00
|
|
|
@mock_rename
|
|
|
|
def test_move_file_special_function(self):
|
|
|
|
moved = []
|
|
|
|
def _copy(src, dst):
|
|
|
|
moved.append((src, dst))
|
|
|
|
shutil.move(self.src_file, self.dst_dir, copy_function=_copy)
|
|
|
|
self.assertEqual(len(moved), 1)
|
|
|
|
|
|
|
|
@mock_rename
|
|
|
|
def test_move_dir_special_function(self):
|
|
|
|
moved = []
|
|
|
|
def _copy(src, dst):
|
|
|
|
moved.append((src, dst))
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.create_empty_file(os.path.join(self.src_dir, 'child'))
|
|
|
|
os_helper.create_empty_file(os.path.join(self.src_dir, 'child1'))
|
2014-06-11 15:40:13 -03:00
|
|
|
shutil.move(self.src_dir, self.dst_dir, copy_function=_copy)
|
|
|
|
self.assertEqual(len(moved), 3)
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
def test_move_dir_caseinsensitive(self):
|
|
|
|
# Renames a folder to the same name
|
|
|
|
# but a different case.
|
2010-04-19 19:30:51 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
self.src_dir = self.mkdtemp()
|
|
|
|
dst_dir = os.path.join(
|
|
|
|
os.path.dirname(self.src_dir),
|
|
|
|
os.path.basename(self.src_dir).upper())
|
|
|
|
self.assertNotEqual(self.src_dir, dst_dir)
|
2010-05-05 19:27:31 -03:00
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
try:
|
|
|
|
shutil.move(self.src_dir, dst_dir)
|
|
|
|
self.assertTrue(os.path.isdir(dst_dir))
|
|
|
|
finally:
|
|
|
|
os.rmdir(dst_dir)
|
|
|
|
|
2023-12-27 12:23:42 -04:00
|
|
|
# bpo-26791: Check that a symlink to a directory can
|
|
|
|
# be moved into that directory.
|
|
|
|
@mock_rename
|
|
|
|
def _test_move_symlink_to_dir_into_dir(self, dst):
|
|
|
|
src = os.path.join(self.src_dir, 'linktodir')
|
|
|
|
dst_link = os.path.join(self.dst_dir, 'linktodir')
|
|
|
|
os.symlink(self.dst_dir, src, target_is_directory=True)
|
|
|
|
shutil.move(src, dst)
|
|
|
|
self.assertTrue(os.path.islink(dst_link))
|
|
|
|
self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
|
|
|
|
self.assertFalse(os.path.exists(src))
|
|
|
|
|
|
|
|
# Repeat the move operation with the destination
|
|
|
|
# symlink already in place (should raise shutil.Error).
|
|
|
|
os.symlink(self.dst_dir, src, target_is_directory=True)
|
|
|
|
with self.assertRaises(shutil.Error):
|
|
|
|
shutil.move(src, dst)
|
|
|
|
self.assertTrue(os.path.samefile(self.dst_dir, dst_link))
|
|
|
|
self.assertTrue(os.path.exists(src))
|
|
|
|
|
|
|
|
@os_helper.skip_unless_symlink
|
|
|
|
def test_move_symlink_to_dir_into_dir(self):
|
|
|
|
self._test_move_symlink_to_dir_into_dir(self.dst_dir)
|
|
|
|
|
|
|
|
@os_helper.skip_unless_symlink
|
|
|
|
def test_move_symlink_to_dir_into_symlink_to_dir(self):
|
|
|
|
dst = os.path.join(self.src_dir, 'otherlinktodir')
|
|
|
|
os.symlink(self.dst_dir, dst, target_is_directory=True)
|
|
|
|
self._test_move_symlink_to_dir_into_dir(dst)
|
2019-09-26 07:15:08 -03:00
|
|
|
|
2022-06-27 15:27:19 -03:00
|
|
|
@os_helper.skip_unless_dac_override
|
|
|
|
@unittest.skipUnless(hasattr(os, 'lchflags')
|
2021-03-02 16:53:15 -04:00
|
|
|
and hasattr(stat, 'SF_IMMUTABLE')
|
|
|
|
and hasattr(stat, 'UF_OPAQUE'),
|
2022-06-27 15:27:19 -03:00
|
|
|
'requires lchflags')
|
2021-03-02 16:53:15 -04:00
|
|
|
def test_move_dir_permission_denied(self):
|
|
|
|
# bpo-42782: shutil.move should not create destination directories
|
|
|
|
# if the source directory cannot be removed.
|
|
|
|
try:
|
|
|
|
os.mkdir(TESTFN_SRC)
|
|
|
|
os.lchflags(TESTFN_SRC, stat.SF_IMMUTABLE)
|
|
|
|
|
|
|
|
# Testing on an empty immutable directory
|
|
|
|
# TESTFN_DST should not exist if shutil.move failed
|
|
|
|
self.assertRaises(PermissionError, shutil.move, TESTFN_SRC, TESTFN_DST)
|
|
|
|
self.assertFalse(TESTFN_DST in os.listdir())
|
|
|
|
|
|
|
|
# Create a file and keep the directory immutable
|
|
|
|
os.lchflags(TESTFN_SRC, stat.UF_OPAQUE)
|
|
|
|
os_helper.create_empty_file(os.path.join(TESTFN_SRC, 'child'))
|
|
|
|
os.lchflags(TESTFN_SRC, stat.SF_IMMUTABLE)
|
|
|
|
|
|
|
|
# Testing on a non-empty immutable directory
|
|
|
|
# TESTFN_DST should not exist if shutil.move failed
|
|
|
|
self.assertRaises(PermissionError, shutil.move, TESTFN_SRC, TESTFN_DST)
|
|
|
|
self.assertFalse(TESTFN_DST in os.listdir())
|
|
|
|
finally:
|
|
|
|
if os.path.exists(TESTFN_SRC):
|
|
|
|
os.lchflags(TESTFN_SRC, stat.UF_OPAQUE)
|
|
|
|
os_helper.rmtree(TESTFN_SRC)
|
|
|
|
if os.path.exists(TESTFN_DST):
|
|
|
|
os.lchflags(TESTFN_DST, stat.UF_OPAQUE)
|
|
|
|
os_helper.rmtree(TESTFN_DST)
|
|
|
|
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
class TestCopyFile(unittest.TestCase):
|
2010-05-05 19:27:31 -03:00
|
|
|
|
|
|
|
class Faux(object):
|
|
|
|
_entered = False
|
|
|
|
_exited_with = None
|
|
|
|
_raised = False
|
|
|
|
def __init__(self, raise_in_exit=False, suppress_at_exit=True):
|
|
|
|
self._raise_in_exit = raise_in_exit
|
|
|
|
self._suppress_at_exit = suppress_at_exit
|
|
|
|
def read(self, *args):
|
|
|
|
return ''
|
|
|
|
def __enter__(self):
|
|
|
|
self._entered = True
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self._exited_with = exc_type, exc_val, exc_tb
|
|
|
|
if self._raise_in_exit:
|
|
|
|
self._raised = True
|
2012-12-25 10:47:37 -04:00
|
|
|
raise OSError("Cannot close")
|
2010-05-05 19:27:31 -03:00
|
|
|
return self._suppress_at_exit
|
|
|
|
|
|
|
|
def test_w_source_open_fails(self):
|
|
|
|
def _open(filename, mode='r'):
|
|
|
|
if filename == 'srcfile':
|
2012-12-25 10:47:37 -04:00
|
|
|
raise OSError('Cannot open "srcfile"')
|
2010-05-05 19:27:31 -03:00
|
|
|
assert 0 # shouldn't reach here.
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
with support.swap_attr(shutil, 'open', _open):
|
|
|
|
with self.assertRaises(OSError):
|
|
|
|
shutil.copyfile('srcfile', 'destfile')
|
2010-05-05 19:27:31 -03:00
|
|
|
|
2018-06-25 21:11:06 -03:00
|
|
|
@unittest.skipIf(MACOS, "skipped on macOS")
|
2010-05-05 19:27:31 -03:00
|
|
|
def test_w_dest_open_fails(self):
|
|
|
|
srcfile = self.Faux()
|
|
|
|
|
|
|
|
def _open(filename, mode='r'):
|
|
|
|
if filename == 'srcfile':
|
|
|
|
return srcfile
|
|
|
|
if filename == 'destfile':
|
2012-12-25 10:47:37 -04:00
|
|
|
raise OSError('Cannot open "destfile"')
|
2010-05-05 19:27:31 -03:00
|
|
|
assert 0 # shouldn't reach here.
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
with support.swap_attr(shutil, 'open', _open):
|
|
|
|
shutil.copyfile('srcfile', 'destfile')
|
2010-05-05 19:27:31 -03:00
|
|
|
self.assertTrue(srcfile._entered)
|
2012-12-25 10:47:37 -04:00
|
|
|
self.assertTrue(srcfile._exited_with[0] is OSError)
|
2010-05-05 19:27:31 -03:00
|
|
|
self.assertEqual(srcfile._exited_with[1].args,
|
|
|
|
('Cannot open "destfile"',))
|
|
|
|
|
2018-06-25 21:11:06 -03:00
|
|
|
@unittest.skipIf(MACOS, "skipped on macOS")
|
2010-05-05 19:27:31 -03:00
|
|
|
def test_w_dest_close_fails(self):
|
|
|
|
srcfile = self.Faux()
|
|
|
|
destfile = self.Faux(True)
|
|
|
|
|
|
|
|
def _open(filename, mode='r'):
|
|
|
|
if filename == 'srcfile':
|
|
|
|
return srcfile
|
|
|
|
if filename == 'destfile':
|
|
|
|
return destfile
|
|
|
|
assert 0 # shouldn't reach here.
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
with support.swap_attr(shutil, 'open', _open):
|
|
|
|
shutil.copyfile('srcfile', 'destfile')
|
2010-05-05 19:27:31 -03:00
|
|
|
self.assertTrue(srcfile._entered)
|
|
|
|
self.assertTrue(destfile._entered)
|
|
|
|
self.assertTrue(destfile._raised)
|
2012-12-25 10:47:37 -04:00
|
|
|
self.assertTrue(srcfile._exited_with[0] is OSError)
|
2010-05-05 19:27:31 -03:00
|
|
|
self.assertEqual(srcfile._exited_with[1].args,
|
|
|
|
('Cannot close',))
|
|
|
|
|
2018-06-25 21:11:06 -03:00
|
|
|
@unittest.skipIf(MACOS, "skipped on macOS")
|
2010-05-05 19:27:31 -03:00
|
|
|
def test_w_source_close_fails(self):
|
|
|
|
|
|
|
|
srcfile = self.Faux(True)
|
|
|
|
destfile = self.Faux()
|
|
|
|
|
|
|
|
def _open(filename, mode='r'):
|
|
|
|
if filename == 'srcfile':
|
|
|
|
return srcfile
|
|
|
|
if filename == 'destfile':
|
|
|
|
return destfile
|
|
|
|
assert 0 # shouldn't reach here.
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
with support.swap_attr(shutil, 'open', _open):
|
|
|
|
with self.assertRaises(OSError):
|
|
|
|
shutil.copyfile('srcfile', 'destfile')
|
2010-05-05 19:27:31 -03:00
|
|
|
self.assertTrue(srcfile._entered)
|
|
|
|
self.assertTrue(destfile._entered)
|
|
|
|
self.assertFalse(destfile._raised)
|
|
|
|
self.assertTrue(srcfile._exited_with[0] is None)
|
|
|
|
self.assertTrue(srcfile._raised)
|
|
|
|
|
2018-06-12 18:04:50 -03:00
|
|
|
|
2018-06-19 12:27:29 -03:00
|
|
|
class TestCopyFileObj(unittest.TestCase):
|
|
|
|
FILESIZE = 2 * 1024 * 1024
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
write_test_file(TESTFN, cls.FILESIZE)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(TESTFN)
|
|
|
|
os_helper.unlink(TESTFN2)
|
2018-06-19 12:27:29 -03:00
|
|
|
|
|
|
|
def tearDown(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(TESTFN2)
|
2018-06-19 12:27:29 -03:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def get_files(self):
|
|
|
|
with open(TESTFN, "rb") as src:
|
|
|
|
with open(TESTFN2, "wb") as dst:
|
|
|
|
yield (src, dst)
|
|
|
|
|
|
|
|
def assert_files_eq(self, src, dst):
|
|
|
|
with open(src, 'rb') as fsrc:
|
|
|
|
with open(dst, 'rb') as fdst:
|
|
|
|
self.assertEqual(fsrc.read(), fdst.read())
|
|
|
|
|
|
|
|
def test_content(self):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
shutil.copyfileobj(src, dst)
|
|
|
|
self.assert_files_eq(TESTFN, TESTFN2)
|
|
|
|
|
|
|
|
def test_file_not_closed(self):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
shutil.copyfileobj(src, dst)
|
|
|
|
assert not src.closed
|
|
|
|
assert not dst.closed
|
|
|
|
|
|
|
|
def test_file_offset(self):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
shutil.copyfileobj(src, dst)
|
|
|
|
self.assertEqual(src.tell(), self.FILESIZE)
|
|
|
|
self.assertEqual(dst.tell(), self.FILESIZE)
|
|
|
|
|
|
|
|
@unittest.skipIf(os.name != 'nt', "Windows only")
|
|
|
|
def test_win_impl(self):
|
|
|
|
# Make sure alternate Windows implementation is called.
|
|
|
|
with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
|
|
|
|
shutil.copyfile(TESTFN, TESTFN2)
|
|
|
|
assert m.called
|
|
|
|
|
|
|
|
# File size is 2 MiB but max buf size should be 1 MiB.
|
|
|
|
self.assertEqual(m.call_args[0][2], 1 * 1024 * 1024)
|
|
|
|
|
|
|
|
# If file size < 1 MiB memoryview() length must be equal to
|
|
|
|
# the actual file size.
|
2019-11-15 13:49:21 -04:00
|
|
|
with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
|
2018-06-19 12:27:29 -03:00
|
|
|
f.write(b'foo')
|
|
|
|
fname = f.name
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(os_helper.unlink, fname)
|
2018-06-19 12:27:29 -03:00
|
|
|
with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
|
|
|
|
shutil.copyfile(fname, TESTFN2)
|
|
|
|
self.assertEqual(m.call_args[0][2], 3)
|
|
|
|
|
|
|
|
# Empty files should not rely on readinto() variant.
|
2019-11-15 13:49:21 -04:00
|
|
|
with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
|
2018-06-19 12:27:29 -03:00
|
|
|
pass
|
|
|
|
fname = f.name
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(os_helper.unlink, fname)
|
2018-06-19 12:27:29 -03:00
|
|
|
with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
|
|
|
|
shutil.copyfile(fname, TESTFN2)
|
|
|
|
assert not m.called
|
|
|
|
self.assert_files_eq(fname, TESTFN2)
|
|
|
|
|
|
|
|
|
2018-06-12 18:04:50 -03:00
|
|
|
class _ZeroCopyFileTest(object):
|
|
|
|
"""Tests common to all zero-copy APIs."""
|
|
|
|
FILESIZE = (10 * 1024 * 1024) # 10 MiB
|
|
|
|
FILEDATA = b""
|
|
|
|
PATCHPOINT = ""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
write_test_file(TESTFN, cls.FILESIZE)
|
|
|
|
with open(TESTFN, 'rb') as f:
|
|
|
|
cls.FILEDATA = f.read()
|
|
|
|
assert len(cls.FILEDATA) == cls.FILESIZE
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(TESTFN)
|
2018-06-12 18:04:50 -03:00
|
|
|
|
|
|
|
def tearDown(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(TESTFN2)
|
2018-06-12 18:04:50 -03:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def get_files(self):
|
|
|
|
with open(TESTFN, "rb") as src:
|
|
|
|
with open(TESTFN2, "wb") as dst:
|
|
|
|
yield (src, dst)
|
|
|
|
|
|
|
|
def zerocopy_fun(self, *args, **kwargs):
|
|
|
|
raise NotImplementedError("must be implemented in subclass")
|
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
self.tearDown()
|
|
|
|
self.tearDownClass()
|
|
|
|
self.setUpClass()
|
|
|
|
self.setUp()
|
|
|
|
|
|
|
|
# ---
|
|
|
|
|
|
|
|
def test_regular_copy(self):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
self.zerocopy_fun(src, dst)
|
|
|
|
self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
|
|
|
|
# Make sure the fallback function is not called.
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
with unittest.mock.patch('shutil.copyfileobj') as m:
|
|
|
|
shutil.copyfile(TESTFN, TESTFN2)
|
|
|
|
assert not m.called
|
|
|
|
|
|
|
|
def test_same_file(self):
|
|
|
|
self.addCleanup(self.reset)
|
|
|
|
with self.get_files() as (src, dst):
|
2023-07-07 17:42:40 -03:00
|
|
|
with self.assertRaises((OSError, _GiveupOnFastCopy)):
|
2018-06-12 18:04:50 -03:00
|
|
|
self.zerocopy_fun(src, src)
|
|
|
|
# Make sure src file is not corrupted.
|
|
|
|
self.assertEqual(read_file(TESTFN, binary=True), self.FILEDATA)
|
|
|
|
|
|
|
|
def test_non_existent_src(self):
|
2019-11-15 13:49:21 -04:00
|
|
|
name = tempfile.mktemp(dir=os.getcwd())
|
2018-06-12 18:04:50 -03:00
|
|
|
with self.assertRaises(FileNotFoundError) as cm:
|
|
|
|
shutil.copyfile(name, "new")
|
|
|
|
self.assertEqual(cm.exception.filename, name)
|
|
|
|
|
|
|
|
def test_empty_file(self):
|
|
|
|
srcname = TESTFN + 'src'
|
|
|
|
dstname = TESTFN + 'dst'
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(lambda: os_helper.unlink(srcname))
|
|
|
|
self.addCleanup(lambda: os_helper.unlink(dstname))
|
2018-06-12 18:04:50 -03:00
|
|
|
with open(srcname, "wb"):
|
|
|
|
pass
|
|
|
|
|
|
|
|
with open(srcname, "rb") as src:
|
|
|
|
with open(dstname, "wb") as dst:
|
|
|
|
self.zerocopy_fun(src, dst)
|
|
|
|
|
|
|
|
self.assertEqual(read_file(dstname, binary=True), b"")
|
|
|
|
|
|
|
|
def test_unhandled_exception(self):
|
|
|
|
with unittest.mock.patch(self.PATCHPOINT,
|
|
|
|
side_effect=ZeroDivisionError):
|
|
|
|
self.assertRaises(ZeroDivisionError,
|
|
|
|
shutil.copyfile, TESTFN, TESTFN2)
|
|
|
|
|
|
|
|
def test_exception_on_first_call(self):
|
|
|
|
# Emulate a case where the first call to the zero-copy
|
|
|
|
# function raises an exception in which case the function is
|
|
|
|
# supposed to give up immediately.
|
|
|
|
with unittest.mock.patch(self.PATCHPOINT,
|
|
|
|
side_effect=OSError(errno.EINVAL, "yo")):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
with self.assertRaises(_GiveupOnFastCopy):
|
|
|
|
self.zerocopy_fun(src, dst)
|
|
|
|
|
|
|
|
def test_filesystem_full(self):
|
|
|
|
# Emulate a case where filesystem is full and sendfile() fails
|
|
|
|
# on first call.
|
|
|
|
with unittest.mock.patch(self.PATCHPOINT,
|
|
|
|
side_effect=OSError(errno.ENOSPC, "yo")):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
self.assertRaises(OSError, self.zerocopy_fun, src, dst)
|
|
|
|
|
|
|
|
|
|
|
|
@unittest.skipIf(not SUPPORTS_SENDFILE, 'os.sendfile() not supported')
|
|
|
|
class TestZeroCopySendfile(_ZeroCopyFileTest, unittest.TestCase):
|
|
|
|
PATCHPOINT = "os.sendfile"
|
|
|
|
|
|
|
|
def zerocopy_fun(self, fsrc, fdst):
|
|
|
|
return shutil._fastcopy_sendfile(fsrc, fdst)
|
|
|
|
|
|
|
|
def test_non_regular_file_src(self):
|
|
|
|
with io.BytesIO(self.FILEDATA) as src:
|
|
|
|
with open(TESTFN2, "wb") as dst:
|
|
|
|
with self.assertRaises(_GiveupOnFastCopy):
|
|
|
|
self.zerocopy_fun(src, dst)
|
|
|
|
shutil.copyfileobj(src, dst)
|
|
|
|
|
|
|
|
self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
|
|
|
|
|
|
|
|
def test_non_regular_file_dst(self):
|
|
|
|
with open(TESTFN, "rb") as src:
|
|
|
|
with io.BytesIO() as dst:
|
|
|
|
with self.assertRaises(_GiveupOnFastCopy):
|
|
|
|
self.zerocopy_fun(src, dst)
|
|
|
|
shutil.copyfileobj(src, dst)
|
|
|
|
dst.seek(0)
|
|
|
|
self.assertEqual(dst.read(), self.FILEDATA)
|
|
|
|
|
|
|
|
def test_exception_on_second_call(self):
|
|
|
|
def sendfile(*args, **kwargs):
|
|
|
|
if not flag:
|
|
|
|
flag.append(None)
|
|
|
|
return orig_sendfile(*args, **kwargs)
|
|
|
|
else:
|
|
|
|
raise OSError(errno.EBADF, "yo")
|
|
|
|
|
|
|
|
flag = []
|
|
|
|
orig_sendfile = os.sendfile
|
|
|
|
with unittest.mock.patch('os.sendfile', create=True,
|
|
|
|
side_effect=sendfile):
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
with self.assertRaises(OSError) as cm:
|
|
|
|
shutil._fastcopy_sendfile(src, dst)
|
|
|
|
assert flag
|
|
|
|
self.assertEqual(cm.exception.errno, errno.EBADF)
|
|
|
|
|
|
|
|
def test_cant_get_size(self):
|
|
|
|
# Emulate a case where src file size cannot be determined.
|
|
|
|
# Internally bufsize will be set to a small value and
|
|
|
|
# sendfile() will be called repeatedly.
|
|
|
|
with unittest.mock.patch('os.fstat', side_effect=OSError) as m:
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
shutil._fastcopy_sendfile(src, dst)
|
|
|
|
assert m.called
|
|
|
|
self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
|
|
|
|
|
|
|
|
def test_small_chunks(self):
|
|
|
|
# Force internal file size detection to be smaller than the
|
|
|
|
# actual file size. We want to force sendfile() to be called
|
|
|
|
# multiple times, also in order to emulate a src fd which gets
|
|
|
|
# bigger while it is being copied.
|
|
|
|
mock = unittest.mock.Mock()
|
|
|
|
mock.st_size = 65536 + 1
|
|
|
|
with unittest.mock.patch('os.fstat', return_value=mock) as m:
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
shutil._fastcopy_sendfile(src, dst)
|
|
|
|
assert m.called
|
|
|
|
self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
|
|
|
|
|
|
|
|
def test_big_chunk(self):
|
|
|
|
# Force internal file size detection to be +100MB bigger than
|
|
|
|
# the actual file size. Make sure sendfile() does not rely on
|
|
|
|
# file size value except for (maybe) a better throughput /
|
|
|
|
# performance.
|
|
|
|
mock = unittest.mock.Mock()
|
|
|
|
mock.st_size = self.FILESIZE + (100 * 1024 * 1024)
|
|
|
|
with unittest.mock.patch('os.fstat', return_value=mock) as m:
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
shutil._fastcopy_sendfile(src, dst)
|
|
|
|
assert m.called
|
|
|
|
self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
|
|
|
|
|
|
|
|
def test_blocksize_arg(self):
|
|
|
|
with unittest.mock.patch('os.sendfile',
|
|
|
|
side_effect=ZeroDivisionError) as m:
|
|
|
|
self.assertRaises(ZeroDivisionError,
|
|
|
|
shutil.copyfile, TESTFN, TESTFN2)
|
|
|
|
blocksize = m.call_args[0][3]
|
|
|
|
# Make sure file size and the block size arg passed to
|
|
|
|
# sendfile() are the same.
|
|
|
|
self.assertEqual(blocksize, os.path.getsize(TESTFN))
|
|
|
|
# ...unless we're dealing with a small file.
|
2020-06-30 10:46:31 -03:00
|
|
|
os_helper.unlink(TESTFN2)
|
2018-06-12 18:04:50 -03:00
|
|
|
write_file(TESTFN2, b"hello", binary=True)
|
2020-06-30 10:46:31 -03:00
|
|
|
self.addCleanup(os_helper.unlink, TESTFN2 + '3')
|
2018-06-12 18:04:50 -03:00
|
|
|
self.assertRaises(ZeroDivisionError,
|
|
|
|
shutil.copyfile, TESTFN2, TESTFN2 + '3')
|
|
|
|
blocksize = m.call_args[0][3]
|
|
|
|
self.assertEqual(blocksize, 2 ** 23)
|
|
|
|
|
|
|
|
def test_file2file_not_supported(self):
|
|
|
|
# Emulate a case where sendfile() only support file->socket
|
|
|
|
# fds. In such a case copyfile() is supposed to skip the
|
|
|
|
# fast-copy attempt from then on.
|
2019-05-30 03:05:41 -03:00
|
|
|
assert shutil._USE_CP_SENDFILE
|
2018-06-12 18:04:50 -03:00
|
|
|
try:
|
|
|
|
with unittest.mock.patch(
|
|
|
|
self.PATCHPOINT,
|
|
|
|
side_effect=OSError(errno.ENOTSOCK, "yo")) as m:
|
|
|
|
with self.get_files() as (src, dst):
|
|
|
|
with self.assertRaises(_GiveupOnFastCopy):
|
|
|
|
shutil._fastcopy_sendfile(src, dst)
|
|
|
|
assert m.called
|
2019-05-30 03:05:41 -03:00
|
|
|
assert not shutil._USE_CP_SENDFILE
|
2018-06-12 18:04:50 -03:00
|
|
|
|
|
|
|
with unittest.mock.patch(self.PATCHPOINT) as m:
|
|
|
|
shutil.copyfile(TESTFN, TESTFN2)
|
|
|
|
assert not m.called
|
|
|
|
finally:
|
2019-05-30 03:05:41 -03:00
|
|
|
shutil._USE_CP_SENDFILE = True
|
2018-06-12 18:04:50 -03:00
|
|
|
|
|
|
|
|
2018-06-25 21:11:06 -03:00
|
|
|
@unittest.skipIf(not MACOS, 'macOS only')
|
2018-06-19 12:27:29 -03:00
|
|
|
class TestZeroCopyMACOS(_ZeroCopyFileTest, unittest.TestCase):
|
2018-06-12 18:04:50 -03:00
|
|
|
PATCHPOINT = "posix._fcopyfile"
|
|
|
|
|
|
|
|
def zerocopy_fun(self, src, dst):
|
2018-06-19 12:27:29 -03:00
|
|
|
return shutil._fastcopy_fcopyfile(src, dst, posix._COPYFILE_DATA)
|
2018-06-12 18:04:50 -03:00
|
|
|
|
|
|
|
|
2019-09-26 07:15:08 -03:00
|
|
|
class TestGetTerminalSize(unittest.TestCase):
|
2012-02-08 18:28:36 -04:00
|
|
|
def test_does_not_crash(self):
|
|
|
|
"""Check if get_terminal_size() returns a meaningful value.
|
|
|
|
|
|
|
|
There's no easy portable way to actually check the size of the
|
|
|
|
terminal, so let's check if it returns something sensible instead.
|
|
|
|
"""
|
|
|
|
size = shutil.get_terminal_size()
|
2012-02-08 18:48:59 -04:00
|
|
|
self.assertGreaterEqual(size.columns, 0)
|
|
|
|
self.assertGreaterEqual(size.lines, 0)
|
2012-02-08 18:28:36 -04:00
|
|
|
|
|
|
|
def test_os_environ_first(self):
|
|
|
|
"Check if environment variables have precedence"
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2012-02-08 18:28:36 -04:00
|
|
|
env['COLUMNS'] = '777'
|
2016-04-24 03:58:43 -03:00
|
|
|
del env['LINES']
|
2012-02-08 18:28:36 -04:00
|
|
|
size = shutil.get_terminal_size()
|
|
|
|
self.assertEqual(size.columns, 777)
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2016-04-24 03:58:43 -03:00
|
|
|
del env['COLUMNS']
|
2012-02-08 18:28:36 -04:00
|
|
|
env['LINES'] = '888'
|
|
|
|
size = shutil.get_terminal_size()
|
|
|
|
self.assertEqual(size.lines, 888)
|
|
|
|
|
2016-04-24 03:58:43 -03:00
|
|
|
def test_bad_environ(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2016-04-24 03:58:43 -03:00
|
|
|
env['COLUMNS'] = 'xxx'
|
|
|
|
env['LINES'] = 'yyy'
|
|
|
|
size = shutil.get_terminal_size()
|
|
|
|
self.assertGreaterEqual(size.columns, 0)
|
|
|
|
self.assertGreaterEqual(size.lines, 0)
|
|
|
|
|
2012-02-08 18:28:36 -04:00
|
|
|
@unittest.skipUnless(os.isatty(sys.__stdout__.fileno()), "not on tty")
|
2024-02-04 20:04:57 -04:00
|
|
|
@support.requires_subprocess()
|
2016-04-19 17:24:56 -03:00
|
|
|
@unittest.skipUnless(hasattr(os, 'get_terminal_size'),
|
|
|
|
'need os.get_terminal_size()')
|
2012-02-08 18:28:36 -04:00
|
|
|
def test_stty_match(self):
|
|
|
|
"""Check if stty returns the same results ignoring env
|
|
|
|
|
|
|
|
This test will fail if stdin and stdout are connected to
|
|
|
|
different terminals with different sizes. Nevertheless, such
|
|
|
|
situations should be pretty rare.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
size = subprocess.check_output(['stty', 'size']).decode().split()
|
2016-11-14 12:14:42 -04:00
|
|
|
except (FileNotFoundError, PermissionError,
|
|
|
|
subprocess.CalledProcessError):
|
2012-02-08 18:28:36 -04:00
|
|
|
self.skipTest("stty invocation failed")
|
|
|
|
expected = (int(size[1]), int(size[0])) # reversed order
|
|
|
|
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2012-02-08 18:28:36 -04:00
|
|
|
del env['LINES']
|
|
|
|
del env['COLUMNS']
|
|
|
|
actual = shutil.get_terminal_size()
|
|
|
|
|
|
|
|
self.assertEqual(expected, actual)
|
2011-05-06 05:23:04 -03:00
|
|
|
|
2022-06-02 19:44:48 -03:00
|
|
|
@unittest.skipIf(support.is_wasi, "WASI has no /dev/null")
|
2016-04-24 03:58:43 -03:00
|
|
|
def test_fallback(self):
|
2020-06-30 10:46:31 -03:00
|
|
|
with os_helper.EnvironmentVarGuard() as env:
|
2016-04-24 03:58:43 -03:00
|
|
|
del env['LINES']
|
|
|
|
del env['COLUMNS']
|
|
|
|
|
|
|
|
# sys.__stdout__ has no fileno()
|
|
|
|
with support.swap_attr(sys, '__stdout__', None):
|
|
|
|
size = shutil.get_terminal_size(fallback=(10, 20))
|
|
|
|
self.assertEqual(size.columns, 10)
|
|
|
|
self.assertEqual(size.lines, 20)
|
|
|
|
|
|
|
|
# sys.__stdout__ is not a terminal on Unix
|
|
|
|
# or fileno() not in (0, 1, 2) on Windows
|
2021-04-05 01:11:23 -03:00
|
|
|
with open(os.devnull, 'w', encoding='utf-8') as f, \
|
2016-04-24 03:58:43 -03:00
|
|
|
support.swap_attr(sys, '__stdout__', f):
|
|
|
|
size = shutil.get_terminal_size(fallback=(30, 40))
|
|
|
|
self.assertEqual(size.columns, 30)
|
|
|
|
self.assertEqual(size.lines, 40)
|
|
|
|
|
2010-05-05 19:27:31 -03:00
|
|
|
|
2014-11-01 06:04:06 -03:00
|
|
|
class PublicAPITests(unittest.TestCase):
|
|
|
|
"""Ensures that the correct values are exposed in the public API."""
|
|
|
|
|
|
|
|
def test_module_all_attribute(self):
|
|
|
|
self.assertTrue(hasattr(shutil, '__all__'))
|
|
|
|
target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
|
|
|
|
'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
|
2024-08-20 21:39:24 -03:00
|
|
|
'SpecialFileError', 'make_archive',
|
2014-11-01 06:04:06 -03:00
|
|
|
'get_archive_formats', 'register_archive_format',
|
|
|
|
'unregister_archive_format', 'get_unpack_formats',
|
|
|
|
'register_unpack_format', 'unregister_unpack_format',
|
|
|
|
'unpack_archive', 'ignore_patterns', 'chown', 'which',
|
|
|
|
'get_terminal_size', 'SameFileError']
|
|
|
|
if hasattr(os, 'statvfs') or os.name == 'nt':
|
|
|
|
target_api.append('disk_usage')
|
|
|
|
self.assertEqual(set(shutil.__all__), set(target_api))
|
2024-08-20 21:39:24 -03:00
|
|
|
with self.assertWarns(DeprecationWarning):
|
|
|
|
from shutil import ExecError
|
2014-11-01 06:04:06 -03:00
|
|
|
|
|
|
|
|
2003-01-24 13:34:13 -04:00
|
|
|
if __name__ == '__main__':
|
2013-06-12 22:25:59 -03:00
|
|
|
unittest.main()
|