2
我試圖找出爲什麼我似乎無法在夾具中使用模擬的返回值。 用下面的進口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
希望有人能幫助我理解爲什麼一個可以工作,另一個不會或甚至更好地提供可行的解決方案!
我也試過改變燈具[會議,模塊,功能]的範圍,以防萬一我不明白爲什麼它失敗。
您的示例對我來說工作正常,在Python 2和Python 3上。 –
您能否提供一些關於您的設置的詳細信息以及如何運行它?也許我可以追蹤那些無法工作的環境。我正在使用Python 3.6(概率應該提到) 通過一切手段,我認爲它應該工作和Github搜索顯示patch.object類似的例子pytest模擬在夾具,但不是我。 – ehindy
我用上面顯示的文件,添加了一個'import pytest,uuid'。然後用Python 3.6和pytest 3.0.7運行它。看着你的堆棧跟蹤,你實際上並沒有運行你上面顯示的代碼片斷。 –