I want to test the following function, but still struggle with a best practice with testing I/O operations.
def get_weight_file(path: Union[Path, str]) -> str:
"""Finds weights (.model) file in a directory
Parameters
----------
path: Union[Path, str]
Path where to find the weights file
Returns
-------
str
Filename of the weights (.model) file
"""
only_files = [
file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))
]
model_file = [file for file in only_files if file.endswith(".model")]
if len(model_file) == 0:
raise FileNotFoundError("No weights file found in current directory")
if len(model_file) > 1:
raise MultipleFilesError("Please provide a single weights file")
return model_file[0]
I tried to mock os.listdir.
@mock.patch("os.listdir", return_value=["test.model", "test.txt", "text.yaml"])
def test_get_weight_file(listdir):
assert get_weight_file(path="./") == "test.model"
This is the error:
if len(model_file) == 0:
> raise FileNotFoundError("No weights file found in current directory")
E FileNotFoundError: No weights file found in current directory
It seems the function was not able to retreive the "test.model" file. Anyway, it does not work and I don´t know why and I also doubt my way to solve this is best practice. Can anyone hell me how to tackle this?