1.安装pytest
pip install pytest
2.导入pytest包
import pytest
3.定义一个函数,倒序输出结果。并建立一个测试用例设置断言检查执行结果
pytest识别test_xxx.py或者xxx_test.py格式的函数作为测试用例来执行
import pytest
def reverse(str):
return str[::-1]
def test_reverse():
str='python'
assert reverse(str) == 'nohtyp'
print(reverse(str))
4.定义的断言值从pytest返回的错误信息取
import pytest
def division(a,b):
return a/b
def test_div():
with pytest.raises(ZeroDivisionError):
division(5, 0)
测试脚本执行方式`
1.pytest命令执行
参数:
-vs -v:输出详细信息 -s:输出调试信息
-n 多线程运行(安装pytest -xdist)
--reruns num 失败重跑(安装pytest -rerunfailres)
-x 出现一个失败则停止
-k 运行测试用例名称包含某个字符串的用例
--html 生成html报告
2.通过主函数main方式执行
if __name__=='__main__':
pytest.main(["-vs"])
3.通过全局配置文件pytest.ini文件执行
ps:
一般放在项目的根目录下
编码格式为ANSI
pytest.ini可以改变默认的测试用例规则
不管是命令运行还是主函数运行,都会加载这个配置文件
跳过用例:skip
1.有条件跳过
import pytest
class TestPC:
def test_login(self):
a=1
b=2
assert a + b == 3
print('今天星期一')
return a+b
@pytest.mark.skipif(1==1,reason="无理由跳过q")
def test_add(self):
print(1+2,'天气很不错')
2.无条件跳过
import pytest
class TestPC:
def test_login(self):
a=1
b=2
assert a + b == 3
print('今天星期一')
return a+b
@pytest.mark.skip(reason="无理由跳过")
def test_add(self):
print(1+2,'天气很不错')