如何基于conftest.py命令行参数实现Pytest测试用例参数化?
解决方案
你的问题核心在于:@pytest.mark.parametrize是在模块加载阶段执行的,这时候pytest还没解析命令行参数,直接引用low和high自然会报错。要实现用命令行参数动态生成测试数据,我们可以借助pytest的pytest_generate_tests钩子函数,它会在测试收集阶段运行(此时命令行参数已解析完成)。
步骤1:调整conftest.py
先保留命令行选项的定义,同时添加可复用的fixture(方便后续在测试中直接引用参数):
#!/usr/bin/env python import pytest def pytest_addoption(parser): # 可以添加默认值避免未传参时报错 parser.addoption("--low", action="store", type=int, default=10, help="起始值") parser.addoption("--high", action="store", type=int, default=20, help="结束值") @pytest.fixture(scope="session") def low(request): return request.config.getoption("--low") @pytest.fixture(scope="session") def high(request): return request.config.getoption("--high")
步骤2:修改test_file.py实现动态参数化
用pytest_generate_tests钩子函数,结合你的自定义generate_data函数生成测试用例:
import pytest def generate_data(low, high): return list(range(low, high)) def pytest_generate_tests(metafunc): # 只给需要`num`参数的测试函数生成数据 if "num" in metafunc.fixturenames: # 从配置中获取命令行传入的low和high low_val = metafunc.config.getoption("--low") high_val = metafunc.config.getoption("--high") # 调用自定义函数生成测试数据 test_data = generate_data(low_val, high_val) # 动态参数化测试用例 metafunc.parametrize("num", test_data) def test_num(num): assert num < 1000
现在执行命令pytest --low=10 --high=100 test_file.py,就会自动生成从10到99的所有测试用例啦。
如何在test_file.py中访问命令行选项?
有两种简单的方式:
方式1:通过fixture直接注入
直接把conftest.py中定义的low和high作为测试函数的参数:
def test_check_range(low, high): # 这里可以直接使用命令行传入的low和high值 assert high > low
方式2:通过request fixture获取config
如果不想依赖自定义fixture,也可以用request fixture拿到配置对象:
def test_direct_config(request): low_val = request.config.getoption("--low") high_val = request.config.getoption("--high") assert high_val - low_val > 0
内容的提问来源于stack exchange,提问作者vinu
相关产品推荐
相关产品推荐

