pytest-18-配置文件pytest.ini

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

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文件就可以了,放到顶层文件夹下

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,它就能默认带上这些参数了

原文地址:https://www.cnblogs.com/jason89/p/10323722.html

时间: 2024-07-30 19:19:24

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

MySQL配置文件mysql.ini参数详解、MySQL性能优化

MySQL配置文件mysql.ini参数详解.MySQL性能优化 my.ini(Linux系统下是my.cnf),当mysql服务器启动时它会读取这个文件,设置相关的运行环境参数. my.ini分为两块:Client Section和Server Section.   Client Section用来配置MySQL客户端参数.   要查看配置参数可以用下面的命令: show variables like '%innodb%'; # 查看innodb相关配置参数 show status like

linux下php中找不到php配置文件php.ini的解决方法

自己编译安装的php经常会遇上这种问题,找不到php.ini.可以按照如下方法解决: 首先需要说明的是,如果你的php是编译安装的,那么默认是没有php.ini的,你必须自行去源码包里边拷贝.运行phpinfo()命令可以看到php指定的配置文件路径,把配置文件放到这个路径中即可. linux下php中找不到php配置文件php.ini的解决方法

Mysql配置文件my.ini详解

原链接:http://blog.sina.com.cn/s/blog_718ac8bf0100pkvp.html 以下是Mysql数据库服务器配置文件my.ini的详细配置.应用场合是InnoDB引擎,2核CPU, 32位SUSE. [client] #password = your_password port  = 3306 socket  = /tmp/mysql.sock # Here follows entries for some specific programs # The MyS

pytest系列(四)- pytest+allure+jenkins - 持续集成平台生成allure报告

pytest是什么 pytest是python的一款测试框架,拥有unittest的功能并比它更丰富. allure是什么 有非常多的优秀的测试框架,但却是有非常少优秀的报告工具可以展示非常清楚的用例执行过程和结果. allure是一款开源的,专门用来展示测试结果的工具,目的是希望团队内部每一个人都可以看到非常清楚的测试结果. allure可以与非常多的著名测试框架做集成. 像java语言,可以与junit4,junit5,TestNG测试框架集成. python语言,可以与pytest,beh

用python读取配置文件config.ini

还在学习中...写的有点凌乱 感觉还是应该先学会读取配置文件才行,把一些经常需要修改的但是又经常需要用到的参数放到配置文件中方便使用(我是这么觉得的) 首先是config.ini的存放位置,我们把它放在根目录下(当然也可以随便想放哪放哪) 1 proDir = os.path.split(os.path.realpath(__file__))[0] //根目录地址 2 configPath = os.path.join(proDir, "config.ini") //存放在根目录下,文

[转载]MySQL5.5 配置文件 my.ini 1067错误

原文链接:http://blog.csdn.net/xiaochunyong/article/details/7438200 解压mysql-5.5.22-win32.zip后的目录中有5个my-xxxx.ini配置文件, 通过查看配置文件中的描述,是说针对不同内存大小的推荐配置. 本例复制了my-medium.ini 并重命名为 my.ini  然后添加了如下几行: [client] default-character-set=utf8   客户端编码 [mysqld] basedir=D:/

Hue的全局配置文件hue.ini(图文详解)

Hue版本:hue-3.9.0-cdh5.5.4 需要编译才能使用(联网) 说给大家的话:大家电脑的配置好的话,一定要安装cloudera manager.毕竟是一家人的.同时,我也亲身经历过,会有部分组件版本出现问题安装起来要个大半天时间去排除,做好心里准备.废话不多说,因为我目前读研,自己笔记本电脑最大8G,只能玩手动来练手.纯粹是为了给身边没高配且条件有限的学生党看的! 但我已经在实验室机器群里搭建好cloudera manager 以及 ambari都有. 大数据领域两大最主流集群管理工

快速定位PHP的配置文件php.ini

因php存在cli和php-fpm两种模式,因此两种运行模式会对应加载不同的配置文件. php-fpm模式 在页面中打印phpinfo(),通过浏览器访问,在页面中搜索php.ini找到Configuration File (php.ini) Path 这一项即可 cli模式 方法1:通过php -i(PHP information) 在php信息中搜索php.ini.(这里同php-fpm模式中的phpinfo()) $ php -i|grep php.ini Configuration Fi

python读写修改配置文件(ini)

python 有时候参数需要保存到配置文件中  接下来总结一下 配置文件的读写和修改的操作 代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- # 读取配置文件 import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open('update.ini')) a = config.get("ZIP","MD5") print a #

pytest 框架生成 pytest - html 报告

需要安装 pytest - html 插件: pip install pytest-html pytest 可以生成多种样式的结果: 生成 JunitXML 格式的测试报告,命令:--junitxml=path 生成 ResultLog 格式的测试报告,命令:--resultlog=report/log.txt 生成 Html 格式的测试报告,命令:--html=OutPuts/reports/report.html(相对路径) 二.生成 HTML 报告 if __name__ == '__ma