我使用以下内容来模拟 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模板网!