【发布时间】:2016-05-11 10:20:15
【问题描述】:
我正在尝试为以下函数创建单元测试:
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”作为文件合并到 fake 目录中。
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")
感谢任何我出错的建议或解决此问题的其他想法!
【问题讨论】:
标签: python unit-testing mocking