概述
pytest.ini
是pytest
测试框架的一个可选配置文件,用于定义全局的pytest
设置和参数。它位于项目的根目录下,并且文件名是固定的,不能更改。
不管是主函数模式运行,命令行模式运行,
pytest
会自动在项目目录及其父目录中查找这个文件,并应用其中的配置。
用途
pytest.ini
文件的主要用途是简化测试配置并提供跨多个项目或环境的一致性。通过这个文件,用户可以定义默认的命令行参数、设置插件、定义环境变量等,从而定制
pytest
的行为。这样,在运行测试时,用户无需每次都手动指定这些配置选项,使测试脚本更加简洁和可维护。
配置内容
执行
pytest -h
查看可用于pytest.ini
的所有配置项,内容如下:
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:
markers (linelist): Register new markers for test functions
empty_parameter_set_mark (string):
Default marker for empty parametersets
norecursedirs (args): Directory patterns to avoid for recursion
testpaths (args): Directories to search for tests when no files or directories are given on the command line
filterwarnings (linelist):
Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.
consider_namespace_packages (bool):
Consider namespace packages when resolving module names during import
usefixtures (args): List of default fixtures to be used with this project
python_files (args): Glob-style file patterns for Python test module discovery
python_classes (args):
Prefixes or glob names for Python test class discovery
python_functions (args):
Prefixes or glob names for Python test function and method discovery
disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
Disable string escape non-ASCII characters, might cause unwanted side effects(use at your own risk)
console_output_style (string):
Console output: "classic", or with additional progress information ("progress" (percentage) | "count" |
"progress-even-when-capture-no" (forces progress even when capture=no)
verbosity_test_cases (string):
Specify a verbosity level for test case execution, overriding the main level. Higher levels will provide
more detailed information about each test case executed.
xfail_strict (bool): Default for the strict parameter of xfail markers when not given explicitly (default: False)
tmp_path_retention_count (string):
How many sessions should we keep the `tmp_path` directories, according to `tmp_path_retention_policy`.
tmp_path_retention_policy (string):
Controls which directories created by the `tmp_path` fixture are kept around, based on test outcome.
(all/failed/none)
enable_assertion_pass_hook (bool):
Enables the pytest_assertion_pass hook. Make sure to delete any previously generated pyc cache files.
verbosity_assertions (string):
Specify a verbosity level for assertions, overriding the main level. Higher levels will provide more
detailed explanation when an assertion fails.
junit_suite_name (string):
Test suite name for JUnit report
junit_logging (string):
Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|all
junit_log_passing_tests (bool):
Capture log information for passing tests to JUnit report:
junit_duration_report (string):
Duration time to report: one of total|call
junit_family (string):
Emit XML for schema: one of legacy|xunit1|xunit2
doctest_optionflags (args):
Option flags for doctests
doctest_encoding (string):
Encoding used for doctest files
cache_dir (string): Cache directory path
log_level (string): Default value for --log-level
log_format (string): Default value for --log-format
log_date_format (string):
Default value for --log-date-format
log_cli (bool): Enable log display during test run (also known as "live logging")
log_cli_level (string):
Default value for --log-cli-level
log_cli_format (string):
Default value for --log-cli-format
log_cli_date_format (string):
Default value for --log-cli-date-format
log_file (string): Default value for --log-file
log_file_mode (string):
Default value for --log-file-mode
log_file_level (string):
Default value for --log-file-level
log_file_format (string):
Default value for --log-file-format
log_file_date_format (string):
Default value for --log-file-date-format
log_auto_indent (string):
Default value for --log-auto-indent
pythonpath (paths): Add paths to sys.path
faulthandler_timeout (string):
Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish
addopts (args): Extra command line options
minversion (string): Minimally required pytest version
required_plugins (args):
Plugins that must be present for pytest to run
pytest -h
返回内容很多,可配置项从这里开始看虽然,我们看到它支持很多参数的配置 ,但其实真正用到的并不多
pytest.ini文件中可以包含以下类型的配置:
命令行选项:通过
addopts
选项,用户可以为pytest
命令行工具提供默认参数。插件配置:使用
plugins
选项,用户可以指定要加载的pytest
插件。这允许用户启用额外的功能或集成其他测试工具。环境变量:在
pytest.ini
文件中,用户可以定义环境变量,这些变量可以在测试代码中通过标准的环境变量访问机制获取。测试发现:用户可以通过配置选项,如
norecursedirs
和testpaths
,来定制pytest
如何发现测试。日志和其他设置:
pytest.ini
还允许用户配置日志行为、修改测试报告格式等。
配置文件示例
是否发现
pytest.ini
配置文件的后缀?没错,它的后缀是
ini
,属于标准配置文件的一种;INI配置文件由节、键、值组成
- 节点 [section]
[节点名称],中括号不可省略
- 选项/参数 name=value
键=值
- 注释 注释使用分号或井号表示
;/#
# 添加默认的命令行选项
[pytest]
addopts = -v --maxfail=2 --tb=short --color=yes --strict-markers
# 这些选项将应用于所有测试文件
# -v: 启用详细模式,显示更多输出信息
# --maxfail=2: 当有2个或更多的测试失败时,停止测试
# --tb=short: 使用简短的回溯信息,使输出更简洁
# --color=yes: 启用彩色输出
# --strict-markers: 严格检查测试函数和钩子函数的标记
# 指定pytest应该搜索测试文件的路径
# 可以是相对路径或绝对路径
testpaths = tests/ unit_tests/ integration_tests/
# 忽略递归查找测试时的目录
norecursedirs = docs/ build/ dist/ .git/ logs/ tmp/
# 修改默认的测试模块文件名规则
# 默认是 test_*.py 或 *_test.py
python_files = test_*.py my_tests_*.py
# 修改默认的测试类名称规则
# 默认是 Test*
python_classes = MyTest*
# 修改默认的测试用例函数名称规则
# 默认是 test_*
python_functions = my_test_*
# 你也可以同时指定多个模式,用空格分隔
# python_functions = my_test_* another_test_*
addopts 配置
addopts
参数可以更改默认的命令行选项;这个参数在我们需要在命令行中输入大一堆指令来执行测试用例时会用到,这个时候就可以配置文件中配置这个参数来代替,省掉很多重复的工作。
更多命令,请回顾
Pytest(03)命令行选项和用例查找规则
推文
参数 | 作用 |
---|---|
-s | 表示输出调试信息,用于显示测试函数中print()打印的信息 |
-v | 未加前只打印模块名,加v后打印类名、模块名、方法名,显示更详细的信息 |
-q | 表示只显示整体测试结果 |
-vs | 这两个参数可以一起使用 |
-n | 支持多线程或者分布式运行测试用例(前提需安装:pytest-xdist插件) |
–html | 生成html的测试报告(前提需安装:pytest-html插件) 如:pytest -vs --html ./reports/result.html |
-x | 表示只要有一个测试用例报错,则执行停止 |
-k | 模糊匹配,测试用例的部分字符串,指定执行测试用例。 |
-m | mark标记 |
收集用例规则配置
在
pytest.ini
配置文件中,testpaths
和norecursedirs
这两个配置项可以影响测试文件的收集过程,但它们的作用和优先级略有不同。testpaths:
testpaths
配置项用于指定pytest
在哪些目录中查找测试文件。- 示例:如果
testpaths = case
,那么 pytest 将只在case
目录下开始搜索符合测试文件命名模式的文件(默认,以test_
开头或以_test
结尾的文件)。norecursedirs:
norecursedirs
配置项用于指定一组目录名或正则表达式,pytest 在递归查找测试文件时将忽略这些目录。- 示例:如果
norecursedirs = sub_case
,那么 pytest 在递归搜索时将忽略所有名为sub_case
的目录。python_file:
python_files
配置项用于指定 pytest 在搜索测试模块时应该匹配的文件名模式。- 默认情况下,pytest 会查找所有以
test_
开头或以_test
结尾的 Python 文件作为测试模块。- 示例:
python_files = test_\*.py my_tests_*.py
表示pytest
将搜索所有以test_
开头并以.py
结尾的文件,以及所有以my_tests_
开头并以.py
结尾的文件作为测试模块。python_classes:
python_classes
配置项用于指定 pytest 在搜索测试类时应该匹配的类名模式。- 默认情况下,
pytest
会查找所有以Test
开头的类作为测试类。- 示例:
python_classes = MyTest*
表示 pytest 将搜索所有以MyTest
开头的类作为测试类。python_functions:
python_functions
配置项用于指定 pytest 在搜索测试用例函数时应该匹配的函数名模式。- 默认情况下,
pytest
会查找所有以test_
开头的函数作为测试用例。- 示例:
python_functions = my_test_*
表示pytest
将搜索所有以my_test_
开头的函数作为测试用例。
收集用例规则演示
pytest.ini
配置文件
[pytest]
# 命令行执行参数
addopts = -vs --strict-markers
# 排除目录
; norecursedirs = testcase
norecursedirs = sub_testcase
# 默认执行目录
testpaths = testcase
; testpaths = sub_case
# 执行规则:class
python_classes = Sub* Root*
# 执行规则:py文件
python_files = sub_* root_*
# 执行规则:function
python_functions = test_*
testcase/root_test_case_01.py
文件代码
class RootTestClass1:
def test_case1(self):
print("---> root_test_case_01.py -> test_case1")
def test_case2(self):
print("---> root_test_case_01.py -> test_case2")
testcase/root_test_case_02.py
文件代码
class RootTestClass2:
def test_case3(self):
print("---> root_test_case_02.py -> test_case3")
def test_case4(self):
print("---> root_test_case_02.py -> test_case4")
testcase/sub_testcase/sub_test_case_01.py
文件代码
class SubTestClass1:
def test_a(self):
print("---> sub_test_case_01.py -> test_a")
def test_b(self):
print("---> sub_test_case_01.py -> test_b")
test/sub_testcase/sub_test_case_02.py
文件代码
class SubTestClass2:
def test_c(self):
print("---> sub_test_case_02.py -> test_c")
def test_d(self):
print("---> sub_test_case_02.py -> test_d")
测试排除指定目录中的用例
pytest.ini
文件中修改如下
# 排除sub_testcase目录中的测试用例收集
norecursedirs = sub_testcase
# 默认执行testcase目录中的测试用例收集
testpaths = testcase
执行结果
验证排除和收集目录重叠
实际开发中,肯定不会且没人这么干,这里突发奇想试一下
pytest.ini
文件中修改如下:
# 排除testcase目录中的测试用例收集
norecursedirs = testcase
# 默认执行testcase目录中的测试用例收集
testpaths = testcase
执行效果
验证排除目录是收集目录的父级
实际开发中,肯定不会且没人这么干,这里突发奇想试一下
pytest.ini
文件中修改如下:
# 排除testcase目录中的测试用例收集
norecursedirs = testcase
# 默认执行testcase目录中的测试用例收集
testpaths = testcase
执行效果