我正在尝试为以下功能创建单元测试:
def my_function(path):
#Search files at the given path
for file in os.listdir(path):
if file.endswith(".json"):
#Search for file i'm looking for
if file == "file_im_looking_for.json":
#Open file
os.chdir(path)
json_file=json.load(open(file))
print json_file["name"]
但是,我无法成功创建包含文件的假目录,以使该功能正常工作而不是出现错误。
以下是我目前所拥有的,但它对我不起作用,而且我不确定如何将“file_im_looking_for”合并为假目录中的文件。
tmpfilepath = os.path.join(tempfile.gettempdir(), "tmp-testfile")
@mock.patch('my_module.os')
def test_my_function(self):
# make the file 'exist'
mock_path.endswith.return_value = True
file_im_looking_for=[{
"name": "test_json_file",
"type": "General"
}]
my_module.my_function("tmpfilepath")
感谢任何我出错的建议或解决此问题的其他想法!
最佳答案
首先,您忘记将模拟对象传递给测试函数。在测试中使用 mock 的正确方法应该是这样的。
@mock.patch('my_module.os')
def test_my_function(self, mock_path):
无论如何,您不应该模拟 endswith
,而应该模拟 listdir
。下面的代码片段是一个示例,可能会对您有所帮助。
app.py
def check_files(path):
files = []
for _file in os.listdir(path):
if _file.endswith('.json'):
files.append(_file)
return files
test_app.py
import unittest
import mock
from app import check_files
class TestCheckFile(unittest.TestCase):
@mock.patch('app.os.listdir')
def test_check_file_should_succeed(self, mock_listdir):
mock_listdir.return_value = ['a.json', 'b.json', 'c.json', 'd.txt']
files = check_files('.')
self.assertEqual(3, len(files))
@mock.patch('app.os.listdir')
def test_check_file_should_fail(self, mock_listdir):
mock_listdir.return_value = ['a.json', 'b.json', 'c.json', 'd.txt']
files = check_files('.')
self.assertNotEqual(2, len(files))
if __name__ == '__main__':
unittest.main()
编辑:在评论中回答您的问题,您需要从您的应用中模拟 json.loads
和 open
。
@mock.patch('converter.open')
@mock.patch('converter.json.loads')
@mock.patch('converter.os.listdir')
def test_check_file_load_json_should_succeed(self, mock_listdir, mock_json_loads, mock_open):
mock_listdir.return_value = ['a.json', 'file_im_looking_for.json', 'd.txt']
mock_json_loads.return_value = [{"name": "test_json_file", "type": "General"}]
files = check_files('.')
self.assertEqual(1, len(files))
但请记住!如果您的 API 过于宽泛或难以维护,那么重构您的 API 或许是个好主意。
关于Python:使用用于单元测试的文件创建模拟或假目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37159714/