前言

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

ini配置文件

pytest里面有些文件是非test文件

  • pytest.ini pytest的主配置文件,可以改变pytest的默认行为
  • conftest.py 测试用例的一些fixture配置
  • _init_.py 识别该文件夹为python的package包
  • tox.ini 与pytest.ini类似,用tox工具时候才有用
  • setup.cfg 也是ini格式文件,影响setup.py的行为

ini文件基本格式

# 保存为pytest.ini文件[pytest]addopts = -rsxX
xfail_strict = true

使用pytest --help指令可以查看pytest.ini的设置选项

[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:markers (linelist)       markers for test functionsempty_parameter_set_mark (string) default marker for empty parametersetsnorecursedirs (args)     directory patterns to avoid for recursiontestpaths (args)         directories to search for tests when no files or direconsole_output_style (string) console output: classic or with additional progrusefixtures (args)       list of default fixtures to be used with this projectpython_files (args)      glob-style file patterns for Python test module discopython_classes (args)    prefixes or glob names for Python test class discoverpython_functions (args)  prefixes or glob names for Python test function and mxfail_strict (bool)      default for the strict parameter of addopts (args)           extra command line optionsminversion (string)      minimally required pytest version

–rsxX 表示pytest报告所有测试用例被跳过、预计失败、预计失败但实际被通过的原因

mark标记

如下案例,使用了2个标签:webtest和hello,使用mark标记功能对于以后分类测试非常有用处

# content of test_mark.py
import pytest@pytest.mark.webtest
def test_send_http():print("mark web test")def test_something_quick():passdef test_another():pass@pytest.mark.hello
class TestClass:def test_01(self):print("hello :")def test_02(self):print("hello world!")if __name__ == "__main__":pytest.main(["-v", "test_mark.py", "-m=hello"])

运行结果

============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0 -- D:\soft\python3.6\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.6.0', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'pytest': '3.6.3', 'py': '1.5.4', 'pluggy': '0.6.0'}, 'Plugins': {'metadata': '1.7.0', 'html': '1.19.0', 'allure-adaptor': '1.7.10'}, 'JAVA_HOME': 'D:\\soft\\jdk18\\jdk18v'}
rootdir: D:\YOYO, inifile:
plugins: metadata-1.7.0, html-1.19.0, allure-adaptor-1.7.10
collecting ... collected 5 items / 3 deselectedtest_mark.py::TestClass::test_01 PASSED                                  [ 50%]
test_mark.py::TestClass::test_02 PASSED                                  [100%]=================== 2 passed, 3 deselected in 0.11 seconds ====================

有时候标签多了,不容易记住,为了方便后续执行指令的时候能准确使用mark的标签,可以写入到pytest.ini文件

# pytest.ini
[pytest]markers =webtest:  Run the webtest casehello: Run the hello case

标记好之后,可以使用pytest --markers查看到

$ pytest --markers

D:\YOYO>pytest --markers
@pytest.mark.webtest:  Run the webtest case@pytest.mark.hello: Run the hello case@pytest.mark.skip(reason=None): skip the given test function with an optional re
ason. Example: skip(reason="no way of currently testing this") skips the test.@pytest.mark.skipif(condition): skip the given test function if eval(condition)
results in a True value.  Evaluation happens within the module global context. E
xample: skipif('sys.platform == "win32"') skips the test if we are on the win32
platform. see http://pytest.org/latest/skipping.html@pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False):mark the test function as an expected failure if eval(condition) has a True val
ue. Optionally specify a reason for better reporting and run=False if you don't
even want to execute the test function. If only specific exception(s) are expect
ed, you can list them in raises, and if the test fails in other ways, it will bereported as a true failure. See http://pytest.org/latest/skipping.html@pytest.mark.parametrize(argnames, argvalues): call a test function multiple tim
es passing in different arguments in turn. argvalues generally needs to be a lis
t of values if argnames specifies only one name or a list of tuples of values ifargnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would l
ead to two calls of the decorated test function, one with arg1=1 and another wit
h arg1=2.see http://pytest.org/latest/parametrize.html for more info and example
s.@pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needingall of the specified fixtures. see http://pytest.org/latest/fixture.html#usefix
tures@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 m
achinery will try to call it last/as late as possible.

最上面两个就是刚才写入到pytest.ini的配置了

禁用xpass

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

什么叫标记为@pytest.mark.xfail但实际通过,这个比较绕脑,看以下案例

# content of test_xpass.py
import pytest
** 作者:上海-悠悠 QQ交流群:588402570**def test_hello():print("hello world!")assert 1@pytest.mark.xfail()
def test_yoyo1():a = "hello"b = "hello world"assert a == b@pytest.mark.xfail()
def test_yoyo2():a = "hello"b = "hello world"assert a != bif __name__ == "__main__":pytest.main(["-v", "test_xpass.py"])

测试结果

collecting ... collected 3 itemstest_xpass.py::test_hello PASSED    [ 33%]
test_xpass.py::test_yoyo1 xfail     [ 66%]
test_xpass.py::test_yoyo2 XPASS     [100%]=============== 1 passed, 1 xfailed, 1 xpassed in 0.27 seconds ================

test_yoyo1和test_yoyo2这2个用例一个是a == b一个是a != b,两个都标记失败了,我们希望两个用例不用执行全部显示xfail。实际上最后一个却显示xpass.为了让两个都显示xfail,那就加个配置
xfail_strict = true

# pytest.ini
[pytest]markers =webtest:  Run the webtest casehello: Run the hello casexfail_strict = true

再次运行,结果就变成

collecting ... collected 3 itemstest_xpass.py::test_hello PASSED        [ 33%]
test_xpass.py::test_yoyo1 xfail         [ 66%]
test_xpass.py::test_yoyo2 FAILED        [100%]================================== FAILURES ===================================
_________________________________ test_yoyo2 __________________________________
[XPASS(strict)]
================ 1 failed, 1 passed, 1 xfailed in 0.05 seconds ================

这样标记为xpass的就被强制性变成failed的结果

配置文件如何放

一般一个工程下方一个pytest.ini文件(不要瞎jb拍脑袋乱命名,瞎jb命名是找不到的)就可以了,放到顶层文件夹下

addopts

addopts参数可以更改默认命令行选项,这个当我们在cmd输入指令去执行用例的时候,会用到,比如我想测试完生成报告,指令比较长

$ pytest -v --reruns 1 --html=report.html --self-contained-html

每次输入这么多,不太好记住,于是可以加到pytest.ini里

# pytest.ini
[pytest]markers =webtest:  Run the webtest casehello: Run the hello casexfail_strict = trueaddopts = -v --reruns 1 --html=report.html --self-contained-html

这样我下次打开cmd,直接输入pytest,它就能默认带上这些参数了

作者:上海-悠悠 QQ交流群:874033608

也可以关注下我的个人公众号:yoyoketang

pytest文档18-配置文件pytest.ini相关推荐

  1. pytest文档3-pycharm运行pytest

    前言 上一篇pytest文档2-用例运行规则已经介绍了如何在cmd执行pytest用例,平常我们写代码在pycharm比较多 写完用例之后,需要调试看看,是不是能正常运行,如果每次跑去cmd执行,太麻 ...

  2. pytest文档21-pytest-html报告优化(nodeid中文显示[\u6350\u52a9\u6211\u4eec]问题解决)

    前言 pytest-html报告中当用到参数化时候,获取用例的nodeid里面有中文时候,会显示[\u6350\u52a9\u6211\u4eec]这种编码(再次声明,这个不叫乱码,这是unicode ...

  3. pycharm中出现pytest_pytest文档3-pycharm运行pytest

    前言 上一篇pytest文档2-用例运行规则已经介绍了如何在cmd执行pytest用例,平常我们写代码在pycharm比较多 写完用例之后,需要调试看看,是不是能正常运行,如果每次跑去cmd执行,太麻 ...

  4. pytest文档73-pytest+yaml实现接口自动化框架之用例参数关联

    前言 使用 yaml 文件写测试用例的时候,如何在 yaml 文件的测试用例里面实现参数关联? 这是很多做自动化测试的小伙伴经常思考的一个问题. 接着前面的pytest+yaml 文件实现接口自动化框 ...

  5. pytest文档46-关于https请求警告问题(InsecureRequestWarning: Unverified HTTPS request is being made)

    前言 使用 pytest 执行 https 请求用例的时候,控制台会出现警告:InsecureRequestWarning: Unverified HTTPS request is being mad ...

  6. pytest文档56-插件打包上传到 pypi 库

    前言 pytest 的插件完成之后,可以上传到 github,方便其他小伙伴通过 pip 源码安装.如果我们想通过 pip install packages 这种方式安装的话,需上传到 pypi 仓库 ...

  7. pytest文档59-运行未提交git的用例(pytest-picked)

    前言 我们每天写完自动化用例后都会提交到 git 仓库,随着用例的增多,为了保证仓库代码的干净,当有用例新增的时候,我们希望只运行新增的未提交 git 仓库的用例. pytest-picked 插件可 ...

  8. TIM学习文档18——TIM部署之组织结构

    本文已搬家至[IBM Tivoli Identity Manager 学习文档]14 TIM组织结构设计

  9. pytest文档48-切换 base_url 测试环境(pytest-base-url)

    前言 当我们自动化代码写完成之后,期望能在不同的环境测试,这时候应该把 base_url 单独拿出来,能通过配置文件和支持命令行参数执行. pytest-base-url 是 pytest 里面提供的 ...

最新文章

  1. centos 学习日记 文件默认权限:umaks
  2. 使用Shell(bash) 来检查 git 本地某个分支是否存在
  3. 促使网站关键词排名稳定的技巧有哪些?
  4. Smali文件添加try/catch语句,出现“invalid use of move-exception”异常
  5. feign接口调用出现连接超时
  6. Densely CNN
  7. springboot国际化04
  8. CASL编程?—— CANape的自动化“利器”
  9. Easyrecovery激活码生成器下载地址?
  10. 从0到1,搭建经营分析体系
  11. 科目二边距30cm有什么技巧
  12. 一个博士在华为的22年!
  13. Ubuntu 14.04 配置 Java SE jdk-7u55
  14. 卡塔尔是一个什么样的国家?
  15. 如何 修改 系统 用户名称 和登陆名称
  16. 将SQL server2019数据库部署在虚拟机上
  17. stc单片机如何用C程序将IO口设为强推挽输出!!!
  18. java基础--内部类学习笔记
  19. 划线高亮和插入笔记的技术实现
  20. js方法在ie浏览器不起作用

热门文章

  1. tp的think-queue的队列使用
  2. vbs 语音说话(表白必备)
  3. Linux命令之passwd命令
  4. AIO-3588SJD4八核8K人工智能主板
  5. 【网络互联设备】网络杂谈(15)之网桥、路由器、网关、集线器、交换机、中继器的作用与概念
  6. 学习 Python 的 12 个方式
  7. 风炫安全Web安全学习第二节课 HTML基础
  8. Linux- 内核引导过程
  9. 阿木实验室的普罗米修斯仿真平台搭建的难点和坑点
  10. 什么,借呗要关闭?官方回应:谣言!