前言

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 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 dire console_output_style (string) console output: classic or with additional progr usefixtures (args) list of default fixtures to be used with this project python_files (args) glob-style file patterns for Python test module disco python_classes (args) prefixes or glob names for Python test class discover python_functions (args) prefixes or glob names for Python test function and m xfail_strict (bool) default for the strict parameter of
addopts (args) extra command line options
minversion (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():
pass def 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 deselected test_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 case
hello: 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 be
reported 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 if
argnames 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 needing
all 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 != b if __name__ == "__main__":
pytest.main(["-v", "test_xpass.py"])

测试结果

collecting ... collected 3 items

test_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 case
hello: Run the hello case xfail_strict = true

再次运行,结果就变成

collecting ... collected 3 items

test_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 --rerun 1 --html=report.html --self-contained-html

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

# pytest.ini
[pytest] markers =
webtest: Run the webtest case
hello: Run the hello case xfail_strict = true addopts = -v --rerun 1 --html=report.html --self-contained-html

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

---------------------------------pytest结合selenium自动化完整版-------------------------

全书购买地址 https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b

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

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

pytest文档18-配置文件pytest.ini的更多相关文章

  1. pytest文档3-pycharm运行pytest

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

  2. pytest文档7-pytest-html生成html报告

    前言 pytest-HTML是一个插件,pytest用于生成测试结果的HTML报告.兼容Python 2.7,3.6 pytest-html 1.github上源码地址[https://github. ...

  3. pytest文档51-内置fixture之cache使用

    前言 pytest 运行完用例之后会生成一个 .pytest_cache 的缓存文件夹,用于记录用例的ids和上一次失败的用例. 方便我们在运行用例的时候加上--lf 和 --ff 参数,快速运行上一 ...

  4. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  5. pytest文档40-pytest.ini配置用例查找规则(面试题)

    前言 面试题:pytest如何执行不是test开头的用例?如执行 xxx_*.py这种文件的用例. pytest.ini 配置文件可以修改用例的匹配规则. pytest命令行参数 cmd打开输入pyt ...

  6. pytest文档55-plugins插件开发

    前言 前面一篇已经学会了使用hook函数改变pytest运行的结果,代码写在conftest.py文件,实际上就是本地的插件了. 当有一天你公司的小伙伴觉得你写的还不错,或者更多的小伙伴想要你这个功能 ...

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

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

  8. pytest文档43-元数据使用(pytest-metadata)

    前言 什么是元数据?元数据是关于数据的描述,存储着关于数据的信息,为人们更方便地检索信息提供了帮助. pytest 框架里面的元数据可以使用 pytest-metadata 插件实现.文档地址http ...

  9. pytest文档19-doctest测试框架

    前言 doctest从字面意思上看,那就是文档测试.doctest是python里面自带的一个模块,它实际上是单元测试的一种. 官方解释:doctest 模块会搜索那些看起来像交互式会话的 Pytho ...

随机推荐

  1. .NETCore Sqlserver下对Dapper的扩展支持

    这里我们自定义一个IServiceCollection的扩展,例如下面我的扩展 services.AddDapperContext(dapperoptions => { dapperoption ...

  2. day7回顾

    静态方法: 与类无关,不能访问类里的任何属性和方法 类方法: 只能访问类变量 属性@property 把一个方法变成一个静态属性 反射 getattr(obj,str) setattr(obj,str ...

  3. ASP.NET:使用Flurl制作可复用的分页组件

    使用ASP.NET MVC查询时,一直使用MvcPaging组件,虽然需要自定义MvcPaging.Pager才能达到我想要的效果,但在没有较好的URL库时,还是这么用.分页的逻辑本来就不复杂,更重要 ...

  4. 【POJ】2454.Jersey Politics

    题解 有种迷一样的讽刺效果 每个城市有1000头牛,然后你现在知道对于自己政党每个城市的选票,把城市划分成三个州,保证在至少两个州内获胜 找出前2K大的然后random_shuffle,直到前K个加起 ...

  5. Python djangorestframework安装库报错SSL: CERTIFICATE_VERIFY_FAILED

    Python djangorestframework 安装库报错SSL: CERTIFICATE_VERIFY_FAILED 问题描述 使用pip按照virtualenv报错,如下: pip inst ...

  6. 黑马程序员_java基础笔记(04)...多线程

    ——————————ASP.Net+Android+IOS开发..Net培训.期待与您交流!—————————— 多线程.第一重点:创建线程的两种方式.第二重点:同步的所有特性      进程:正在执 ...

  7. 【记录】HTTP协议状态码含义

    状态码200-299之间的状态码表示成功300-399之间的代码表示资源已经被移走400-499之间的代码表示客户端的请求出错500-599之间的代码表示服务器出错了

  8. 【面试总结】2019校招京东一面二面,及深信服技术面(已拿深信服offer),还有百度一面

    百度一面: 1.自我介绍+项目介绍 2.进程和线程的区别 3.常用linux命令列举 4.堆排序 5.快速排序 反问环节. 现在的状态是岗位转推,毕竟百度投的是开发岗. 京东一面: 1.C++三大特性 ...

  9. JAVA内存泄漏解决办法

    JVM调优工具 Jconsole,jProfile,VisualVM Jconsole : jdk自带,功能简单,但是可以在系统有一定负荷的情况下使用.对垃圾回收算法有很详细的跟踪.详细说明参考这里 ...

  10. Urllib库的基本用法

    1.什么是url? 统一资源定位符是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址. 基本URL包含模式(或称协议).服务器名称(或IP地址).路径和文件名,如“ ...