How to raise a shutil.SameFileError?

205 views Asked by At

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})")
1

There are 1 answers

1
Eftal Gezer On

Thanks for the help. I did it with:

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