問題描述
我使用以下內容來模擬 py.test 測試的常量值:
I use the following to mock constant values for a test with py.test:
@patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10)
def test_PowerUp():
...
thing = Thing.Thing()
assert thing.a == 1
這模擬了測試和 Thing 中使用的 DELAY_TIME,這是我所期望的.
This mocks DELAY_TIME as used in both the test, and in Thing, which is what I expected.
我想對這個文件中的所有測試都這樣做,所以我嘗試了
I wanted to do this for all the tests in this file, so I tried
@patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10)
@pytest.fixture(autouse=True)
def NoDelay():
pass
但這似乎沒有同樣的效果.
But that doesn't seem to have the same effect.
這是一個類似的問題:pytest fixture中的pytest-mock mocker,但模擬似乎在那里以非裝飾方式完成.
Here is a similar question: pytest-mock mocker in pytest fixture, but the mock seems done in a non-decorator way there.
推薦答案
我想說通過裝飾器打補丁并不是這里的最佳方法.我會使用上下文管理器:
I'd say patching via decorator is not the optimal approach here. I'd use the context manager:
import pytest
from unittest.mock import patch
@pytest.fixture(autouse=True)
def no_delay():
with patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10):
yield
這樣,補丁在測試拆解時完全恢復.
This way, patching is cleanly reverted on test teardown.
這篇關于夾具上的 py.test 補丁的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!