我想使用 unittest 测试一种使用上下文管理器从文件中读取的方法:
with open(k_file, 'r') as content_file:
content = content_file.read()
我不想在我的系统上创建一个文件,所以我想模拟它,但目前我并没有取得多大成功。我发现了模拟打开 http://www.voidspace.org.uk/python/mock/helpers.html#mock-open但我真的不明白我应该如何使用它并在测试用例中将模拟作为 content_file 提供。例如有这样的post https://stackoverflow.com/a/19663055/914086在这里,但我不明白如何在不修改原始代码的情况下在测试用例中编写此代码。
有人能指出我正确的方向吗?
mock_open()
是要走的路;你打补丁open
在您的测试代码中,结果为mock_open()
call:
mocked_open = unittest.mock.mock_open(read_data='file contents\nas needed\n')
with unittest.mock.patch('yourmodule.open', mocked_open, create=True):
# tests calling your code; the open function will use the mocked_open object
The patch()上下文管理器 http://www.voidspace.org.uk/python/mock/patch.html#patch会放一个open()
全局进入你的模块(我将其命名为yourmodule
),绑定到mocked_open()
- 产生的对象。该对象在调用时会假装生成一个文件对象。
这个模拟文件对象唯一的东西won'tdo Yet 是迭代;你不能做for line in content_file
有了它,至少在当前版本中没有mock
图书馆。看自定义unittest.mock.mock_open进行迭代 https://stackoverflow.com/questions/24779893/customizing-unittest-mock-mock-open-for-iteration解决方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)