I am trying to raise a shutil.SameFileError for unit testing but could not succeed. The problem is the error is not raised.
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"
)
The code for copy_file_tester:
def copy_file_tester(sourcefile, destinationfile):
"""Tester function for copy_file"""
copy_file(sourcefile, destinationfile)
return list(glob.glob(destinationfile))
The code for 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})")
Thanks for the help. I did it with: