pytest夹具中的pytest-mock mocker
问题描述:
我试图找出为什么我似乎无法在夹具中使用模拟的返回值。 用下面的进口pytest夹具中的pytest-mock mocker
import pytest
import uuid
pytest-模拟例子的工作原理:
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
希望有人能帮助我理解为什么一个可以工作,另一个不会或甚至更好地提供可行的解决方案!
我也试过改变灯具[会议,模块,功能]的范围,以防万一我不明白为什么它失败。
答
所以找到了罪魁祸首,它真的很愚蠢,我实际上重新键入上面的例子,而不是复制和粘贴,所以我原来的代码有问题。在我的夹具我输入了:
mock_uuid.return_value(uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f'))
当它应该是:
mock_uuid.return_value = uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f')
,我曾在我的例子,因此它是给别人打工......失去了这么多小时......感觉很愚蠢,但是我希望这可以帮助未来的人...
您的示例对我来说工作正常,在Python 2和Python 3上。 –
您能否提供一些关于您的设置的详细信息以及如何运行它?也许我可以追踪那些无法工作的环境。我正在使用Python 3.6(概率应该提到) 通过一切手段,我认为它应该工作和Github搜索显示patch.object类似的例子pytest模拟在夹具,但不是我。 – ehindy
我用上面显示的文件,添加了一个'import pytest,uuid'。然后用Python 3.6和pytest 3.0.7运行它。看着你的堆栈跟踪,你实际上并没有运行你上面显示的代码片断。 –