如何将pytest fixture注入到用于mock第三方库的自定义类中
问题核心原因
@pytest.mark.usefixtures 仅能将fixture注入到被装饰的测试函数、测试类的作用域中,无法自动把fixture参数传递给自定义的Mock类,且直接给patch的new参数传递Mock类时,pytest没有途径将fixture注入到Mock的构造函数中。
方案1:在测试函数内通过偏函数绑定fixture参数
无需修改原有fixture和Mock类定义,直接在测试中预先把fixture参数绑定到Mock的构造函数即可:
from functools import partial def my_test(file): # 测试函数先接收file fixture # 预先给Mock构造函数绑定file参数 MockWithFile = partial(Mock, file=file) with patch("thirdparty.Class", new=MockWithFile): # 测试逻辑 ...
方案2:封装fixture实现复用
如果多个测试都需要使用这个带fixture的Mock类,可以单独封装一个fixture来返回预绑定参数的Mock构造器,避免重复代码:
from functools import partial import pytest @pytest.fixture def patched_mock_class(file): return partial(Mock, file=file)
测试时直接使用该fixture即可:
def my_test(patched_mock_class): with patch("thirdparty.Class", new=patched_mock_class): # 测试逻辑 ...
不推荐通过给Mock类设置类属性传递fixture的方案,多并发测试场景下会出现类属性污染,导致测试结果不符合预期。
内容的提问来源于stack exchange,提问作者Ramon
相关产品推荐
相关产品推荐

