我试图找出为什么我似乎不能在fixture中使用模拟返回值。使用以下导入
import pytest
import uuidpytest-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'以上测试通过。然而,由于我将在许多测试用例中使用它,我认为我可以只使用一个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'以上操作失败,输出如下:
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希望有人能帮助我理解为什么一个可以工作,而另一个不能,或者更好地提供一个有效的解决方案!
我还尝试更改了fixturesession、module、function的作用域,以防我真的不理解它失败的原因。
发布于 2017-04-13 12:32:01
所以找到了罪魁祸首,这真的很愚蠢,我实际上重新输入了上面的例子,而不是复制和粘贴,所以我的原始代码有一个问题。在我的固定装置中,我输入了:
mock_uuid.return_value(uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f'))当它本应该是:
mock_uuid.return_value = uuid.UUID(hex='5ecd5827b6ef4067b5ac3ceac07dde9f')这是我在我的例子中,因此它是工作在others...so许多小时lost...Feeling相当愚蠢,但我希望这可以帮助在未来的人…
https://stackoverflow.com/questions/43358802
复制相似问题