pytest夹具中的pytest-mock嘲笑者 [英] pytest-mock mocker in pytest fixture
问题描述
我正试图找出为什么我似乎无法在灯具中使用模拟返回值的原因. 带有以下进口
I'm trying to find out why I don't seem to be able to use a mocked return value in a fixture. With the following imports
import pytest
import uuid
有效的pytest-mock示例:
pytest-mock example that works:
def test_mockers(mocker):
mock_uuid = mocker.patch.object(uuid, 'uuid4', autospec=True)
mock_uuid.return_value = uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f')
# this would return a different value if this wasn't the case
assert uuid.uuid4().hex == '5ecd5827b6ef4067b5ac3ceac07dde9f'
以上测试通过. 但是,由于我将在许多测试用例中使用它,所以我认为我可以使用固定装置:
The above test passes. However as I will be using this in many test cases I thought I could just use a fixture:
@pytest.fixture
def mocked_uuid(mocker):
mock_uuid = mocker.patch.object(uuid, 'uuid4', autospec=True)
mock_uuid.return_value = uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f')
return mock_uuid
def test_mockers(mocked_uuid):
# this would return a different value if this wasn't the case
assert uuid.uuid4().hex == '5ecd5827b6ef4067b5ac3ceac07dde9f'
以上操作失败,并显示以下输出:
The above fails with the following output:
FAILED
phidgetrest\tests\test_taskscheduler_scheduler.py:62 (test_mockers)
mocked_uuid = <function uuid4 at 0x0000029738C5B2F0>
def test_mockers(mocked_uuid):
# this would return a different value if this wasn't the case
> assert uuid.uuid4().hex == '5ecd5827b6ef4067b5ac3ceac07dde9f'
E AssertionError: assert <MagicMock name='uuid4().hex' id='2848515660208'> == '5ecd5827b6ef4067b5ac3ceac07dde9f'
E + where <MagicMock name='uuid4().hex' id='2848515660208'> = <MagicMock name='uuid4()' id='2848515746896'>.hex
E + where <MagicMock name='uuid4()' id='2848515746896'> = <function uuid4 at 0x0000029738C5B2F0>()
E + where <function uuid4 at 0x0000029738C5B2F0> = uuid.uuid4
tests\test_taskscheduler_scheduler.py:65: AssertionError
希望有人可以帮助我理解为什么一个可行而另一个却不可行,甚至更好地提供了可行的解决方案!
Hoping someone can help me understand why one works and the other doesn't or even better provide a solution that works!
我还尝试更改了夹具的范围[会话,模块,功能],以防万一我真的不明白为什么它会失败.
I've also tried changing the scope of the fixture[session, module, function], just in case as I don't really understand why it's failing.
推荐答案
因此找到了罪魁祸首,这确实很愚蠢,我实际上重新键入了上面的示例,而不是复制并粘贴,因此我的原始代码出现了问题.在我的装置中,我输入了:
So found the culprit and it was really silly, I actually retyped the examples above rather then copy and paste so my original code has an issue. In my fixture I had typed:
mock_uuid.return_value(uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f'))
应该在什么时候出现:
mock_uuid.return_value = uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f')
在我的示例中,它正在为其他人工作...浪费了很多时间...感觉相当愚蠢,但是我希望这对以后的某个人有帮助...
which I had in my example, hence it was working for others...so many hours lost...Feeling rather silly, however I hope this may help someone in the future...
这篇关于pytest夹具中的pytest-mock嘲笑者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!