You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅为带自定义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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:57:01