[英]Unittest - mock os.listdir is not used in testfunction / returns wrong value
我想測試以下 function,但仍然在努力尋找測試 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
function 似乎無法檢索“test.model”文件。 無論如何,它不起作用,我不知道為什么,我也懷疑我解決這個問題的方法是最佳實踐。 誰能告訴我如何解決這個問題?
實際上,您應該修補@mock.patch('os.listdir')
,請參閱where-to-patch 。
此外,我還修補了os.path.isfile()
方法,因為我的真實文件系統上沒有這些目錄文件,所以我將它的返回值模擬為True
。
例如
get_weight_file.py
:
import os
def get_weight_file(path):
only_files = [
file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))
]
print('os.listdir(path): ', os.listdir(path))
model_file = [file for file in only_files if file.endswith(".model")]
return model_file[0]
test_get_weight_file.py
:
from unittest import TestCase, mock
import unittest
from get_weight_file import get_weight_file
class TestGetWeightFile(TestCase):
@mock.patch("os.path.isfile", return_value=True)
@mock.patch("os.listdir", return_value=["test.model", "test.txt", "text.yaml"])
def test_get_weight_file(self, mock_listdir, mock_isfile):
print('mock_isfile: ', mock_isfile.return_value)
print('mock_listdir: ', mock_listdir.return_value)
assert get_weight_file(path="./") == "test.model"
if __name__ == '__main__':
unittest.main()
測試結果:
mock_isfile: True
mock_listdir: ['test.model', 'test.txt', 'text.yaml']
os.listdir(path): ['test.model', 'test.txt', 'text.yaml']
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.