05-Pytest 配置
5. pytest 常用配置
pytest除了通过命令行参数来控制运行行为时,也可以通过pytest.ini文件来改变其运行规则。
5.1 pytest.ini 配置
通过pytest --help 可以查看配置文件中可以添加的参数和相应的选项,如下所示:
[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
5.2 @pytest.marker 标记
在pytest.ini中设置markers后,在测试方法上面即可以使用这些markers。配置示例如下所示:
[pytest]
markers=Smoke: Run the smoke test function
P1: Highest Prority test function
P2: Medium Prority test function
P3: Lower Prority test function
Regression: Regression test function
在命令行中运行以下命令,可以查看气配置的markers
C:\Users\Surpass\Documents\PyCharmProjects\Pytest\03-codes\Content-05>pytest --markers
@pytest.mark.smoke: Run the smoke test function
@pytest.mark.P1: Highest Prority test function
@pytest.mark.P2: Medium Prority test function
@pytest.mark.P3: Lower Prority test function
@pytest.mark.Regression: Regression test function
测试代码如下所示:
# @IDE: PyCharm
# @Project: PyCharmProjects
# @File: test_pytest_markers_01.py
# @Time 2025-03-14 22:29
# @Author: Surpass Lee
# @E-mail: surpassmebyme@gmail.com
import pytest
@pytest.mark.Smoke
def test_pytest_ini_01():
print("\ntest pytest markers")
@pytest.mark.P1
def test_pytest_ini_02():
print("\ntest pytest markers")
@pytest.mark.P1
@pytest.mark.Regression
def test_pytest_ini_03():
print("\ntest pytest markers")
运行以下命令后结果:
C:\Users\Surpass\Documents\PyCharmProjects\Pytest\03-codes\Content-05>pytest -s -m "P1" --collect-only
collected 3 items / 1 deselected / 2 selected
<Dir Content-05>
<Module test_pytest_markers_01.py>
<Function test_pytest_ini_02>
<Function test_pytest_ini_03>
5.3 设置测试用例路径
testpaths 则指定了pytest去哪里搜索运行测试, testpaths是一系列相对于根目录的路径,用于限定测试用例的搜索范围,只有在pytest未指定文件目录参数或测试用例标识符时,该选项才会启用
[pytest]
testpaths = Content-05
5.4 设置忽略目录
pytest在默认情况,会搜索指定目录及其子目录。如果想跳过某些目录,可以使用norecursedirs选项。
[pytest]
norecursedirs = .* build dist CVS _darcs \{arch\} *.egg
5.5 usefixtures 默认配置
在pytest.ini中配置 usefixtures 的值,如果在使用时与配置值不同,可以通过传递参数来配置值。
[pytest]
usefixtures = login
prefix
如果 usefixtures 后面没有填写相应的fixture,则默认读取配置文件中的默认fixture,且默认值fixture必须存在,否则则出现报错。示例代码如下所示:
# @IDE: PyCharm
# @Project: PyCharmProjects
# @File: test_pytest_markers_02.py
# @Time 2025-03-14 22:43
# @Author: Surpass Lee
# @E-mail: surpassmebyme@gmail.com
import pytest
@pytest.fixture()
def login():
print("\n01:调用login fixture")
@pytest.fixture()
def prefix():
print("\n02:调用prefix fixture")
@pytest.mark.usefixtures()
def test_pytest_ini_01():
print("\n调用默认fixture")
运行结果如下所示:
============================= test session starts =============================
collecting ... collected 1 item
test_pytest_markers_02.py::test_pytest_ini_01
01:调用login fixture
02:调用prefix fixture
PASSED [100%]
调用默认fixture
============================== 1 passed in 0.02s ==============================
5.6 自定义搜索规则
在 pytest 中默认搜索规则是以test/Test开头或结尾的文件、测试方法、测试类,但我们也可以在pytest.ini自定义搜索规则。配置如下所示:
[pytest]
# 搜索测试类
python_classes = *Test Test* *Suite
# 搜索测试文件
python_files = test_* *_test check_*
# 搜索测试方法
python_functions = test_* *_test check_*
5.7 console_output_style 输出样式配置
在运行测试方法时,可以设置控制台输出样式,如下所示:
- classic: 经典style样式输出
- progress: 经典style + 百分比进度条 样式输出,例如:80%
- count: 类似于进度条样式,但进度条是当前执行的测试用例数/总测试用例数,例如:2/100
默认style为progress
配置文件格式如下所示:
[pytest]
console_output_style=count
5.8 禁用xpass
设置xfail_strict = True 可以将那些被标记@pytest.mark.xfail但实际运行通过的测试用例也被报告为测试失败。设置如下所示:
[pytest]
xfail_strict = True
5.9 log相关配置
pytest.ini log相关的配置主要分为运行中日志、日志文件配置等。通过pytest --help 查看结果如下所示:
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
在pytest.ini中,日志配置如下所示:
- log_cli=true:表示启动实时日志
- log_cli_level=INFO: 表示日志INFO以上的信息全部显示
- log_cli_format=%(时间)s[%(日志级别)s]%(信息)s(%(文件名)s:%(行号)s)
- log_cli_date_format=%年-%月-%日 %时:%分:%秒
- log_file=logs/runtime.log
示例配置如下所示:
[pytest]
log_cli = true
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format = %Y-%m-%d %H:%M:%S
log_file = ./runtime.log
5.10 添加执行默认参数
如果某一些选项经常,又不想每次重复输入,这时则可以修改pytest.ini文件的addopts设置,如下所示:
[pytest]
addopts = -rsxX --tb=short --strict
5.11 配置pytest最小版本号
minversion选项可以指定运行测试用例的pytest的最低版本。示例如下所示:
[pytest]
minversion = 8.20
当不满足pytest.ini中配置的最小版本号,会出现如下所示的报错:
pytest.ini: 'minversion' requires pytest-8.20, actual pytest-8.3.5'
5.12 required_plugins
插件必须存在,pytest才能运行此插件,也可以在pytest.ini中进行配置,多个插件之间采用空格进行分隔,其中插件可以,也可以不带版本号,示例配置如下所示:
[pytest]
required_plugins = pytest-html pytest-xdist >= 1.0.l allure-pytest>=2.10.0,<=2.11.0
当不满足要求时,会出现如下所示报错:
ERROR: Missing required plugins: allure-pytest>=2.10.0,<=2.11.0
本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:

作者: Surpassme
来源: http://www.jianshu.com/u/28161b7c9995/
http://www.cnblogs.com/surpassme/
声明:本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出 原文链接 ,否则保留追究法律责任的权利。如有问题,可发送邮件 联系。让我们尊重原创者版权,共同营造良好的IT朋友圈。

浙公网安备 33010602011771号