【发布时间】:2016-11-04 17:06:49
【问题描述】:
出于测试目的,我想模拟 shutil.which (Python 3.5.1),它在简化方法 find_foo() 中调用
def _find_foo(self) -> Path:
foo_exe = which('foo', path=None)
if foo_exe:
return Path(foo_exe)
else:
return None
我正在使用 pytest 来实现我的测试用例。因此,我也想使用 pytest 扩展 pytest-mock。在下面,我使用 pytest + pytest-mock 粘贴了一个示例测试用例:
def test_find_foo(mocker):
mocker.patch('shutil.which', return_value = '/path/foo.exe')
foo_path = find_foo()
assert foo_path is '/path/foo.exe'
这种用 pytest-mock 模拟的方式是行不通的。 shutil.which 仍然被调用而不是 mock。
我尝试直接使用现在是 Python3 一部分的 mock 包:
def test_find_foo():
with unittest.mock.patch('shutil.which') as patched_which:
patched_which.return_value = '/path/foo.exe'
foo_path = find_foo()
assert foo_path is '/path/foo.exe'
遗憾的是结果是一样的。还调用 shutil.which() 而不是指定的模拟。
在我的测试用例中成功实现模拟的哪些步骤是错误的或遗漏的?
【问题讨论】:
标签: python unit-testing mocking pytest