【发布时间】:2022-01-14 13:51:51
【问题描述】:
我想测试以下函数,但仍然在努力寻找测试 I/O 操作的最佳实践。
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]
我试图模拟 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"
这是错误:
if len(model_file) == 0:
> raise FileNotFoundError("No weights file found in current directory")
E FileNotFoundError: No weights file found in current directory
该函数似乎无法检索“test.model”文件。 无论如何,它不起作用,我不知道为什么,我也怀疑我解决这个问题的方法是最佳实践。谁能告诉我如何解决这个问题?
【问题讨论】:
-
如果你的函数在模块
foo中,而你的测试在不同的模块中,那么你需要修补foo.os.listdir。
标签: python unit-testing python-unittest python-unittest.mock