Using pytest.ini for Global Pytest Configuration
This guide explains how to create, locate, and populate a pytest.ini file with common configuration options, provides a complete example, and outlines best practices for using the file to streamline and standardize test execution in Python projects.
pytest.ini is the global configuration file for Pytest, allowing you to customize test runner behavior and rules, avoid repetitive command‑line arguments, and improve testing efficiency and consistency.
1. Location and format The file is typically placed in the project root directory and starts with a [pytest] header followed by specific configuration items.
2. Common configuration items
配置项 说明
addopts 添加默认的命令行选项。例如:addopts = -v -s --html=report.html。
testpaths 指定测试用例的查找路径。例如:testpaths = tests。
python_files 指定测试文件的匹配模式。默认为 test_*.py。
python_classes 指定测试类的匹配模式。默认为 Test*。
python_functions 指定测试函数的匹配模式。默认为 test_*。
markers 定义测试用例的标记(marker)。例如:markers = smoke: smoke test。
norecursedirs 指定不递归搜索的目录。例如:norecursedirs = venv build。
xfail_strict 设置 xfail 标记的行为。如果设置为 True,则标记为 xfail 的测试用例在通过时会被报告为失败。3. Example configuration file
# 添加默认命令行选项
addopts = -v -s --html=report.html
# 指定测试用例的查找路径
testpaths = tests
# 定义测试文件、类和函数的匹配模式
python_files = test_*.py
python_classes = Test*
python_functions = test_*
# 定义测试标记
markers =
smoke: smoke test
integration: integration test
# 设置不递归搜索的目录
norecursedirs = venv build
# 设置 xfail 标记的行为
xfail_strict = True4. Usage Create the file in the project root, edit it to add or modify options as needed, then run pytest ; Pytest will automatically read the configurations.
5. Notes Paths and patterns support relative paths and wildcards; command‑line arguments can override file settings; the file must be saved with ANSI encoding (e.g., using Notepad++).
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.