pytest学习和使用18-pytest.ini配置文件如何使用?

举报
虫无涯 发表于 2023/03/15 17:54:53 2023/03/15
【摘要】 1 配置文件的作用改变pytest的运行方式;pytest.ini是一个固定的文件;pytest.ini用来读取配置信息。 2 文件格式# 文件名为:pytest.ini[pytest]addopts = xfail_strict = 3 查看pytest.ini的选项使用命令:pytest --help其中pytest.ini选项内容如下:[pytest] ini-options in...

1 配置文件的作用

  • 改变pytest的运行方式;
  • pytest.ini是一个固定的文件;
  • pytest.ini用来读取配置信息。

2 文件格式

# 文件名为:pytest.ini

[pytest]

addopts = 
xfail_strict = 

3 查看pytest.ini的选项

  • 使用命令:
pytest --help
  • 其中pytest.ini选项内容如下:
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg 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 in 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").
  xfail_strict (bool):  default for the strict parameter of xfail markers when not given explicitly (default: False)
  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
  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
  rsyncdirs (pathlist): list of (relative) paths to be rsynced for remote distributed testing.
  rsyncignore (pathlist):
                        list of (relative) glob-style paths to be ignored for rsyncing.
  looponfailroots (pathlist):
                        directories to check for changes

4 存放位置

  • 名称必须为pytest.ini,放置于项目根目录下。

5 常用选项

5.1 marks

  • 以下是使用@pytest.mark.xxx方法:
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/3/15 
# 文件名称:test_ini.py
# 作用:pytest.ini的使用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

import pytest

@pytest.mark.name
def one_name():
    print("name is xiaoming")

@pytest.mark.old
def two_old():
    print("old is 20")

def th_weight():
    print("weight is 50")

@pytest.mark.case
class TestCase:
    def test_case_01(self):
        print("case_01")

    def test_case_02(self):
        print("case_02")


if __name__ == '__main__':
    pytest.main(["-v", "test_ini.py", "-m=case"])

  • 标签多容易出错,可以写入到pytest.ini
# pytest.ini
[pytest]

markers =
    name: run the name
    old: run the old
    case: run the test_case
  • 标记后可使用pytest --markers查看:
(venv) F:\pytest_study\test_case\test_i>pytest --markers
@pytest.mark.name: run the name

@pytest.mark.old: run the old

@pytest.mark.case: run the test_case

@pytest.mark.forked: Always fork for this test.

@pytest.mark.flaky(reruns=1, reruns_delay=0): mark test to re-run up to 'reruns' times. Add a delay of 'rerun
s_delay' seconds between re-runs.

@pytest.mark.repeat(n): run the given test function `n` times.

@pytest.mark.run: specify ordering information for when tests should run in relation to one another. Provided
 by pytest-ordering. See also: http://pytest-ordering.readthedocs.org/

@pytest.mark.no_cover: disable coverage for this test.

@pytest.mark.allure_label: allure label marker

@pytest.mark.allure_link: allure link marker

@pytest.mark.allure_display_name: allure test name marker

@pytest.mark.allure_description: allure description

@pytest.mark.allure_description_html: allure description html

@pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/
stable/warnings.html#pytest-mark-filterwarnings

@pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason="n
o way of currently testing this") skips the test.

@pytest.mark.skipif(condition, ..., *, reason=...): skip the given test function if any of the conditions eva
luate to True. Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. See h
ttps://docs.pytest.org/en/stable/reference.html#pytest-mark-skipif

@pytest.mark.xfail(condition, ..., *, reason=..., run=True, raises=None, strict=xfail_strict): mark the test
function as an expected failure if any of the conditions evaluate to True. Optionally specify a reason for be
tter reporting and run=False if you don't even want to execute the test function. If only specific exception(
s) are expected, you can list them in raises, and if the test fails in other ways, it will be reported as a t
rue failure. See https://docs.pytest.org/en/stable/reference.html#pytest-mark-xfail

@pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different argum
ents in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list
of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to
two calls of the decorated test function, one with arg1=1 and another with arg1=2.see https://docs.pytest.org
/en/stable/parametrize.html for more info and examples.

@pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixture
s. see https://docs.pytest.org/en/stable/fixture.html#usefixtures

@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it
 first/as early as possible.

@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it
last/as late as possible.

5.2 xfail_strict

  • 设置xfail_strict = True可以让那些标记为@pytest.mark.xfail但实际通过显示XPASS的测试用例被报告标记为失败;
  • pytest.ini的写法:
[pytest]

markers =
    name: run the name
    old: run the old
    case: run the test_case

xfail_strict = True
  • 代码为:
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/3/15 
# 文件名称:test_ini01.py
# 作用:pytest.ini的使用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

import pytest

@pytest.mark.name
def test_name():
    print("name is xiaoming")

@pytest.mark.old
def test_old():
    print("old is 20")

@pytest.mark.xfail()
def test_weight():
    a = 30
    b = 60
    assert a != b

@pytest.mark.case
class TestCase:
    def test_case_01(self):
        print("case_01")

    def test_case_02(self):
        print("case_02")


if __name__ == '__main__':
    pytest.main(["-v", "test_ini01.py", "-m=case"])

  • 结果如下,可以看到测试结果为失败:
test_ini01.py::test_name PASSED                                          [ 20%]name is xiaoming

test_ini01.py::test_old PASSED                                           [ 40%]old is 20

test_ini01.py::test_weight FAILED                                        [ 60%]
test_case\test_i\test_ini01.py:18 (test_weight)
[XPASS(strict)] 

test_ini01.py::TestCase::test_case_01 PASSED                             [ 80%]case_01

test_ini01.py::TestCase::test_case_02 PASSED                             [100%]case_02


================================== FAILURES ===================================
_________________________________ test_weight _________________________________
[XPASS(strict)] 
=========================== short test summary info ===========================
FAILED test_ini01.py::test_weight
========================= 1 failed, 4 passed in 0.05s =========================

5.3 addopts

  • addopts参数可以更改默认命令行选项;
  • 比如测试完生成报告,失败重跑3次,一共运行2次,通过分布式去测试:
addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto
  • 把以上命令加入pytest.ini,就不用在命令行重复去写这些参数:
[pytest]

markers =
    name: run the name
    old: run the old
    case: run the test_case

xfail_strict = True

addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto
  • 运行结果:
test_ini01.py::test_old[1-2] 
test_ini01.py::test_old[2-2] 
test_ini01.py::test_weight[1-2] 
test_ini01.py::test_weight[2-2] 
test_ini01.py::test_name[1-2] 
test_ini01.py::TestCase::test_case_01[2-2] 
test_ini01.py::test_name[2-2] 
test_ini01.py::TestCase::test_case_01[1-2] 
[gw3] [ 10%] PASSED test_ini01.py::test_old[2-2] 
[gw6] [ 20%] PASSED test_ini01.py::TestCase::test_case_01[1-2] 
[gw2] [ 30%] PASSED test_ini01.py::test_old[1-2] 
[gw0] [ 40%] PASSED test_ini01.py::test_name[1-2] 
test_ini01.py::TestCase::test_case_02[1-2] 
[gw0] [ 50%] PASSED test_ini01.py::TestCase::test_case_02[1-2] 
[gw1] [ 60%] PASSED test_ini01.py::test_name[2-2] 
test_ini01.py::TestCase::test_case_02[2-2] 
[gw7] [ 70%] PASSED test_ini01.py::TestCase::test_case_01[2-2] 
[gw1] [ 80%] PASSED test_ini01.py::TestCase::test_case_02[2-2] 
[gw5] [ 90%] RERUN test_ini01.py::test_weight[2-2] 
test_ini01.py::test_weight[2-2] 
[gw4] [100%] RERUN test_ini01.py::test_weight[1-2] 
test_ini01.py::test_weight[1-2] 
[gw5] [100%] RERUN test_ini01.py::test_weight[2-2] 
test_ini01.py::test_weight[2-2] 
[gw5] [100%] FAILED test_ini01.py::test_weight[2-2] 
test_case\test_i\test_ini01.py:18 (test_weight[2-2])
[XPASS(strict)] 

[gw4] [100%] RERUN test_ini01.py::test_weight[1-2] 
test_ini01.py::test_weight[1-2] 
[gw4] [100%] FAILED test_ini01.py::test_weight[1-2] 
test_case\test_i\test_ini01.py:18 (test_weight[1-2])
[XPASS(strict)] 


================================== FAILURES ===================================
______________________________ test_weight[2-2] _______________________________
[gw5] win32 -- Python 3.7.0 F:\pytest_study\venv\Scripts\python.exe
[XPASS(strict)] 
______________________________ test_weight[1-2] _______________________________
[gw4] win32 -- Python 3.7.0 F:\pytest_study\venv\Scripts\python.exe
[XPASS(strict)] 
-- generated html file: file://F:\pytest_study\test_case\test_i\reports.html --
=========================== short test summary info ===========================
FAILED test_ini01.py::test_weight[2-2]
FAILED test_ini01.py::test_weight[1-2]
==================== 2 failed, 8 passed, 4 rerun in 3.11s =====================

  • addopts常用参数:
参数 说明
-s 表示输出调试信息,用于显示测试函数中print()打印的信息
-v 未加前只打印模块名,加v后打印类名、模块名、方法名,显示更详细的信息
-q 表示只显示整体测试结果
-vs 这两个参数可以一起使用
-n 支持多线程或者分布式运行测试用例(前提需安装pytest-xdist插件)
-html 生成html的测试报告(前提需安装pytest-html插件) 如:pytest -vs --html ./reports/result.html

5.4 log_cli

  • 控制台实时输出日志;
  • log_cli=TrueFalse(默认);
  • log_cli=True
collecting ... collected 5 items

test_ini01.py::test_name PASSED                                          [ 20%]name is xiaoming

test_ini01.py::test_old PASSED                                           [ 40%]old is 20

test_ini01.py::test_weight FAILED                                        [ 60%]
test_case\test_i\test_ini01.py:18 (test_weight)
[XPASS(strict)] 

test_ini01.py::TestCase::test_case_01 PASSED                             [ 80%]case_01

test_ini01.py::TestCase::test_case_02 PASSED                             [100%]case_02


================================== FAILURES ===================================
_________________________________ test_weight _________________________________
[XPASS(strict)] 
=========================== short test summary info ===========================
FAILED test_ini01.py::test_weight
========================= 1 failed, 4 passed in 0.05s =========================
  • 加了log_cli=True之后,可以清晰看到哪个packagemodule下的用例执行情况。

5.5 norecursedirs

  • pytest 收集测试用例时,会递归遍历所有子目录;
  • 如果有些目录不需要执行,可使用norecursedirs参数简化 pytest 的搜索工作;
  • 方法如下,多个路径用空格隔开:
norecursedirs = .* build dist CVS _darcs {arch} *.egg
  • 比如:
[pytest]

markers =
    name: run the name
    old: run the old
    case: run the test_case

xfail_strict = True

# addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto

log_cli = False
norecursedirs = .* build dist CVS _darcs {arch} *.egg report test_case log

  • 也可以使用norecursedirs修改pytest的默认用例收集规则;
  • 其中默认用例收集规则为:
文件名以 test_*.py 文件和 *_test.py
以test_ 开头的函数
以Test 开头的类,不能包含 __init__ 方法
以test_ 开头的类里面的方法
  • 比如修改为:
[pytest]

python_files = test* test_*  *_test
python_classes = Test*   test*
python_functions = test_*  test*

6 本文涉及的pytest.ini源码

[pytest]

markers =
    name: run the name
    old: run the old
    case: run the test_case

xfail_strict = True

addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto

log_cli = False

norecursedirs = .* build dist CVS _darcs {arch} *.egg report test_case log

python_files = test* test_*  *_test
python_classes = Test*   test*
python_functions = test_*  test*
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。