如何创建支持全局配置的pytest Mock身份验证服务fixture插件?
为pytest认证fixture添加全局配置的几种实用方案
下面是几种能让你的插件用户一次性全局设置认证参数的方法,都是pytest生态里常用的实践:
1. 命令行选项+配置文件兜底
通过pytest_addoption扩展命令行参数,同时支持在pytest.ini里配置默认值,兼顾灵活性和易用性。
在你的包的conftest.py中添加:
import pytest def pytest_addoption(parser): # 注册全局配置参数 parser.addoption( "--auth-username", default="test_user", help="认证服务全局用户名" ) parser.addoption( "--auth-password", default="test_pass", help="认证服务全局密码" ) parser.addoption( "--auth-endpoint", default="http://mock-auth.local", help="认证服务全局端点地址" ) @pytest.fixture(scope="session") def mock_auth_service(request): # 从命令行或配置文件读取参数 auth_config = { "username": request.config.getoption("--auth-username"), "password": request.config.getoption("--auth-password"), "endpoint": request.config.getoption("--auth-endpoint"), } # 初始化你的模拟认证服务 mock_service = MockAuthService(**auth_config) yield mock_service # 可选:测试结束后的清理逻辑 mock_service.shutdown()
用户使用时,可以直接通过命令行传参:
pytest --auth-username=prod_user --auth-password=prod_123 --auth-endpoint=https://auth.example.com
也可以在项目根目录的pytest.ini里写好默认值,不用每次输命令行:
[pytest] addopts = --auth-username=default_user --auth-password=default_pass --auth-endpoint=http://local-auth:8080
2. 自定义配置文件
如果用户需要更复杂的多环境配置(比如区分测试/预发/生产),可以让他们用YAML/JSON文件管理参数,fixture自动读取。
修改conftest.py:
import pytest import yaml from pathlib import Path def pytest_addoption(parser): parser.addoption( "--auth-config", default="auth_config.yaml", help="认证服务配置文件路径" ) @pytest.fixture(scope="session") def mock_auth_service(request): config_path = request.config.getoption("--auth-config") config_file = Path(config_path) # 读取配置文件,不存在则用默认值 if config_file.exists(): with open(config_file, "r") as f: auth_config = yaml.safe_load(f) else: auth_config = { "username": "test_user", "password": "test_pass", "endpoint": "http://mock-auth.local" } mock_service = MockAuthService(**auth_config) yield mock_service mock_service.shutdown()
用户的auth_config.yaml示例:
username: staging_user password: staging_456 endpoint: https://auth.staging.example.com
3. 环境变量读取
适合CI/CD流水线场景,直接读取系统环境变量,不用额外传参:
import pytest import os @pytest.fixture(scope="session") def mock_auth_service(): auth_config = { "username": os.getenv("AUTH_USERNAME", "test_user"), "password": os.getenv("AUTH_PASSWORD", "test_pass"), "endpoint": os.getenv("AUTH_ENDPOINT", "http://mock-auth.local"), } mock_service = MockAuthService(**auth_config) yield mock_service mock_service.shutdown()
用户只需提前设置环境变量即可:
export AUTH_USERNAME=ci_user && export AUTH_PASSWORD=ci_789 && pytest
可选进阶:参数优先级
如果想让用户有最大灵活性,可以组合多种方式,按优先级取值:命令行参数 > 环境变量 > 配置文件 > 默认值,这样用户可以根据场景选择最方便的配置方式。
内容的提问来源于stack exchange,提问作者Martin Thoma
相关产品推荐
相关产品推荐

