如何为基于YAML的自定义PyTest测试用例添加Fixtures?
如何为pytest自定义测试用例添加Fixture支持
可行性结论
完全可行,pytest允许自定义测试Item类通过request对象或声明fixturenames属性来使用fixture。
具体实现步骤
1. 定义Fixture
在conftest.py中添加你的fixture:
import pytest import yaml @pytest.fixture def evaluate_condition(): return eval # 原有的pytest_collect_file、YamlFile类保持不变
2. 修改自定义TestCase类
有两种常用方式实现fixture注入:
方式一:通过request对象获取fixture(推荐,灵活度高)
修改TestCase类的runtest方法,利用pytest自动注入的self.request对象获取fixture:
class TestCase(pytest.Item): def __init__(self, *, condition, **kwargs): super().__init__(**kwargs) self.condition = condition def runtest(self): # 通过request.getfixturevalue获取指定fixture evaluate_func = self.request.getfixturevalue("evaluate_condition") assert evaluate_func(self.condition)
方式二:声明fixturenames属性
通过fixturenames属性声明当前Item需要的fixture,pytest会自动将fixture实例绑定到Item对象上:
class TestCase(pytest.Item): # 声明需要使用的fixture名称列表 fixturenames = ["evaluate_condition"] def __init__(self, *, condition, **kwargs): super().__init__(**kwargs) self.condition = condition def runtest(self): # 直接通过属性访问fixture实例 assert self.evaluate_condition(self.condition)
验证运行
修改完成后,执行原测试命令:
$ pytest --no-header stackoverflow.yaml -v
测试会正常执行,且evaluate_condition fixture已被正确使用。
内容的提问来源于stack exchange,提问作者Berthin
相关产品推荐
相关产品推荐

