我正在努力提高一个shutil.SameFileError
用于单元测试但未能成功。问题是没有引发错误。
import unittest
class TestErrors(unittest.TestCase):
"""Unit testing of errors"""
def test_copy_file(self):
"""Error tests for copy_file"""
with self.assertRaises(shutil.SameFileError):
copy_file_tester(
f"{mpath}{os.sep}tests{os.sep}assets{os.sep}runs{os.sep}{get_fake_project()}{os.sep}i1{os.sep}C.fdf",
f"{mpath}{os.sep}tests{os.sep}assets{os.sep}runs{os.sep}{get_fake_project()}{os.sep}i1{os.sep}C.fdf"
)
代码为copy_file_tester
:
def copy_file_tester(sourcefile, destinationfile):
"""Tester function for copy_file"""
copy_file(sourcefile, destinationfile)
return list(glob.glob(destinationfile))
代码为copy_file
:
def copy_file(sourcefile, destinationfile):
"""Copy and paste a file"""
if not os.path.isfile(sourcefile):
raise FileNotFoundError(f"ERROR: {sourcefile} is not found")
try:
print(f"Copying {sourcefile} to {destinationfile}")
if not os.path.exists(destinationfile):
shutil.copy(sourcefile, destinationfile)
print(f"{sourcefile} is copied to {destinationfile} successfully")
else:
print(f"{destinationfile} exists")
except shutil.SameFileError:
print(f"ERROR: {sourcefile} and {destinationfile} represents the same file")
except PermissionError:
print(f"ERROR: Permission denied while copying {sourcefile} to {destinationfile}")
except (shutil.Error, OSError, IOError) as e:
print(f"ERROR: An error occurred while copying {sourcefile} to {destinationfile} ({e})")
谢谢您的帮助。我用以下方法做到了:
def copy_file(sourcefile, destinationfile):
"""Copy and paste a file"""
if not os.path.isfile(sourcefile):
raise FileNotFoundError(f"ERROR: {sourcefile} is not found")
try:
print(f"Copying {sourcefile} to {destinationfile}")
if not os.path.exists(destinationfile):
shutil.copy(sourcefile, destinationfile)
print(f"{sourcefile} is copied to {destinationfile} successfully")
else:
print(f"{destinationfile} exists")
except shutil.SameFileError as e:
raise shutil.SameFileError(f"ERROR: {sourcefile} and {destinationfile} represents the same file") from e
except PermissionError as e:
raise PermissionError(f"ERROR: Permission denied while copying {sourcefile} to {destinationfile}") from e
except (shutil.Error, OSError, IOError) as e:
raise f"ERROR: An error occurred while copying {sourcefile} to {destinationfile} ({e})" from e
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)