let's say I want to create a 'utils' package with several functions working on files and folders. I want to do it once properly so I can use them in all my personal projects without feeling to re invent the wheel each time. I also want to learn 2 items by the way:
- exception handling, already read a lot about EAFP vs LBYL, I think the following function suits well to EAFP.
- unit tests with pytest tool, it seems simple enough to start with.
My function is:
def removeanything(src): """ remove files or folders """ try: os.remove(src) print('File is removed') except IsADirectoryError: shutil.rmtree(src) print('Folder is removed') except FileNotFoundError: print('File/folder is not existing') except PermissionError: print('Not allowed to suppress this file')
Do you have any comment to do regarding my exception handling? Did I forget one or more exceptions?
To go ahead, I have written this test function for pytest:
from pathlib import Path import utils #import pytest def test_removeanything(tmp_path): d = tmp_path / '.tmp_dir' d.mkdir() f = d / '.tmp_file' f.touch() # Test permission d.chmod(mode=0o555) utils.removeanything(f) assert Path.exists(f) # Test file deletion d.chmod(mode=0o777) utils.removeanything(f) assert not Path.exists(f) # Test folder deletion utils.removeanything(d) assert not Path.exists(d)
As I am pretty newbie at testing, I would like to know if I include all reasonable things to assert for my function? Are there other way to do it more properly? Is there a way to assert if expected error has been indeed raised by my function?