py.test patch on fixture(夹具上的 py.test 补丁)
问题描述
我使用以下内容来模拟 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 补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:夹具上的 py.test 补丁
基础教程推荐
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
