【问题标题】:pytest-mock mocker in pytest fixturepytest 夹具中的 pytest-mock mocker
【发布时间】:2023-03-11 10:30:01
【问题描述】:

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

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

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

我也尝试过更改夹具[会话、模块、功能]的范围,以防万一我真的不明白它为什么会失败。

【问题讨论】:

  • 您的示例在 Python 2 和 3 上都适用于我。
  • 您能否提供一些设置的细节以及您是如何运行它的?也许我可以追踪我的环境不起作用的原因。我正在使用 python 3.6(可能应该提到过)无论如何我认为它应该可以工作,并且 github 搜索显示了类似的 patch.object 示例和 pytest-mock 在夹具中,但不适合我。
  • 我使用了您上面显示的文件,并添加了import pytest, uuid。然后用 Python 3.6 和 pytest 3.0.7 运行它。查看您的堆栈跟踪,您实际上并没有运行上面显示的 sn-p。
  • 我想知道它是否与我的 pytest.ini 设置有关,我也在使用覆盖和分析运行它...将启动一个新的环境并尝试一个简单的设置然后继续添加以查看可能出错的地方。

标签: python unit-testing mocking pytest fixtures


【解决方案1】:

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

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

应该是什么时候:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2019-10-23
    • 2020-01-15
    相关资源
    最近更新 更多