基于YAML配置文件实现pytest parametrize及自定义测试ID需求问询
基于YAML配置生成pytest测试参数及自定义测试ID
实现步骤
1. 依赖准备
首先安装pyyaml用于读取YAML配置文件:
pip install pyyaml
2. 解析YAML配置生成测试参数
编写辅助函数加载配置,将每个项目与对应测试板型组合成测试参数,并生成便于筛选的自定义测试ID。
3. 绑定参数到测试函数
使用pytest.mark.parametrize装饰器将参数和ID绑定到目标测试函数,实现参数化测试。
完整代码示例
假设YAML配置文件名为test_config.yaml,内容如下:
Zephyr: projects: - prj_root: "/home/ubuntu/nrf5340_threads" prj_name: "threads" test_input: [] successful_output: ["Toggled led0:", "Toggled led1:"] boards_to_test_on: ["nrf5340", "mps2-an521"] - prj_root: "/home/ubuntu/nrf5340_psa" prj_name: "psa" test_input: ["run"] successful_output: ["encrypted"] boards_to_test_on: ["nrf5340", "mps2-an521" ]
测试代码文件test_projects.py:
import pytest import yaml def load_test_config(config_path): """加载YAML配置,生成测试参数列表和自定义测试ID列表""" with open(config_path, 'r') as config_file: config_data = yaml.safe_load(config_file) test_params = [] test_ids = [] # 遍历每个项目配置 for project in config_data['Zephyr']['projects']: prj_root = project['prj_root'] prj_name = project['prj_name'] test_input = project['test_input'] expected_output = project['successful_output'] # 为每个测试板型生成独立的测试用例 for board in project['boards_to_test_on']: test_params.append((prj_root, board, expected_output, test_input)) # 生成格式为"项目名_板型"的测试ID,方便pytest -k筛选 test_ids.append(f"{prj_name}_{board}") return test_params, test_ids # 加载配置生成参数和ID test_cases, test_case_ids = load_test_config('test_config.yaml') @pytest.mark.parametrize( "prj_root, board_type, successful_output, test_input", test_cases, ids=test_case_ids ) def test_project_run(prj_root, board_type, successful_output, test_input): """项目运行测试的核心逻辑,替换为你的实际测试代码""" # 示例:模拟项目运行并获取输出(实际场景中替换为真实运行逻辑) actual_output = [] # 根据项目路径和输入模拟输出 if "threads" in prj_root and test_input == []: actual_output = ["Toggled led0:", "Toggled led1:"] elif "psa" in prj_root and test_input == ["run"]: actual_output = ["encrypted"] # 验证所有预期输出都存在于实际结果中 for expected in successful_output: assert expected in actual_output, f"预期内容 '{expected}' 未在输出中找到"
使用说明
运行全部测试
pytest test_projects.py -v
筛选指定测试
利用自定义测试ID,通过-k选项精准执行测试:
- 运行
threads项目的所有测试用例:
pytest test_projects.py -v -k "threads"
- 运行
psa项目在nrf5340板上的测试:
pytest test_projects.py -v -k "psa_nrf5340"
- 运行所有针对
mps2-an521板的测试:
pytest test_projects.py -v -k "mps2-an521"
内容的提问来源于stack exchange,提问作者Noam Yulzari
相关产品推荐
相关产品推荐

