如何用Pytest Parameterize From file Library多.yml文件并行执行单测试脚本
使用pytest-parameterize-from-file加载多YAML配置文件并实现并行执行
环境准备
- 安装依赖包:
pip install pytest pytest-parameterize-from-file pytest-xdist
项目结构
建议将配置文件集中存放,示例结构:
your_project/ ├── tests/ │ └── test_stage.py └── configs/ ├── test_01_stage.yml ├── test_02_stage.yml └── test_03_stage.yml
实现多配置文件参数化
方法1:手动遍历配置文件实现参数化
直接收集所有YAML文件路径,通过@pytest.mark.parametrize传入测试函数:
import pytest from parameterize_from_file import load_yaml import os CONFIG_DIR = "../configs" # 获取目录下所有.yml文件 config_files = [ os.path.join(CONFIG_DIR, f) for f in os.listdir(CONFIG_DIR) if f.endswith(".yml") ] @pytest.mark.parametrize("config_path", config_files) def test_stage(config_path): # 加载当前配置文件的测试数据 test_data = load_yaml(config_path) # 替换为你的测试逻辑 assert test_data["expected_output"] == your_test_func(test_data["input_params"])
方法2:用钩子函数动态生成测试用例
适合需要对配置数据做预处理的场景,通过pytest_generate_tests动态生成参数化用例:
import pytest from parameterize_from_file import load_yaml import os CONFIG_DIR = "../configs" def pytest_generate_tests(metafunc): # 仅对包含test_data参数的测试函数生效 if "test_data" not in metafunc.fixturenames: return all_test_cases = [] config_files = [f for f in os.listdir(CONFIG_DIR) if f.endswith(".yml")] for file_name in config_files: file_path = os.path.join(CONFIG_DIR, file_name) case_data = load_yaml(file_path) # 为用例添加配置文件标识,方便排查问题 case_data["config_source"] = file_name all_test_cases.append(case_data) # 参数化测试用例 metafunc.parametrize("test_data", all_test_cases) def test_stage(test_data): print(f"执行测试用例,来源配置文件:{test_data['config_source']}") # 测试逻辑 assert test_data["expected"] == run_test(test_data["params"])
并行执行配置
使用pytest-xdist实现多进程并行测试:
- 运行命令(指定进程数):
# 使用4个进程并行执行 pytest tests/test_stage.py -n 4 - 自动匹配CPU核心数:
pytest tests/test_stage.py -n auto
注意事项
- 确保测试用例之间无状态依赖,避免并行时出现数据冲突。
- 如果配置文件涉及共享资源(如数据库、文件),需添加隔离机制(如独立测试环境、临时文件)。
内容的提问来源于stack exchange,提问作者Dinesh
相关产品推荐
相关产品推荐

