夹具上的 py.test 补丁 [英] py.test patch on fixture

查看:49
本文介绍了夹具上的 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 补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆