配置文件pytest.ini
前言
很多 pytest settings 可以设置在 配置文件 ,它通常位于存储库的根目录或测试文件夹中
pytest.ini
文件优先于其他文件,即使是空的
pytest配置文件可以改变pytest的运行方式,它是一个固定的文件pytest.ini文件,读取配置信息,按指定的方式去运行
常用配置项
markers
它的作用是做注册标记,防止拼写错误。比如把@pytest.mark.smoke拼成@pytest.mark.somke,默认情况下。这不会引起程序错误。pytest会以为这是你创建的另一个标记。为了避免拼写错误。可以在pytest.ini文件里注册标记
[pytest]
# 注册自定义标记
markers =
smoke: Run the smoke test functions for tasks project
get: Run the test functions that test tasks.get()
标记注册好后,可以通过pytest --markers来查看
testpaths
testpaths指示pytest去哪里访问。testpaths是一系列相对于根目录的路径,用于限定测试用例的搜索范围。只有在pytest未指定文件目录参数或测试用例标识符时,该选项才有作用,举个🌰:
修改pytest.ini
文件如下:
[pytest]
testpaths = test_02.py
修改test_01.py test_02.py
文件如下:
# FileName: test_01.py
import pytest
def test_01(fixturedemo):
print('执行测试用例1')
# FileName: test_02.py
def test_02(fixturedemo):
print('执行测试用例2')
执行pytest -v
结果如下:
addopts
更改默认命令行选项
pytest用命令行运行时,有时候需要经常要用到某些参数,又不想重复输入,这时可以使用pytest.ini文件里的addopts设置,举个🌰,修改pytest.ini
文件如下:
[pytest]
addopts=-vs
执行pytest
结果如下:
可以看到打印了用例所在文件及用例名称,也打印了print输出
再举个🌰:
比如:想测试完生成报告,失败重跑两次,一共运行两次,如果在cmd中写的话,命令会很长
pytest -v --rerun=2 --count=2 --html=report.html --self-contained-html
每次都需要敲,会浪费不少时间,可以使用pytest.ini完美解决:
[pytest]
# 命令行参数
addopts = -v --reruns=1 --count=2 --html=reports.html --self-contained-html
xfail_strict
作用:设置xfail_strict = True可以让那些标记为@pytest.mark.xfail但实际通过显示XPASS的测试用例被报告为失败
格式:True 、False(默认),1、0
修改pytest.ini
如下:
[pytest]
xfail_strict = True
修改test_01.py文件如下:
# FileName: test_01.py
import pytest
def test_02(fixturedemo):
print('执行test_02测试用例2')
@pytest.mark.xfail()
def test_01():
print("执行test_02测试用例1")
执行结果如下:
log_cli
作用:控制台实时输出日志
格式:log_cli=True 或False(默认),或者log_cli=1 或 0
修改pytest.ini
如下:
[pytest]
log_cli = True
log_cli为0/1,前后执行结果对比如下:
加了log_cli=1之后,可以清晰看到哪个package下的哪个module下的哪个测试用例是否passed还是failed
norecursedirs
作用:pytest 收集测试用例时,会递归遍历所有子目录,包括某些你明知道没必要遍历的目录,遇到这种情况,可以使用 norecursedirs 参数简化 pytest 的搜索工作
默认设置: norecursedirs = .* build dist CVS _darcs {arch} *.egg
正确写法:多个路径用空格隔开
举个🌰,想要不遍历 venv、src、resources、log、report、util文件夹,可以进行如下设置
[pytest]
norecursedirs = .* build dist CVS _darcs {arch} *.egg venv src resources log report util
更改测试用例收集规则
pytest默认的测试用例收集规则
是可以修改或者添加这个用例收集规则的(建议在原有的规则上添加),举个🌰:
修改pytest.ini
文件如下:
[pytest]
python_files = test_* *_test test*
python_classes = Test* test*
python_functions = test_* test* tes_*
修改test_02.py
如下:
# FileName: test_02.py
import pytest
def test_02(fixturedemo):
print('执行test_02测试用例2')
@pytest.mark.xfail()
def test_01():
print("执行test_02测试用例1")
执行结果如下:
注意事项
pytest.ini文件应该放在项目根目录下,不要修改名字,否则无法被识别