gpt4 book ai didi

python - py.test fixture 上的补丁

转载 作者:太空狗 更新时间:2023-10-30 00:30:59 25 4
gpt4 key购买 nike

我使用以下代码模拟常量值以使用 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-mock mocker in pytest fixture ,但模拟似乎是以非装饰器的方式完成的。

最佳答案

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

import pytest
from unittest.mock import patch


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

通过这种方式,补丁在测试拆卸时完全恢复。

关于python - py.test fixture 上的补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50048080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com