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

pytest 5.x+升级:如何用命令行标记控制测试执行与跳过

解决方案

在pytest 5.x及以上版本中,全局pytest.config已被移除,模块级代码无法直接访问配置对象。要保留原有装饰器语法并实现命令行标记控制测试执行的效果,可按以下步骤修改:

1. 注册命令行选项(conftest.py)

在项目根目录创建或修改conftest.py,注册--integration命令行参数:

def pytest_addoption(parser):
    parser.addoption(
        "--integration",
        action="store_true",
        default=False,
        help="启用集成测试的执行"
    )

2. 修改common.py中的装饰器

将原有的integration标记改为延迟求值的形式,通过request fixture在测试运行时获取配置:

# common.py
import pytest

def _should_skip_integration(request):
    # 检查命令行是否传入--integration标记
    return not request.config.getoption("--integration")

# 保留原有装饰器名称,避免修改大量测试文件
integration = pytest.mark.skipif(
    _should_skip_integration,
    reason="需添加--integration标记才能执行"
)

3. 测试文件无需修改

你的测试文件写法完全保持不变,依然使用@integration装饰器:

# test_something.py 
from .common import integration 

@integration
def test_mytest():
    assert 1 == 1

@integration
def test_other_mytest():
    assert 2 == 2

运行方式

  • 跳过集成测试(默认行为):直接执行pytest
  • 执行集成测试:执行pytest --integration

原理说明

pytest的skipif标记支持传入可调用对象,该对象会在测试运行阶段被触发,并自动接收request fixture作为参数。通过request.config即可访问命令行参数,实现与原版本完全一致的逻辑,同时规避了全局pytest.config被移除的问题。

内容的提问来源于stack exchange,提问作者Joe Jasinski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:32:41