我正在将一些代码从 Python 2 移植到 3,而 py.test
不能很好地与来自 unittest.mock< 的
。当我使用 patch
装饰器一起玩patch
装饰器将模拟传递给测试函数的参数时,py.test
反而将该参数解释为固定装置,并且无法设置测试。
这里有一个人为的例子,希望能说明问题:
@patch('my_module.my_func')
def test_my_func(mock_func):
mock_func()
mock_func.assert_called_once_with()
运行 py.test
后,错误消息如下所示:
E fixture 'my_func' not found
> available fixtures: cache, capfd, capsys, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory
> use 'pytest --fixtures [testpath]' for help on them.
这是发生此故障的唯一情况。如果我显式调用测试(即运行 test_my_func()
),没有错误。如果我使用其他任何一种修补技术修补 my_func
,都不会出错。如果我从 mock
而不是 unittest.mock
导入补丁,没有错误。
只有在使用 py.test
运行我的测试时,使用 unittest.mock
,并在发生这种情况时使用装饰器进行修补。
我正在运行 Python 3.4.5。
最佳答案
是的,不支持模拟装饰器。
这还不错——通过装饰器更改函数签名被认为是个坏主意。
但是您仍然可以使用 with mock.patch(...)
语法。
还有一个选项是 pytest-mock带有非常干净的 api 的插件,用于模拟:
def test_foo(mocker):
# all valid calls
mocker.patch('os.remove')
mocker.patch.object(os, 'listdir', autospec=True)
mocked_isfile = mocker.patch('os.path.isfile')
关于python - Pytest 适用于旧模拟,但不适用于 unittest.mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169563/