简介
pytest.ini是pytest的主配置文件,可以添加配置改变pytest的默认行为,这样不用我们每次执行都在命令行中指定很多参数;
此配置文件通常放到项目根目录下。
配置项
执行pytest -h,查看可用于pytest.ini的配置
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:
markers (linelist): 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.
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)
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.
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_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
render_collapsed (string):
row(s) to render collapsed on open.
max_asset_filename_length (string):
set the maximum filename length for assets attached to the html report.
environment_table_redact_list (linelist):
a list of regexes corresponding to environment table variables whose values should be
redacted from the report
initial_sort (string):
column to initially sort on.
generate_report_on_test (bool):
the HTML report will be generated after each test instead of at the end of the run.
reruns (string): number of times to re-run failed tests. defaults to 0.
reruns_delay (string):
add time (seconds) delay between reruns.
配置文件样例
pytest.ini
[pytest]
# 命令行执行参数
addopts = -vs --strict-markers
# 排除目录
norecursedirs = xxx
# 默认执行目录
testpaths = case
# 执行规则:class
python_classes = Test*
# 执行规则:py文件
python_files = test_* *_test
# 执行规则:function
python_functions = test_*
# 自定义注册标记
markers =
user: 用户模块
order: 订单模块
addopts:命令行参数
pytest命令行运行参数可以写入到pytest.ini中的addopts参数值中,addopts参数几乎支持所有参数,这样避免每一次运行的时候都需要输入参数;
多个参数用空格分隔。
说明:
[pytest]
addopts = -vs --strict-markers
等价于命令行参数:
pytest -vs --strict-markers
等价于main:
if __name__ == "__main__":
pytest.main(["-vs","--strict-markers"])
目录规则
norecursedirs = sub_case
testpaths = case
说明:
1. norecursedirs:配置测试不搜索路径(也就是不访问哪些目录)
2. testpaths:配置测试搜索路径(也就是要访问的目录)
3. 当两者有冲突时,比如二者配置的一样,testpaths优先,也就是执行testpaths下的所有用例
4. testpaths包含norecursedirs,执行testpaths下除了norecursedirs的用例
5. norecursedirs包含testpaths,不执行任何用例,并给出警告
验证:
配置文件
[pytest]
# 命令行执行参数
addopts = -vs --strict-markers
# 排除目录
; norecursedirs = case
norecursedirs = sub_case
# 默认执行目录
testpaths = case
; testpaths = sub_case
# 执行规则:class
python_classes = Test*
# 执行规则:py文件
python_files = test_* *_test
# 执行规则:function
python_functions = test_*
test_qzcsbj.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
import pytest
class Test01:
def test_case2(self):
print("--------------test_case2")
def test_case1(self):
print("--------------test_case1")
test_qzcsbj1.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :
import pytest
class TestCase:
def test_a(self):
print("---test_a")
def test_b(self):
print("---test_b")
test_qzcsbj2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
def test_c():
print("---test_c")
assert 1 == 1
如果配置
验证:
配置文件
[pytest]
# 命令行执行参数
addopts = -vs --strict-markers
# 排除目录
; norecursedirs = case
norecursedirs = sub_case
# 默认执行目录
testpaths = case
; testpaths = sub_case
# 执行规则:class
python_classes = Test*
# 执行规则:py文件
python_files = test_* *_test
# 执行规则:function
python_functions = test_*
test_qzcsbj.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
import pytest
class Test01:
def test_case2(self):
print("--------------test_case2")
def test_case1(self):
print("--------------test_case1")
test_qzcsbj1.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
import pytest
class TestCase:
def test_a(self):
print("---test_a")
def test_b(self):
print("---test_b")
test_qzcsbj2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
def test_c():
print("---test_c")
assert 1 == 1
如果配置
norecursedirs = sub_case
testpaths = case
结果是:执行case下除了sub_case的用例
如果配置
norecursedirs = case
testpaths = case
结果是:执行case下所有用例
如果配置
norecursedirs = case
testpaths = sub_case
结果是:不执行任何用例
执行规则
python_classes = Test*
python_files = test_*.py *_test.py
python_functions = test_* qzcsbj_*
说明:
python_files = test_*.py,表示配置测试搜索的文件名
python_classes = Test*,表示配置测试搜索的类名
python_functions = test_*,表示配置测试搜索的函数名
我们可以修改规则,比如function除了test_开头,还可以qzcsbj_开头,不过,不建议修改。
另外,如果不加通配符,表示执行指定内容,比如python_files = test_qzcsbj.py,表示执行test_qzcsbj.py文件。
xfail:标志规则
设置xfail_strict = true,标记为@pytest.mark.xfail且实际是通过(显示XPASS)的测试用例会被报告为失败FAILED
xfail_strict默认是false,标记为@pytest.mark.xfail的测试用例,如果是通过,显示XPASS
添加配置:
[pytest]
xfail_strict = true
结果:如果通过,显示FAILED
markers:自定义注册标志
测试用例加了@pytest.mark.xxx修饰器(下面示例加在测试类上了),如果配置文件中没有配置markers就会报warnings
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
import pytest
@pytest.fixture(params=['韧', '全栈测试笔记', '性能测试', '自动化测试', '测试开发'])
def fun(request): # 必须是request这个参数名
return request.param # 依次取列表中的每个值返回
@pytest.mark.case
class TestX:
def test_case(self, fun):
print(f"---test_case,data={fun}")
结果:是因为我们给测试方法打的标签,pytest识别不到
解决方案:https://docs.pytest.org/en/stable/how-to/mark.html
加上配置(可以加多个)
[pytest]
markers =
case
后面还可以加上说明
[pytest]
markers =
case: case marker
结果:没有warning了
log-cli:控制台实时输出日志
默认是false,log-cli=false,等价于:log_cli=0
示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
import pytest
@pytest.mark.xfail
class TestX:
def test_case(self):
print(f"---test_case")
assert 1==1
配置0
[pytest]
log_cli=0
结果:
配置1
[pytest]
log_cli=1
结果:展示更细了,可以看到测试类和测试方法
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
import pytest
@pytest.fixture(params=['韧', '全栈测试笔记', '性能测试', '测试开发'])
def fun(request): # 必须是request这个参数名
return request.param # 依次取列表中的每个值返回
class TestX:
def test_case(self, fun):
print(f"---test_case,data={fun}")
结果:用例名unicode编码展示
解决方案是配置文件中加上:
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
结果:中文正常显示
【bak】
__EOF__
本文作者:持之以恒(韧)