Pytest入门系列之pytest的ini配置文件
pytest
的主配置文件,用于:
✅设置默认命令行选项
✅配置测试发现规则
✅定义全局 Fixture
和插件
✅ 管理测试环境参数
基础配置
文件位置与结构
📌 首先需要创建一个ini
文件,取名为pytest.ini
1 2 3 4 5 6
| [pytest]
addopts = -v --tb=short testpaths = tests python_files = test_*.py
|
🔍 验证配置生效:
1
| pytest --help | grep "config file"
|
核心配置项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| [pytest]
""" -ra 显示所有测试结果摘要 -q 精简输出模式 --durations=10 --junitxml=reports/junit.xml --color=yes 启用终端信息的彩色输出 """ addopts = -ra -q --durations=10 --junitxml=reports/junit.xml --color=yes
python_files = test_*.py python_classes = Test* *Test python_functions = test_*
testpaths = tests/login tests/team
norecursedirs = .git build dist legacy_*
filterwarnings = ignore:.*deprecated.*:DeprecationWarning error
|
中级配置
自定义标记
1 2 3 4 5 6 7 8 9 10 11
| [pytest] markers = smoke: 冒烟测试(每日执行) db: 需要数据库连接的测试 performance: 性能测试(单独执行) nightly: 夜间执行的长耗时测试 flaky(reruns=2, reruns_delay=1): 不稳定的测试用例
|
🔹 示例:
1 2 3 4 5 6 7 8 9 10 11
| @pytest.mark.smoke def test_login(): """核心登录功能测试""" assert auth.login() == 200
@pytest.mark.db def test_user_query(): """数据库用户查询测试""" assert db.query_user(1) is not None
|
日志系统集成
1 2 3 4 5 6 7 8
| [pytest] log_level = DEBUG log_cli = true log_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)" log_date_format = "%Y-%m-%d %H:%M:%S" log_file = logs/pytest.log log_file_level = INFO
|
测试数据隔离
1 2 3 4 5 6
| [pytest]
db_host = localhost db_port = 5432 db_name = test_db db_timeout = 5
|
🔹 示例: 使用示例(conftest.py
)
1 2 3 4 5 6 7 8 9
| @pytest.fixture(scope="session") def database(pytestconfig): """创建数据库连接的全局 Fixture""" return psycopg2.connect( host=pytestconfig.getini("db_host"), port=pytestconfig.getini("db_port"), database=pytestconfig.getini("db_name"), connect_timeout=pytestconfig.getini("db_timeout") )
|
高级配置 (企业级实践)
动态配置生成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| def pytest_configure(config): """根据命令行参数动态修改配置""" env = config.getoption("--env") if env == "prod": config.inicfg["db_host"] = "prod-db.example.com" config.inicfg["db_name"] = "prod_db"
def pytest_addoption(parser): """添加自定义命令行参数""" parser.addoption( "--env", action="store", default="dev", choices=["dev", "staging", "prod"], help="设置运行环境" )
|
多环境配置方案
1 2 3 4 5
| [pytest] env_files = config/env_dev.ini config/env_prod.ini
|
🔹 示例:环境配置文件示例 (config/env_prod.ini
):
1 2 3 4 5
| [db] host = prod-db.example.com port = 5432 user = prod_user password = ${DB_PASSWORD}
|
安全配置规范
1 2 3 4 5 6 7 8
| [pytest] xfail_strict = true filterwarnings = error ignore::DeprecationWarning ignore:.*Unexpected kwargs.*:UserWarning
|
效能优化
缓存配置优化
1 2 3 4
| [pytest] cache_dir = .pytest_cache enable_caching = true cache_show = true
|
并行测试配置
1 2 3 4
| [pytest] addopts = -n auto dist = loadscope tx = 3
|
分层配置架构
1 2 3 4 5 6 7 8 9 10
| project/ ├── pytest.ini # 全局基础配置 ├── conftest.py # 全局Fixtures和hooks ├── config/ │ ├── env_dev.ini # 开发环境参数 │ └── env_prod.ini # 生产环境参数 └── tests/ ├── conftest.py # 测试目录级配置 └── api/ └── conftest.py # API测试专用配置
|
调试与验证
配置验证命令
1 2 3 4 5 6 7 8 9
| pytest --version
pytest --check-config
PYTEST_DEBUG=1 pytest -rA
|
配置覆盖示例
1 2 3 4 5 6
| pytest -o "log_cli=false" -o "log_file=debug.log"
pytest -o "testpaths=tests/unit"
|
完整配置实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| [pytest]
addopts = -v -ra --strict-markers --tb=short testpaths = tests python_files = test_*.py python_classes = Test* *Test python_functions = test_*
markers = smoke: 核心功能验证 db: 需要数据库连接 api: 外部API调用测试
env_files = config/env.ini
log_cli = true log_level = INFO log_format = "%(asctime)s [%(levelname)s] %(message)s" log_file = reports/pytest.log
filterwarnings = error xfail_strict = true
|
📌 配置文件需保存为 UTF-8 编码,避免中文乱码问题。
总结
pytest.ini
可以很高效的提高我们的开发效率和质量