1
0
mirror of https://github.com/arsenetar/send2trash.git synced 2026-03-12 18:51:38 +00:00

6 Commits

Author SHA1 Message Date
2a88b82104 Fix test_plat_other from previous change 2021-08-24 01:21:12 -05:00
18e51c0b5a Minor cleanup in plat_other
- Add OSError code values
- Use INFO_SUFFIX constant in tests
- Remove old PathLike conversions
2021-08-24 01:00:02 -05:00
7686647389 Fix flake8 error 2021-08-21 16:04:05 -05:00
696aed558b Change method for test symlink path generation 2021-08-21 16:00:50 -05:00
007d84361a Fix items missed in test_plat_other in last commit 2021-08-21 15:22:59 -05:00
78a536abba Minor code quality updates 2021-08-21 15:19:32 -05:00
4 changed files with 72 additions and 117 deletions

View File

@@ -37,54 +37,10 @@ class FileOperationProgressSink(DesignatedWrapPolicy):
# but that may need some additional considerations before implementing. # but that may need some additional considerations before implementing.
return 0 if flags & shellcon.TSF_DELETE_RECYCLE_IF_POSSIBLE else 0x80004005 # S_OK, or E_FAIL return 0 if flags & shellcon.TSF_DELETE_RECYCLE_IF_POSSIBLE else 0x80004005 # S_OK, or E_FAIL
def PostDeleteItem(self, flags, item, hrDelete, newlyCreated): def PostDeleteItem(self, flags, item, hr_delete, newly_created):
if newlyCreated: if newly_created:
self.newItem = newlyCreated.GetDisplayName(shellcon.SHGDN_FORPARSING) self.newItem = newly_created.GetDisplayName(shellcon.SHGDN_FORPARSING)
def StartOperations(self):
pass
def FinishOperations(self, Result):
pass
def PreRenameItem(self, Flags, Item, NewName):
pass
def PostRenameItem(self, Flags, Item, NewName, hrRename, NewlyCreated):
pass
def PreMoveItem(self, Flags, Item, DestinationFolder, NewName):
pass
def PostMoveItem(self, Flags, Item, DestinationFolder, NewName, hrMove, NewlyCreated):
pass
def PreCopyItem(self, Flags, Item, DestinationFolder, NewName):
pass
def PostCopyItem(self, Flags, Item, DestinationFolder, NewName, hrCopy, NewlyCreated):
pass
def PreNewItem(self, Flags, DestinationFolder, NewName):
pass
def PostNewItem(
self, Flags, DestinationFolder, NewName, TemplateName, FileAttributes, hrNew, NewItem,
):
pass
def UpdateProgress(self, WorkTotal, WorkSoFar):
pass
def ResetTimer(self):
pass
def PauseTimer(self):
pass
def ResumeTimer(self):
pass
def CreateSink(): def create_sink():
return pythoncom.WrapObject(FileOperationProgressSink(), shell.IID_IFileOperationProgressSink) return pythoncom.WrapObject(FileOperationProgressSink(), shell.IID_IFileOperationProgressSink)

View File

@@ -182,26 +182,23 @@ def send2trash(paths):
path_b = fsencode(path) path_b = fsencode(path)
elif isinstance(path, bytes): elif isinstance(path, bytes):
path_b = path path_b = path
elif hasattr(path, "__fspath__"):
# Python 3.6 PathLike protocol
return send2trash(path.__fspath__())
else: else:
raise TypeError("str, bytes or PathLike expected, not %r" % type(path)) raise TypeError("str, bytes or PathLike expected, not %r" % type(path))
if not op.exists(path_b): if not op.exists(path_b):
raise OSError("File not found: %s" % path) raise OSError(errno.ENOENT, "File not found: %s" % path)
# ...should check whether the user has the necessary permissions to delete # ...should check whether the user has the necessary permissions to delete
# it, before starting the trashing operation itself. [2] # it, before starting the trashing operation itself. [2]
if not os.access(path_b, os.W_OK): if not os.access(path_b, os.W_OK):
raise OSError("Permission denied: %s" % path) raise OSError(errno.EACCES, "Permission denied: %s" % path)
# if the file to be trashed is on the same device as HOMETRASH we
# want to move it there.
path_dev = get_dev(path_b)
path_dev = get_dev(path_b)
# If XDG_DATA_HOME or HOMETRASH do not yet exist we need to stat the # If XDG_DATA_HOME or HOMETRASH do not yet exist we need to stat the
# home directory, and these paths will be created further on if needed. # home directory, and these paths will be created further on if needed.
trash_dev = get_dev(op.expanduser(b"~")) trash_dev = get_dev(op.expanduser(b"~"))
# if the file to be trashed is on the same device as HOMETRASH we
# want to move it there.
if path_dev == trash_dev: if path_dev == trash_dev:
topdir = XDG_DATA_HOME topdir = XDG_DATA_HOME
dest_trash = HOMETRASH_B dest_trash = HOMETRASH_B

View File

@@ -12,7 +12,7 @@ from platform import version
import pythoncom import pythoncom
import pywintypes import pywintypes
from win32com.shell import shell, shellcon from win32com.shell import shell, shellcon
from .IFileOperationProgressSink import CreateSink from .IFileOperationProgressSink import create_sink
def send2trash(paths): def send2trash(paths):
@@ -42,7 +42,7 @@ def send2trash(paths):
# actually try to perform the operation, this section may throw a # actually try to perform the operation, this section may throw a
# pywintypes.com_error which does not seem to create as nice of an # pywintypes.com_error which does not seem to create as nice of an
# error as OSError so wrapping with try to convert # error as OSError so wrapping with try to convert
sink = CreateSink() sink = create_sink()
try: try:
for path in paths: for path in paths:
item = shell.SHCreateItemFromParsingName(path, None, shell.IID_IShellItem) item = shell.SHCreateItemFromParsingName(path, None, shell.IID_IShellItem)

View File

@@ -13,14 +13,16 @@ except ImportError:
# py2 # py2
from ConfigParser import ConfigParser # noqa: F401 from ConfigParser import ConfigParser # noqa: F401
from tempfile import mkdtemp, NamedTemporaryFile, mktemp from tempfile import mkdtemp, NamedTemporaryFile
import shutil import shutil
import stat import stat
import uuid
if sys.platform != "win32": if sys.platform != "win32":
import send2trash.plat_other import send2trash.plat_other
from send2trash.plat_other import send2trash as s2t from send2trash.plat_other import send2trash as s2t
INFO_SUFFIX = send2trash.plat_other.INFO_SUFFIX.decode()
HOMETRASH = send2trash.plat_other.HOMETRASH HOMETRASH = send2trash.plat_other.HOMETRASH
else: else:
pytest.skip("Skipping non-windows tests", allow_module_level=True) pytest.skip("Skipping non-windows tests", allow_module_level=True)
@@ -38,7 +40,7 @@ def testfile():
# Remove trash files if they exist # Remove trash files if they exist
if op.exists(op.join(HOMETRASH, "files", name)): if op.exists(op.join(HOMETRASH, "files", name)):
os.remove(op.join(HOMETRASH, "files", name)) os.remove(op.join(HOMETRASH, "files", name))
os.remove(op.join(HOMETRASH, "info", name + ".trashinfo")) os.remove(op.join(HOMETRASH, "info", name + INFO_SUFFIX))
if op.exists(file.name): if op.exists(file.name):
os.remove(file.name) os.remove(file.name)
@@ -58,7 +60,7 @@ def testfiles():
yield files yield files
filenames = [op.basename(file.name) for file in files] filenames = [op.basename(file.name) for file in files]
[os.remove(op.join(HOMETRASH, "files", filename)) for filename in filenames] [os.remove(op.join(HOMETRASH, "files", filename)) for filename in filenames]
[os.remove(op.join(HOMETRASH, "info", filename + ".trashinfo")) for filename in filenames] [os.remove(op.join(HOMETRASH, "info", filename + INFO_SUFFIX)) for filename in filenames]
def test_trash(testfile): def test_trash(testfile):
@@ -84,52 +86,50 @@ def _filesys_enc():
@pytest.fixture @pytest.fixture
def testUnicodefile(): def gen_unicode_file():
name = u"send2trash_tést1" name = u"send2trash_tést1"
file = op.join(op.expanduser(b"~"), name.encode("utf-8")) file = op.join(op.expanduser(b"~"), name.encode("utf-8"))
touch(file) touch(file)
assert op.exists(file) is True assert op.exists(file) is True
yield file yield file
# Cleanup trash files on supported platforms # Cleanup trash files on supported platforms
if sys.platform != "win32": if sys.platform != "win32" and op.exists(op.join(HOMETRASH, "files", name)):
# Remove trash files if they exist os.remove(op.join(HOMETRASH, "files", name))
if op.exists(op.join(HOMETRASH, "files", name)): os.remove(op.join(HOMETRASH, "info", name + INFO_SUFFIX))
os.remove(op.join(HOMETRASH, "files", name))
os.remove(op.join(HOMETRASH, "info", name + ".trashinfo"))
if op.exists(file): if op.exists(file):
os.remove(file) os.remove(file)
@pytest.mark.skipif(_filesys_enc() == "ascii", reason="Requires Unicode filesystem") @pytest.mark.skipif(_filesys_enc() == "ascii", reason="Requires Unicode filesystem")
def test_trash_bytes(testUnicodefile): def test_trash_bytes(gen_unicode_file):
s2t(testUnicodefile) s2t(gen_unicode_file)
assert not op.exists(testUnicodefile) assert not op.exists(gen_unicode_file)
@pytest.mark.skipif(_filesys_enc() == "ascii", reason="Requires Unicode filesystem") @pytest.mark.skipif(_filesys_enc() == "ascii", reason="Requires Unicode filesystem")
def test_trash_unicode(testUnicodefile): def test_trash_unicode(gen_unicode_file):
s2t(testUnicodefile.decode(sys.getfilesystemencoding())) s2t(gen_unicode_file.decode(sys.getfilesystemencoding()))
assert not op.exists(testUnicodefile) assert not op.exists(gen_unicode_file)
class ExtVol: class ExtVol:
def __init__(self, path): def __init__(self, path):
self.trashTopdir = path self.trash_topdir = path
if PY3: if PY3:
self.trashTopdir_b = os.fsencode(self.trashTopdir) self.trash_topdir_b = os.fsencode(self.trash_topdir)
else: else:
self.trashTopdir_b = self.trashTopdir self.trash_topdir_b = self.trash_topdir
def s_getdev(path): def s_getdev(path):
from send2trash.plat_other import is_parent from send2trash.plat_other import is_parent
st = os.lstat(path) st = os.lstat(path)
if is_parent(self.trashTopdir, path): if is_parent(self.trash_topdir, path):
return "dev" return "dev"
return st.st_dev return st.st_dev
def s_ismount(path): def s_ismount(path):
if op.realpath(path) in (op.realpath(self.trashTopdir), op.realpath(self.trashTopdir_b),): if op.realpath(path) in (op.realpath(self.trash_topdir), op.realpath(self.trash_topdir_b),):
return True return True
return old_ismount(path) return old_ismount(path)
@@ -141,58 +141,60 @@ class ExtVol:
def cleanup(self): def cleanup(self):
send2trash.plat_other.get_dev = self.old_getdev send2trash.plat_other.get_dev = self.old_getdev
send2trash.plat_other.os.path.ismount = self.old_ismount send2trash.plat_other.os.path.ismount = self.old_ismount
shutil.rmtree(self.trashTopdir) shutil.rmtree(self.trash_topdir)
@pytest.fixture @pytest.fixture
def testExtVol(): def gen_ext_vol():
trashTopdir = mkdtemp(prefix="s2t") trash_topdir = mkdtemp(prefix="s2t")
volume = ExtVol(trashTopdir) volume = ExtVol(trash_topdir)
fileName = "test.txt" file_name = "test.txt"
filePath = op.join(volume.trashTopdir, fileName) file_path = op.join(volume.trash_topdir, file_name)
touch(filePath) touch(file_path)
assert op.exists(filePath) is True assert op.exists(file_path) is True
yield volume, fileName, filePath yield volume, file_name, file_path
volume.cleanup() volume.cleanup()
def test_trash_topdir(testExtVol): def test_trash_topdir(gen_ext_vol):
trashDir = op.join(testExtVol[0].trashTopdir, ".Trash") trash_dir = op.join(gen_ext_vol[0].trash_topdir, ".Trash")
os.mkdir(trashDir, 0o777 | stat.S_ISVTX) os.mkdir(trash_dir, 0o777 | stat.S_ISVTX)
s2t(testExtVol[2]) s2t(gen_ext_vol[2])
assert op.exists(testExtVol[2]) is False assert op.exists(gen_ext_vol[2]) is False
assert op.exists(op.join(trashDir, str(os.getuid()), "files", testExtVol[1])) is True assert op.exists(op.join(trash_dir, str(os.getuid()), "files", gen_ext_vol[1])) is True
assert op.exists(op.join(trashDir, str(os.getuid()), "info", testExtVol[1] + ".trashinfo",)) is True assert op.exists(op.join(trash_dir, str(os.getuid()), "info", gen_ext_vol[1] + INFO_SUFFIX,)) is True
# info relative path (if another test is added, with the same fileName/Path, # info relative path (if another test is added, with the same fileName/Path,
# then it gets renamed etc.) # then it gets renamed etc.)
cfg = ConfigParser() cfg = ConfigParser()
cfg.read(op.join(trashDir, str(os.getuid()), "info", testExtVol[1] + ".trashinfo")) cfg.read(op.join(trash_dir, str(os.getuid()), "info", gen_ext_vol[1] + INFO_SUFFIX))
assert (testExtVol[1] == cfg.get("Trash Info", "Path", raw=True)) is True assert (gen_ext_vol[1] == cfg.get("Trash Info", "Path", raw=True)) is True
def test_trash_topdir_fallback(testExtVol): def test_trash_topdir_fallback(gen_ext_vol):
s2t(testExtVol[2]) s2t(gen_ext_vol[2])
assert op.exists(testExtVol[2]) is False assert op.exists(gen_ext_vol[2]) is False
assert op.exists(op.join(testExtVol[0].trashTopdir, ".Trash-" + str(os.getuid()), "files", testExtVol[1],)) is True assert (
op.exists(op.join(gen_ext_vol[0].trash_topdir, ".Trash-" + str(os.getuid()), "files", gen_ext_vol[1],)) is True
)
def test_trash_topdir_failure(testExtVol): def test_trash_topdir_failure(gen_ext_vol):
os.chmod(testExtVol[0].trashTopdir, 0o500) # not writable to induce the exception os.chmod(gen_ext_vol[0].trash_topdir, 0o500) # not writable to induce the exception
pytest.raises(TrashPermissionError, s2t, [testExtVol[2]]) pytest.raises(TrashPermissionError, s2t, [gen_ext_vol[2]])
os.chmod(testExtVol[0].trashTopdir, 0o700) # writable to allow deletion os.chmod(gen_ext_vol[0].trash_topdir, 0o700) # writable to allow deletion
def test_trash_symlink(testExtVol): def test_trash_symlink(gen_ext_vol):
# Use mktemp (race conditioney but no symlink equivalent) # Generating a random uuid named path for symlink
# Since is_parent uses realpath(), and our getdev uses is_parent, sl_dir = op.join(op.expanduser("~"), "s2t_" + str(uuid.uuid4()))
# this should work os.mkdir(op.join(gen_ext_vol[0].trash_topdir, "subdir"), 0o700)
slDir = mktemp(prefix="s2t", dir=op.expanduser("~")) file_path = op.join(gen_ext_vol[0].trash_topdir, "subdir", gen_ext_vol[1])
os.mkdir(op.join(testExtVol[0].trashTopdir, "subdir"), 0o700) touch(file_path)
filePath = op.join(testExtVol[0].trashTopdir, "subdir", testExtVol[1]) os.symlink(op.join(gen_ext_vol[0].trash_topdir, "subdir"), sl_dir)
touch(filePath) s2t(op.join(sl_dir, gen_ext_vol[1]))
os.symlink(op.join(testExtVol[0].trashTopdir, "subdir"), slDir) assert op.exists(file_path) is False
s2t(op.join(slDir, testExtVol[1])) assert (
assert op.exists(filePath) is False op.exists(op.join(gen_ext_vol[0].trash_topdir, ".Trash-" + str(os.getuid()), "files", gen_ext_vol[1],)) is True
assert op.exists(op.join(testExtVol[0].trashTopdir, ".Trash-" + str(os.getuid()), "files", testExtVol[1],)) is True )
os.remove(slDir) os.remove(sl_dir)