如何向非测试模块传递自定义pytest命令行参数?
用pytest命令行传参并在非测试模块中使用
直接用sys.argv虽然简单,但pytest会校验命令行参数,直接传自定义参数会触发未知参数报错,而且参数位置容易混乱,更规范的做法是用pytest自带的参数扩展机制:
1. 定义自定义命令行参数
在测试目录下创建conftest.py文件,添加参数定义:
# conftest.py def pytest_addoption(parser): parser.addoption( "--arg", action="store", default="default_value", help="自定义参数,支持传入foo/bar等值" )
2. 封装参数为全局可用的fixture
在conftest.py中添加session级别的fixture,让参数在整个测试会话中都能获取:
# conftest.py import pytest @pytest.fixture(scope="session") def custom_arg(request): return request.config.getoption("--arg")
3. 在测试用例中使用参数
直接在测试函数中注入fixture即可获取参数:
# path/to/test.py def test_func(custom_arg): print(f"测试用例获取到参数: {custom_arg}") # 测试逻辑
4. 在非测试模块中使用参数
方式一:通过测试用例传递参数(推荐)
把参数作为参数传递给非测试模块的函数,耦合度更低:
# 非测试模块 utils.py def process_data(arg_value): print(f"非测试模块使用参数: {arg_value}") # 业务逻辑处理
# 测试用例中调用 from utils import process_data def test_func(custom_arg): process_data(custom_arg)
方式二:全局变量直接获取
如果非测试模块需要独立获取参数,可在conftest.py中初始化全局变量:
# conftest.py custom_arg_value = None def pytest_configure(config): global custom_arg_value custom_arg_value = config.getoption("--arg")
然后在非测试模块中导入使用:
# utils.py from conftest import custom_arg_value def process_data(): print(f"非测试模块直接获取参数: {custom_arg_value}")
运行示例
执行命令:
pytest --arg=foo path/to/test.py::test_func
内容的提问来源于stack exchange,提问作者q30a
相关产品推荐
相关产品推荐

