一.pytest框架
pytest是一个流行的测试框架,广泛用于单元测试,集成测试和功能测试.它具有简单,灵活,可扩展的特点.提供了丰富的功能和插件生态系统,它简化了测试的编写和组织,pytest通过丰富的功能和简介的语法,让测试变得更容易,灵活且易于理解
二.安装
pip install pytest -i https://pypi.tuna.tsinghua.edu.cn/simple/
三.pytest编写规则
1.测试文件以test开头(以test结尾也可以)
2.测试类以Test开头,并且不能带有init()构造函数
3.测试函数以test开头
4.断言使用基本的assert即可
四.pytest的运行方式
1.主函数模式
pytest.main(['-v','-s'])
2.命令行模式
# 运行某一个测试文件
pytest test_login.py
# 运行某一个测试文件中的指定测试类
pytest test_login.py::TestLogin2
# 要运行一个测试文件里面类中的指定测试方法
pytest test_login.py::TestLogin2::test_case_02
3.通过读取pytest.ini配置文件运行(企业自动化推荐使用)
一般在项目根目录下创建pytest.ini文件,文件名为固定写法,不能随意更改
[pytest]
# -vs:控制台打印详细的调试信息 -n 数字:设置并发执行数量(多进程/多线程) -rerun 数字:设置全局测试用例失败重跑次数
addopts = -vs -n 3 --reruns 3
# 测试用例路径
testpaths = ./other
# 约定测试文件的模块名称,通过这个配置可以改变pytest的默认规则
python_files = test_*.py
# 约定测试类的名称
python_classes = Test*
# 约定测试函数的名称
python_functions = test_*
# 注册自定义标记
markers =
last
first
second
五.断言
断言是一种用于验证代码行为是否符合预期的方式.当测试执行时,如果断言失败,测试将被标记为失败.通过关键字assert去断言结果
class TestAssert:
# 相等断言
def test_case01(self):
assert 1 == 2
# 不相等断言
def test_case02(self):
assert 1 != 2
# 真假断言
def test_case03(self):
assert_bool = False
assert assert_bool is True
# 成员关系断言
def test_case04(self):
container = ['pytest','unittest','python']
item = 'python'
assert item in container
# 集合断言
def test_case05(self):
set_a = {
1,2,3,4}
set_b = {
3,2,1}
assert set_a == set_b
六.pytest丰富的插件系统
1.并发执行(多进程/多线程)
pytest-xdist提供一个-n选项设置多进程/多线程数量,使得测试用例可以在多个进程或线程中并发执行,提升测试效率.
-
安装插件
pip install pytest-xdist -
示例代码
import pytest from time import sleep class TestPlugin: def test_plugin_case_01(self): sleep(3) print("plugin第一个测试用例") def test_plugin_case_02(self): sleep(3) print("plugin第二个测试用例") def test_plugin_case_03(self): sleep(3) print("plugin第三个测试用例") if __name__ == '__main__': pytest.main(['-n 3'])
2.失败用例重跑
当我们做自动化测试时执行测试用例,遇到网络波动或其他不确定因素导致case运行失败,这并不是测试,这时需要用到重试运行
-
安装插件
pip install pytest-rerunfailures -
示例代码
import pytest import random class TestRerunFailed: # @pytest.mark.flaky(reruns=3,reruns_delay=2) # 对单个测试用例设置失败重跑次数reruns: 重跑次数;reruns_delay: 重跑间隔时间 def test_rerun_failed_case(self): assert random.choice([

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



