pytest.ini
是 pytest 的配置文件,用于定义 pytest 的默认行为和自定义规则。除了我们熟知的 addopts
、testpaths
和 markers
,还有多个常用参数可以配置。在实际工作中,使用好这些参数可以大大提升我们的测试效率。
1. 基本配置参数
addopts
-
作用:定义默认的命令行参数,每次运行 pytest 时自动添加这些参数。
-
示例:
[pytest] addopts = -v --tb=short --strict-markers
testpaths
-
作用:指定 pytest 搜索测试文件的目录(默认是当前目录)。
-
示例:
[pytest] testpaths = tests/ unit_tests/
markers
-
作用:注册自定义标记,避免未注册标记的警告。
-
示例:
[pytest] markers = slow: 标记为运行缓慢的测试 smoke: 冒烟测试
2. 测试发现规则
python_files
-
作用:定义 pytest 识别为测试文件的文件名模式(默认是
test_*.py
和*_test.py
)。 -
示例:
[pytest] python_files = check_*.py # 匹配如 check_login.py
python_classes
-
作用:定义 pytest 识别为测试类的类名模式(默认是
Test*
)。 -
示例:
[pytest] python_classes = *Test # 匹配如 LoginTest
python_functions
-
作用:定义 pytest 识别为测试函数的函数名模式(默认是
test_*
)。 -
示例:
[pytest] python_functions = test_* # 默认值,匹配如 test_login()
norecursedirs
-
作用:指定 pytest 忽略的目录(默认忽略
.*
,build
,dist
,node_modules
等)。 -
示例:
[pytest] norecursedirs = .git venv cache
3. 报告与日志
junit_suite_name
-
作用:指定 JUnit XML 报告中的测试套件名称。
-
示例:
[pytest] junit_suite_name = MyTestSuite
log_cli
-
作用:控制是否在控制台实时输出日志(需配合
-s
禁用输出捕获)。 -
示例:
[pytest] log_cli = true # 启用实时日志 log_cli_level = INFO # 设置日志级别
4. 警告处理
filterwarnings
-
作用:过滤 Python 警告(支持
ignore
、error
等操作)。 -
示例:
[pytest] filterwarnings = ignore:.*deprecated.* # 忽略包含 "deprecated" 的警告 error:ResourceWarning # 将 ResourceWarning 转为错误
5. 缓存与插件
cache_dir
-
作用:指定 pytest 缓存目录(默认是
.pytest_cache
)。 -
示例:
[pytest] cache_dir = /tmp/pytest_cache
required_plugins
-
作用:强制要求安装指定的 pytest 插件(未安装时报错)。
-
示例:
[pytest] required_plugins = pytest-html pytest-cov
6. 文档测试(Doctest)
doctest_optionflags
-
作用:配置文档测试的选项(如
NORMALIZE_WHITESPACE
)。 -
示例:
[pytest] doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
7. 其他常用参数
timeout
-
作用:设置单个测试用例的超时时间(需安装
pytest-timeout
)。 -
示例:
[pytest] timeout = 30 # 每个测试最多运行 30 秒
asyncio_mode
-
作用:配置异步测试模式(需安装
pytest-asyncio
)。 -
示例:
[pytest] asyncio_mode = auto
完整示例
[pytest]
# 基本配置
addopts = -v --tb=short
testpaths = tests/
markers =
slow: 标记慢速测试
smoke: 冒烟测试
# 测试发现
python_files = test_*.py
python_classes = *Test
python_functions = test_*
norecursedirs = .git venv
# 报告与日志
junit_suite_name = API_Tests
log_cli = true
log_cli_level = INFO
# 警告处理
filterwarnings =
ignore:.*deprecated.*
# 缓存
cache_dir = .pytest_cache
验证配置
运行以下命令检查配置是否生效:
pytest --help | grep "cachedir" # 查看缓存目录配置 pytest --markers # 查看注册的标记
通过这些配置,可以统一团队测试规范,减少重复命令行输入,提高测试效率。