pytest fixture 中的 pytest-mock 嘲笑者

pytest-mock mocker in pytest fixture

我试图找出为什么我似乎无法在夹具中使用模拟的 return 值。 使用以下导入

import pytest
import uuid

有效的 pytest-mock 示例:

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'

以上测试通过。 然而,由于我将在许多测试用例中使用它,我认为我可以只使用一个夹具:

@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'

以上操作失败,输出如下:

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

希望有人能帮助我理解为什么一个有效而另一个无效,或者更好地提供一个有效的解决方案!

我也尝试过更改 fixture[session、module、function] 的范围,以防万一我真的不明白为什么会失败。

所以找到了罪魁祸首,这真的很愚蠢,我实际上重新输入了上面的示例,而不是复制和粘贴,所以我的原始代码有问题。在我的装置中,我输入了:

mock_uuid.return_value(uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f'))

应该是什么时候:

mock_uuid.return_value = uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f')

我在我的示例中使用了它,因此它对其他人有用...浪费了很多时间...感觉很傻,但是我希望这可以帮助将来的人...