ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

pytest系列——配置文件pytest.ini

2022-08-04 18:01:22  阅读:151  来源: 互联网

标签:log 配置文件 -- pytest ini test string


前言

pytest.ini文件是pytest的主配置文件;可以改变pytest的运行方式;它是一个固定的文件pytest.ini文件,读取配置信息,按指定的方式去运行。

pytest.ini文件的位置一般放在项目的根目录下,不能随便放,也不能更改名字。

查看pytest.ini文件的配置选项

cmd下执行 pytest -h 或者 pytest --help 可以查看配置选项,找到如下内容:

[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
  render_collapsed (bool):
                        Open the report with all rows collapsed. Useful for very large reports
  max_asset_filename_length (string):
                        set the maximum filename length for assets attached to the html report.
  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

常用的配置选项

markers

作用:测试用例中使用@pytest.mark.slow装饰器,如果不添加markers选项就会报warning

格式:list列表类型

写法:

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

举例:

①当使用 @pytest.mark. 标记名称时,如果使用的自定义标记,当在执行测试用例追加命令行参数 -m= 标记名称时,虽然不会影响测试执行,但是在执行后会出现告警提示。

image

②此时可以在 pytest.ini 配置文件中增加 markers 字段注册标记名称。【将自定义的标签注册,注册后pytest可以识别出来后就不会报出警告信息】

[pytest]
# 注册标记名称
markers =
    smoke: 冒烟测试用例
    normal: 正常用例

③添加后字段注册标记名称后,使用 pytest --markers 命令行参数运行可以查看到添加的标记名称。

image

④再次执行用例:运行结果在控制台没有告警提示

image

【注意】:在自定义标签的的同时应该尽量避免使用如下关键字:【pytest测试框架的内置标签,可以直接使用,不需要重新在pytest.ini文件中注册】
usefixturesusefixturesskipskipifxfailparametrize

xfail_strict

作用:设置xfail_strict=true可以让那边标记为@pytest.mark.xfail 但实际通过显示为XPASS 的测试用例被报告为失败。

格式:True、False(默认)、1、0

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict = true

举例:

# file_name: test_xfail.py

import pytest


class Test_C:

    @pytest.mark.xfail
    def test_c(self):
        print('\n------------------> test_c has ran')
        a = 'hello'
        b = 'hello world'
        assert a != b


if __name__ == '__main__':
    pytest.main(['-s', 'test_xfail.py'])

没有设置xfail_strict = True 时,测试结果显示XPASS

image

设置xfail_strict = True 时,测试结果显示failed

image

addopts

作用:addopts参数可以更改默认的命令行选项;这个参数在我们需要在命令行中输入大一堆指令来执行测试用例时会用到,这个时候就可以配置文件中配置这个参数来代替,省掉很多重复的工作

例如:我想在测试结束之后,生成测试报告,失败的测试用例重跑两次,如果通过命令行输入指令来执行的话,指令会很长: pytest -v --reruns 2 --html=report.html --self-contained-html

如果每次执行都要输入上面的指令会很繁琐,这个时候我们通过配置addopts参数来解决这个问题:

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict = True

addopts = -v --reruns=2 --html=report.html --self-contained-html  # 多个命令行参数用空格分隔开,可以添加多个命令行参数

这样加上addopts后,我们再次进入cmd命令行执行时,只要输入pytest就可以默认带上这些参数了。

log_cli

作用:控制台实时输出日志

格式: log_cli=Truelog_cli=False(默认),或者 log_cli=1log_cli=0

①设置 log_cli=True 时,运行结果为:

image

② 设置 log_cli=False时,运行结果为:

image

结论:

当我们设置 log_cli=True时,在控制台使用命令行参数运行测试用例时可以看到程序里写入的日志;可以非常清晰的看出具体的是哪个package下的哪个module下的哪个测试用例是passed还是failed;

所以我们平时在调试代码是否有问题时推荐加上 log_cli=True ,当测试用例调试通过之后批量执行时就可以去掉了。
image

norecursedirs

①norecursedirs作用:pytest在收集测试用例的时候,会递归遍历当前目录下的所有子目录,当我们需要某些目录下的用例不要执行时,就可以通过设置norecursedirs参数来实现这个功能。

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict = True

addopts = -v --reruns=2 --html=report.html --self-contained-html

log_cli = False

norecursedirs = venv report util log  # 多个目录需要空格分开,可以配置多个

上面的配置表示venv report util log这4个目录下的用例需要过滤掉不执行。

②pytest之命令行参数 --ignore 用法

文件目录结构如下:

├── demo
 ├── all
  │ ├── a_a_test
  │ │ └── test_1.py
  │ ├── b_a_test
  │ │ └── test_2.py
  │ └── c
  │ └── test_2.py

1、忽略 c 文件夹下的脚本:

# demo.py

pytest --ignore=all/c 

# c后面不要有/,也不要写成c/*

# 注意,多个目录忽略,加多个--ignore即可,中间用空格做间隔。

2、忽略某一类脚本:

# demo.py

pytest --ignore-glob='*_a_test'  #  glob模糊匹配文件夹

# 会忽略a_a_test 和 b_a_test 目录下的脚本

3、实例:可以作为pytest命令行参数之一集成至pytest.ini文件中的addopts参数中,与上述案例的效果相同

image

更改测试用例的收集规则

pytest默认的测试用例收集规则为:

  • 文件名匹配 test_*.py*_test.py
  • test_ 开头的函数
  • Test_ 开头的类,不能包含_init_初始化方法
  • 类中以 test_ 开头的方法

上面的默认规则我们是可以通过配置文件的设置来修改的

# file_name: pytest.ini

[pytest]
testpaths = xdist_study

python_files = test*.py

python_classes = Test*

python_functions = test_*

testpaths:配置在哪个目录下搜索测试用例,可自定义,可以配置多个,多个用空格隔开

python_files:用来配置搜索的测试用例的文件名称,可自定义,可以配置多个,多个用空格隔开

python_classes:配置搜索的测试用例的类名,可自定义,可以配置多个,多个用空格隔开

python_functions:配置搜索的测试用例的方法名,可自定义,可以配置多个,多个用空格隔开

上面的配置表示:在xdist_study目录下,搜索以test开头,以.py结尾的文件,以Test开头的类,以test_开头的方法。

pytest.ini配置文件的参数值会被命令行覆盖

当ini配置文件的参数与执行测试用例文件的命令行参数重复时,命令行参数值会覆盖ini配置文件中定义的参数值。

举例:命令行参数值为3,pytest.ini参数值为2,实际执行的参数值为3

image

标签:log,配置文件,--,pytest,ini,test,string
来源: https://www.cnblogs.com/guanqibuyu/p/16551479.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有