Python中能否在Patch装饰器内使用pytest fixture?
能不能在pytest的@patch装饰器里直接使用fixture?
没办法直接在@patch装饰器的参数里引用fixture。原因很简单:装饰器是在模块加载阶段就执行的,而pytest的fixture要等到测试函数即将运行时才会被实例化注入。你之前写的new=mock.Mock(return_value=data)里的data,在装饰器执行时只是conftest里定义的那个fixture函数本身,根本还没被调用生成实际的返回值,自然没法正常工作。
除了你已经知道的那种在测试函数内设置mock返回值的写法,还有两种常用的替代方式:
使用
pytest-mock提供的mockerfixture(需先安装pytest-mock)def test_fn1(mocker, data): mocker.patch("a.b.c.xyz.get_data", return_value=data) # 测试逻辑...这种写法不用嵌套装饰器,直接在函数里调用patch,此时
data已经被注入,能正常使用。自定义fixture封装patch逻辑
在conftest.py中新增:import pytest from unittest import mock @pytest.fixture def patched_get_data(data): with mock.patch("a.b.c.xyz.get_data", return_value=data) as mock_obj: yield mock_obj测试函数直接使用这个fixture:
def test_fn1(patched_get_data): # 此时get_data已被patch为返回data的mock,直接编写测试逻辑 ...
内容的提问来源于stack exchange,提问作者user762421
相关产品推荐
相关产品推荐

