Pytest配置文件
pytest的配置文件通常放在测试目录下,名称为pytest.ini,命令运行时会使用该配置文件中的配置
配置文件时以 [pytest] 开头 ,pytest.ini文件格式示例:
[pytest]
addopts = -s
testpaths = ./scripts
python_files = test*.py
python_classes = Test*
python_functions = test_*
- 配置pytest命令行运行参数
[pytest]
# 空格分隔,可添加多个命令行参数 -所有参数均为插件包的参数
addopts = -s --reruns 2 --html=./report.html ...
-s是输出程序运行信息
--rerun 2 : 失败重试2次
--html=./report.ml 在当前目录下生成report.html文件
- 配置测试搜索的路径
[pytest]
testpaths = ./scripts # 当前目录下的scrip文件夹 可自定义
- 配置测试搜索的文件名
[pytest]
python_files = test_*.py
# 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件 -可自定义
- 配置测试搜索的测试类名
[pytest]
python_classes = Test_*
# 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类
- 配置测试搜索的测试函数名
[pytest]
python_functions = test_*
# 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类内,以test_开头的⽅法 -可自定
标记(marks)
作用
可以使用标记应用元数据来测试函数(但不是Fixture方法),然后可以通过Fixture方法或插件访问
常用的标记函数如下
Pytest.mark.xfail() | 将测试函数标记为预期失败。 |
---|---|
pytest.mark.usefixtures() | 使用类,模块或项目中的Fixture方法。 |
pytest.mark.skip() | 无条件地跳过测试函数 |
pytest.mark.skipif() | 满足条件,跳过测试函数 |
pytest.mark.parametrize() | 参数化Fixture方法和测试函数。 |
标记为预期失败函数
使用场景: 标记某测试函数会失败
方法:
xfail(condition=None, reason=None, raises=None, run=True, strict=False)
常用参数:
condition:预期失败的条件,若是不传,使用默认值或者condition条件为真,则会预期失败。若是条件为假则不会进行预期失败,而是正常执行测试函数
reason:失败的原因
使用方法:
@pytest.mark.xfail(condition, reason="xxx")
注意:
- 是 参数 condition 不传递值 ,则 参数 reason 可有可无即:
- @pytest.mark.xfail([ reason=“xxx”])
- 若是 参数 condition 传递值,则参数 reason 必须有
- @pytest.mark.xfail(condition, reason=“xxx”)
import pytest
def test_1():
print('未使用xfail')
@pytest.mark.xfail()
def test_one():
print('one----')
@pytest.mark.xfail(condition=