1

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?

Data Mastery
  • 1,555
  • 4
  • 18
  • 60
  • You need to patch `os.remove` also. – Florin C. Nov 27 '21 at 08:05
  • @FlorinC. ok thank you, that helped me a bit, but now how do I check the expected output? – Data Mastery Nov 27 '21 at 08:27
  • If the goal of your function is to delete some files, you assert that your mock was called. Check this answer for a simple example: https://stackoverflow.com/questions/3829742/assert-that-a-method-was-called-in-a-python-unit-test – Florin C. Nov 27 '21 at 08:30

0 Answers0