Python py.夹具上的测试补丁

Python py.夹具上的测试补丁,python,mocking,pytest,Python,Mocking,Pytest,我使用以下方法模拟py.test测试的常量值: @patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10) def test_PowerUp(): ... thing = Thing.Thing() assert thing.a == 1 这模拟了测试中使用的延迟时间,以及我所期望的东西中使用的延迟时间 我想对这个文件中的所有测试都这样做,所以我尝试了 @patch('ConstantsModule.Constants

我使用以下方法模拟py.test测试的常量值:

@patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10)
def test_PowerUp():
    ...
    thing = Thing.Thing()
    assert thing.a == 1
这模拟了测试中使用的延迟时间,以及我所期望的东西中使用的延迟时间

我想对这个文件中的所有测试都这样做,所以我尝试了

@patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10)
@pytest.fixture(autouse=True)
def NoDelay():
    pass
但这似乎没有同样的效果


这里有一个类似的问题:,但是模拟似乎是以非装饰的方式完成的。

我想说,通过装饰进行修补并不是最佳的方法。我会使用上下文管理器:

import pytest
from unittest.mock import patch


@pytest.fixture(autouse=True)
def no_delay():
    with patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10):
        yield

这样,在测试拆卸时可以干净地恢复补丁。

pytest通过提供内置补丁支持。因此,要修补文件中所有测试的常数,可以创建以下自动使用夹具:

@pytest.fixture(autouse=True)
def no_delay(monkeypatch):
    monkeypatch.setattr(ConstantsModule.ConstantsClass, 'DELAY_TIME', 10)

如果您不想在测试中导入
ConstantsModule
,您可以使用字符串,请参见。

注意
monkeypatch
是一个函数范围的夹具,因此您的测试将引发
scopemissmatch
。哇,这将教会我没有测试我发布的代码。感谢大家的提醒,我已经纠正了它。我怎样才能在测试用例中将延迟时间传递给这个夹具呢?