如何仅为带自定义marker的pytest测试用例应用fixture?
如何让Fixture仅作用于带自定义Marker的Pytest测试用例
可以通过pytest钩子函数实现这个需求,无需修改现有测试用例结构,自动为带指定marker的测试绑定fixture。
方案:使用pytest_collection_modifyitems钩子
在项目根目录的conftest.py中添加以下代码:
import pytest def pytest_collection_modifyitems(config, items): # 遍历所有收集到的测试用例 for item in items: # 检查当前测试用例是否带有my_marker标记 if item.get_closest_marker("my_marker"): # 为该测试用例添加需要执行的fixture item.fixturenames.append("my_fixture") @pytest.fixture() def my_fixture(): # 这里编写你的fixture逻辑 # fancy fixture stuff pass
你的测试文件保持不变:
import pytest @pytest.mark.my_marker def test_1(): # tests something pass def test_2(): # tests something else pass
效果说明
运行pytest时,test_1因为带有my_marker标记,会自动触发my_fixture的执行;而test_2没有标记,不会执行该fixture。
内容的提问来源于stack exchange,提问作者Nicolas Berthier
相关产品推荐
相关产品推荐

