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

查看:83
本文介绍了夹具上的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夹具中的pytest-mock模拟程序 ,但该模拟似乎是通过非装饰器的方式完成的.

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天全站免登陆