1.是单元测试框架,可以实现测试用例跳过以及result失败用例重试;可以和allure生成美观的测试报告;可以和jenkins持续集成;有很多插件:pytest,pytest-html,pytest-xdist(测试用例分步式执行);pytest-ordering(改变执行顺序),pytest-rerunfailures(失败重新跑);allure-pytest(生成美观的测试报告)
2.需要具备的技能:selenium request appium 断言 报告邮件 等
安装库:
pytest
pytest-html
pytest-xdist
pytest-ordering
pytest-rerunfailures
allure-pytest
使用pytest:
规则: 1.模块名必须以test_开头或者_test结尾
2.测试类必须以Test开头 且不能有init方法
3.测试方法必须以test开头
运行方式:
1.主函数 1)所有: pytest.main()
2.命令行 在工程目录下执行
pytest
pytest -vs
pytest -vs xxx.py
pytest -vs xxx/xxx.py::类名::函数名
pytest -vs xxx.py -n 2 两个线程同时执行
pytest -vs xxx.py -n 2 两个线程同时执行
pytest -vs xxx.py --reruns 2 失败重跑两次
pytest -vs xxx.py -x 失败停止
pytest -vs xxx.py --maxfail num 失败num次停止
-k string 根据指定的字符串跑特定的包含string的用例
--html ./report/report.html 生成测试报告
参数:
['-vs']: 输出调试的信息
指定模块:跑特定的用例 ['-vs','XXX.py']
指定特定的文件夹: ['-vs','文件夹']
指定函数执行:pytest.main(['-vs','testcase/test_login.py::test_zhiliao'])
3.通过读取pytest.ini配置运行
pytest的执行顺序:
指定测试顺序:
1.在函数前加装饰器:
```
@pytest.mark.run(order=3)
```
2.使用pytest.ini配置执行
一般放在项目的根目录,格式必须是ANSI,可以改变pytest的默认行为
[pytest] addopts = -vs testpaths = ./testcase python_files = test*.py python_classes = Test* python_functions = test
如何分组执行:
[pytest] addopts = -vs testpaths = ./ python_files = test*.py python_classes = Test* python_functions = test markers = smoke:冒烟用例 user: 用户 product: 商品
执行smoke和user标记的用例的命令: pyest -vs -m "smoke or user"
跳过一些用例:
无条件: @pytest.mark.skip(reason="无条件跳过")
有条件: @pytest.mark.skipif(age>=18,reason="已成年")
二. pytest前后置处理,常用的三种
- setup/teardown setup_class/teardown_class 作用于所有的用例或者所有的类
用途: 用例执行前后的一些操作
import pytest
class TestLogin():
age = 18
def setup_class(self):
print("所有的用例执行之前只执行一次")
def setup(self):
print("所有的用例执行之前都要执行一次,有多少个用例执行多少次")
def test_01_baili(self):
print("测试百里")
def test_02_xiaoxin(self):
print("测试小新")
def test_03_tiaotiao(self):
print("测试跳跳")
def test_04_huahua(self):
print("测试花花")
def teardown(self):
print("用例执行后的一些操作")
def teardown_class(self):
print("在所有的用例执行完了之后执行一次")
2.使用fixture装饰器
用途:部分用例前后的操作 既可以作用于全部有可以作用于个别用例
@pytest.fixture()
#scope:表示作用域:function class module package
#params :参数化 autouse: 自动执行 默认是false
# ids:参数化时给每个值设置一个name
# name:表示被@pytest.fixture装饰的函数起一个别名
@pytest.fixture(scope='module')
def my_fixture():
print("这是部分用力的前置操作!")
yield
print("这是后置的操作!!")
3.通过 conftest.py和@pytest.fixture 实现全局的前置应用
import pytest
@pytest.fixture(scope='function',autouse=True)
def all_fixture(request):
print("全局前置")
yield
print("全局后置")
四. 断言
assert : assert 1 == 2
五. 生成报告
pytest 结合allure-pytest生产allure报告
pytest-html
allure-pytest
1.安装allure
下载allure网址:
https://blog.csdn.net/gaomingjian218/article/details/121071149
2.生产json文件:
--alluredir report/tmp
3.生成allure报告:
--allure gengrate ./report/tmp -o ./result/ --clean
注意: 我本地直接用浏览器打开报告后一直显示加载中,解决方法可以参考这个博客: