I have the following function I want to test:
def rmdir_and_files_with_exceptions(folder: str, exceptions: "list[str]") -> None:
"""[removes subfolders and files of a given folder
with a list as parameter to prevent deletion]
Args:
folder (str): [folder where subfolders should be removed in]
exceptions (list[str]): [list with folders NOT to delete]
"""
for dir_or_file in os.listdir(folder):
if os.path.isdir(f"{folder}/{dir_or_file}"):
if dir_or_file not in exceptions:
shutil.rmtree(f"{folder}/{dir_or_file}")
else:
if dir_or_file not in exceptions:
os.remove(f"{folder}/{dir_or_file}")
I try to mock a directory structure like this with mock
from unittest
:
def test_rmdir_and_files_with_exceptions():
with mock.patch('os.listdir') as mocked_listdir, \
mock.patch('os.remove') as mocked_listdir:
mocked_listdir.return_value = ['alpha', 'beta', 'xyz']
rmdir_and_files_with_exceptions(".", exceptions=["alpha"])
assert len(mocked_listdir) == 2
AssertionError: assert 0 == 2
Can anyone help me how to setup this correctly?