一.配置文件
pytest的配置文件可以改变pytest的运行方式,是一个固定的配置文件pytest.ini,读取配置信息,按照指定方式运行
1.必须放在根目录下
2.命名必须为pytest.ini
3.pytest -h 配置文件帮助命令
二.配置项
1.markers
装饰器@pytest.mark的时候可以读取到,否则会报错warnings
[pytest]
markers=
number_01: 分类1
number_02: 分类2
number_03: 分类3
2.addopts
addopts参数可以更改默认命令行选项,这个当我们在命令行输入一堆指令去执行测试用例的时候就可以用该参数代替了,省去重复敲命令的工作了
比如测试完想生成报告,失败重跑2次,一共运行2次,通过分布式去测试,如果在命令中写就会很麻烦很长,每次都去敲也不太现实
pytest -v --return=2 --count=2 --html=report.html --self-contained-html -n=auto
所以放在配置文件中更节省时间
[pytest] addopts = pytest -v --return=2 --count=2 --html=report.html --self-contained-html -n=auto
3.log_cli
控制台输出日志的,log_cli=True或False(默认),或者1/0
4.norecursedirs
pytest收集测试用例时会递归遍历所有的子目录,包括某些明知道没有必要遍历的项目,遇到这种情况可以使用norecursedirs参数简化pytest的搜索工作
默认设置:norecursedirs =.*build dist CVS_darcs{arch}*.egg
正确写法:多个路径用空格隔开
[pytest]
norecursedirs =.*build dist CVS_darcs{arch}*.egg venv src resources log report util
三、参数化测试
1.参数化启动级别
pytest可以在多个级别启动参数化
- pytest.fixture()
- @pytest.mark.parametrize
- pytest_generate_test:允许定义自定义参数化方案或扩展
2.parametrize参数
2.1装饰测试类
use_info =[('tom','123'),('bob','2345'),('cindy','7823')]
@pytest.mark.parametrize('username,pwd',use_info)
def test_login(username,pwd):
print(username +pwd)
2.2多个参数化装饰器
import pytest
#笛卡尔积,组合数据
l1 = [3,4,5]
l2 = ['a','b','c']
@pytest.mark.parametrize('a',l1)
@pytest.mark.parametrize('b',l2)
def test_01(a,b):
print(f'笛卡尔积数据:{a},{b}')
2.3传入字典数据
import pytest
data = (
{
'user':1,
'pwd':2
},
{
'user':3,
'pwd':4
}
)
@pytest.mark.parametrize('dic',data)
def test_01(dic):
print(f'user:{dic["user"]},pwd:{dic["pwd"]}')
2.4 ids参数,其实是为了增强可读性
import pytest
#增强可读性
data = [(1,2,3),(4,5,9)]
ids = ["a:{}+b:{} = expect:{}".format(a,b,expect) for a,b,expect in data ]
@pytest.mark.parametrize('a,b,expect',data,ids=ids)
def test_01(a,b,expect):
print('测试数据为{}+{}={}'.format(a,b,expect))
2.5 indirect
@pytest.mark.parametrize里面indirect参数,默认是False
False: 就是parametrize里面argnames 参数当作一个普通的变量,不会去找变量对应函数的名的方法
True: 就是parametrize里面argnames 参数当作函数执行,它会去找对应的函数,去执行
import pytest
@pytest.fixture()
def login(request):
name = request.param
print(f'我是函数{name}')
return name
#增强可读性
data = ['tom','bob']
# ids = [f'正确名字{name}'for name in data ]
@pytest.mark.parametrize('login',data,indirect=True)
def test_01(login):
print(f'我是变量{login}')
False:
import pytest
@pytest.fixture()
def login(request):
name = request.param
print(f'我是函数{name}')
return name
#增强可读性
data = ['tom','bob']
# ids = [f'正确名字{name}'for name in data ]
@pytest.mark.parametrize('login',data,indirect=False)
def test_01(login):
print(f'我是变量{login}')



