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

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

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

  • Jenkins 默认启用 workspace cleanup:每次构建前清空工作区,确保环境干净;
  • 但 get_asset() 在 collection 阶段执行:此时 'asset' 目录尚不存在或为空 → get_file_list(...) 返回空迭代器 → parametrize 接收空列表 → pytest 将整个测试标记为 skipped(实际是“无参数可生成”,而非显式跳过);
  • 本地/手动运行看似正常:因历史构建残留了 asset/ 目录及文件,get_asset() 能成功返回路径列表,测试得以生成并执行。

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

应避免在 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,
    )

注意事项与最佳实践

  • ? 不要在 conftest.py 顶层或 parametrize 中执行 I/O 操作:collection 阶段无 fixture 上下文,且不可预测环境状态;
  • ? 在 Jenkins 中验证清理行为:添加构建步骤 ls -la asset/ 或 find . -name "asset" -type d -exec ls -la {} \;,确认目录是否真实存在;
  • ⚠️ 权限与路径一致性:确保 Jenkins agent 以正确用户运行,且 CURRENT_MODULE_PATH 在 CI 中解析为预期路径(建议用 Path(__file__).parent 替代);
  • ? 失败即止优于静默跳过:如示例中所示,在 pytest_generate_tests 内对空资产列表抛出 RuntimeError,可让 Jenkins 构建明确失败,避免误判“测试通过”;
  • ? 资产预置更可靠:若资产固定,建议通过 Jenkins Pipeline 的 archiveArtifacts 或 copyArtifact 提前部署,而非依赖运行时发现。

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