Pytest入门系列之pytest的ini配置文件

Pytest入门系列之pytest的ini配置文件

pytest 的主配置文件,用于:
✅设置默认命令行选项
✅配置测试发现规则
✅定义全局 Fixture 和插件
✅ 管理测试环境参数

基础配置

文件位置与结构

📌 首先需要创建一个ini文件,取名为pytest.ini

1
2
3
4
5
6
# 项目根目录创建 pytest.ini
[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 # 显示最慢的10个测试
--junitxml=reports/junit.xml # 生成JUnit报告
--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 =
# 冒烟测试标记(可通过 -m smoke 选择)
smoke: 冒烟测试(每日执行)
# 数据库测试标记(自动跳过无DB环境)
db: 需要数据库连接的测试
# 性能测试标记(单独执行)
performance: 性能测试(单独执行)
nightly: 夜间执行的长耗时测试
# 自定义重试机制(需配合pytest-rerunfailures插件)
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 # 默认PostgreSQL端口
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
# conftest.py(根据环境加载配置)
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.ini
[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 # 将意外成功的xfail用例标记为失败
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 # 自动检测CPU核心数
dist = loadscope # 按测试模块分发任务
tx = 3 # 每个worker的超时时间(分钟)

分层配置架构

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 可以很高效的提高我们的开发效率和质量


Pytest入门系列之pytest的ini配置文件
https://dreamshao.github.io/2025/03/21/pytest入门系列5/
作者
Yun Shao
发布于
2025年3月21日
许可协议