贝利信息

如何解决 Jenkins 中 pytest 参数化测试被跳过的问题

日期:2025-12-31 00:00 / 作者:霞舞

pytest 在 jenkins 中执行时因测试收集阶段早于资源准备导致参数化函数返回空列表,进而使测试被跳过;本地或手动运行正常是因为工作区残留文件掩盖了问题。核心在于将动态资产发现逻辑移至 pytest 会话启动阶段。

在使用 @pytest.mark.parametrize 进行动态参数化时,pytest 会在测试收集(collection)阶段立即调用参数生成函数(如 get_asset()),而此时测试环境尚未初始化、fixture 尚未执行,且关键外部资源(如测试资产文件)可能还未就位。该问题在 Jenkins 环境中尤为突出,原因在于:

正确做法:推迟资产发现至会话启动阶段

应避免在 parametrize 中直接调用依赖文件系统的函数。推荐使用 pytest_sessionstart 钩子,在 pytest 会话初始化后、测试收集前,预加载资产列表并缓存到全局配置中:

# conftest.py
import pytest
from pathlib import Path
from typing import List

def get_file_list(directory: Path) -> List[Path]:
    return [f for f in directory.rglob("*") if f.is_file()]

def get_asset() -> List[Path]:
    asset_dir = Path(__file__).parent / "asset"
    return [asset for asset in get_file_list(asset_dir) if "need_to_skip_asset" not in str(asset)]

def pytest_sessionstart(session):
    """在测试收集前加载资产列表,并存入 config 对象"""
    try:
        assets = get_asset()
        session.config._assets_cache = assets  # 自定义属性缓存
        print(f"[pytest_sessionstart] Loaded {len(assets)} assets.")
    except Exception as e:
        session.config._assets_cache = []
        print(f"[pytest_sessionstart] Warning: Failed to load assets: {e}")

def pytest_generate_tests(metafunc):
    """动态注入参数:仅当测试函数需要 'asset' 参数且缓存存在时生效"""
    if "asset" in metafunc.fixturenames:
        assets = getattr(metafunc.config, "_assets_cache", [])
        if assets:
            metafunc.parametrize("asset", assets, ids=lambda x: x.name)
        else:
            # 可选:抛出错误而非静默跳过,便于 CI 快速失败
            raise RuntimeError("No test assets found. Check 'asset/' directory existence and permissions.")

同时,更新你的测试函数,移除 @pytest.mark.parametrize 的直接调用,改由 pytest_generate_tests 统一管理:

# test_app.py
def test_app_launch_asset(app_binary, asset):
    """Test Application Function"""
    print(f'Application: {app_binary}')
    print(f'Asset: {asset}')

    applib.execute(
        cmd=[str(app_binary), str(asset)],
        timeout=15,
    )

注意事项与最佳实践

通过将资源准备逻辑上移到 pytest_sessionstart,你确保了所有后续测试收集和执行均基于一致、就绪的上下文——这既是 pytest 插件开发的最佳实践,也是 CI/CD 环境中稳定运行自动化测试的关键保障。