繁体   English   中英

夹具上的py.test补丁

[英]py.test patch on fixture

我使用以下命令来模拟py.test测试的常量值:

@patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10)
def test_PowerUp():
    ...
    thing = Thing.Thing()
    assert thing.a == 1

这样可以在测试和Thing中使用DELAY_TIME,这是我的预期。

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

@patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10)
@pytest.fixture(autouse=True)
def NoDelay():
    pass

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

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

我会说通过装饰器修补不是这里的最佳方法。 我使用上下文管理器:

import pytest
from unittest.mock import patch


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

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

pytest通过monkeypatch fixture提供内置的补丁支持。 因此,要修复文件中所有测试的常量,您可以创建以下autouse fixture:

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

如果您不想在测试中导入ConstantsModule ,则可以使用字符串,请参阅完整的API参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM