在fixtu上测试补丁

2024-10-03 11:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下方法模拟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

但这似乎没有同样的效果。

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


Tags: 方法pytesttimepytestdeffixturepatch
2条回答

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

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

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

我认为通过decorator进行修补并不是这里的最佳方法。我会使用上下文管理器:

import pytest
from unittest.mock import patch


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

这样,在测试拆卸时,修补将被完全恢复。

相关问题 更多 >