全网最全pytest大型攻略,单元测试学这就够了
off999 2025-05-21 15:45 86 浏览 0 评论
pytest 是一款以python为开发语言的第三方测试,主要特点如下:
- 比自带的 unittest 更简洁高效,兼容 unittest框架
- 支持参数化
- 可以更精确的控制要测试的测试用例
- 丰富的插件,已有300多个各种各样的插件,也可自定义扩展,如pytest-selenium、pytest-html、pytest-rerunfailures、pytes-xdish
- 可很好的和CI工具结合
安装
pip install pytest
测试用例编写规则
- 测试文件以test_开头 或者 _test结尾
- 测试类以Test开头,并且不能带有 init 方法
- 测试文件以 test_开头
- 断言使用基本的 assert 即可
pytest会递归查找当前目录及子目录下所有 以test_开始 或者 _test结尾的python脚本,执行其中符合规则的函数和方法,不需要显示调用
运行命令:(cmd进入用例所在目录)
pytest folder_name ======》直接运行文件夹内符合规则的所有用例
pytest test_file.py ======》执行某个py文件中的用例
pytest test_file.py::test_func ======》执行模块内的某个函数(节点运行)
pytest
test_file.py::TestClass::test_method ======》执行模块内测试类的某个方法(节点运行)pytest test_file.py::TestClass ======》执行模块内某个测试类(节点运行)
pytest test_file.py::TestClass
test_file2.py::test_mothod ======》多节点运行,中间用空格隔开pytest -k pass ======》匹配用例名称的表达式,含有“pass”的被执行,其他的deselected
pytest -k "pass or fail" ======》组合匹配,含有“pass” 和 “fail”的被执行
pytest -k "not pass" ======》排除运行,不含“pass”的被执行
pytest -m finished ======》标记表达式,运行用@pytest.mark.finished 标记的用例
pytest -m "finished and not merged" ======》多个标记逻辑匹配,运行含有finished 不含 merged标记的用例
pytest -v ======》运行时显示详细信息
pytest -s ======》显示打印消息
pytest -x ======》遇到错误就停止运行
pytest -x --maxfail=2 ======》遇到两个错误就停止运行
pytest --setup-show ======》跟踪固件运行
pytest -v --reruns 5 --reruns-delay 1 ======》运行失败的用例间隔1s重新运行5次 pip install pytest-rerunfailures
pytest ======》多条断言,报错后,后面的依然执行, pip install pytest-assume,断言 pytest.assume(2==4)
pytest -n 3 ======》3个cpu并行执行测试用例,需保证测试用例可随机执行, pip install pytest-xdist分布式执行插件,多个cpu或主机执行
pytest -v -n auto ======》自动侦测系统里cpu的数目
pytest --count=2 ======》重复运行测试 pip install pytest-repeat
pytest --html=./report/report.html ======》生成报告,此报告中css是独立的,分享时会丢失样式,pip install pytest-html
pytest --html=report.html --self-containd-html ======》合并css到html报告中,除了passed所有行都被展开
pytest --durations=10 ======》获取最慢的10个用例的执行耗时
用例执行顺序控制
pytest 用例执行顺序默认是按字母顺序去执行,要控制执行顺序,需要安装插件 pytest-ordering:pip install pytest-ordering
在测试方法上加上装饰器:
@pytest.mark.last 最后一个执行
@pytest.mark.run(order=n) n=1则是第一个执行
Mark
标签的使用方法:
注册标签名 / 内置标签—> 在测试用例 / 测试类 / 模块文件 前面加上 @pytest.mark.标签名
注册方法:
1.在conftest.py 文件中添加代码
# 单个标签文件内容
def pytest_configure(config):
config.addinivalue_line("markers", "demo:demo标签名称")
# 多个标签文件内容
def pytest_configure(config):
marker_list = ["p0:p0级别用例", "p1:p1级别用例", "p2:p2级别用例"] # 标签名称
for markers in marker_list:
config.addinivalue_line("markers", markers)
2.项目中添加pytest.ini配置文件
[pytest]
markers =
p0:p0级别用例
p1:p1级别用例
p2:p2级别用例
使用方法:
import pytest
@pytest.mark.p0
def test_mark01():
print("函数级别的mark_p0")
@pytest.mark.p1
def test_mark02():
print("函数级别的mark_p1")
@pytest.mark.P2
class TestDemo:
def test_mark03(self):
print("mark_p2")
def test_mark04(self):
print("mark_p2")
运行方式:
命令行运行
pytest -m "p0 and p1"
文件运行
pytest.main(["-m", "P0", "--html=report.html"])
内置标签:
参数化:@pytest.mark.parametrize(argnames, argvalues)
无条件跳过用例:@pytest.mark.skip(reason=“xxx”)
有条件跳过用例:@pytest.mark.skipif(version < 0.3, reason = “not supported until 0.3”)
预测执行失败进行提示标记:@pytest.mark.xfail(version < 0.3, reason = “not supported until 0.3”),运行结果为X(通过xpassed,失败xfailed)
# 参数化
import hashlib
@pytest.mark.parametrize("x", list(range(10)))
def test_somethins(x):
time.sleep(1)
@pytest.mark.parametrize("passwd",["123456", "abcdefgfs", "as52345fasdf4"])
def test_passwd_length(passwd):
assert len(passwd) >= 8
@pytest.mark.parametrize('user, passwd',[('jack', 'abcdefgh'),('tom', 'a123456a')])
def test_passwd_md5(user, passwd):
db = {
'jack': 'e8dc4081b13434b45189a720b77b6818',
'tom': '1702a132e769a623c1adb78353fc9503'
}
assert hashlib.md5(passwd.encode()).hexdigest() == db[user]
# 如果觉得每组测试的默认参数显示不清晰,可以使用 pytest.param 的 id 参数进行自定义
@pytest.mark.parametrize("user, passwd",
[pytest.param("jack", "abcdefgh", id = "User<Jack>"),
pytest.param("tom", "a123456a", id = "User<Tom>")])
def test_passwd_md5_id(user, passwd):
db = {
'jack': 'e8dc4081b13434b45189a720b77b6818',
'tom': '1702a132e769a623c1adb78353fc9503'
}
assert hashlib.md5(passwd.encode()).hexdigest() == db[user]
Fixture
固件:是一些函数,pytest会在执行函数之前或者之后加载运行它们,相当于预处理和后处理。
fixture的目的是提供一个固定基线,在该基线上测试可以可靠地、重复的执行。
名称:默认为定义时的函数名,可以通过 @pytest.fixture(name="demo") 给fixture重命名
定义:在固件函数定义前加上@pytest.fixture();fixture是有返回值的,没return则返回None
使用:作为参数、使用usefixtures、自动执行(定义时指定autouse参数)
def test_demo(fixture_func_name)
@pytest.mark.usefixtures("fixture_func_name1", "fixture_func_name2") 标记函数或者类
预处理和后处理:用yield关键词,yield之前的代码是预处理,之后的是后处理
作用域:通过scope参数控制作用域
function:函数级,每个测试函数都会执行一次(默认)
class:类级别,每个测试类执行一次,所有方法都共享这个fixture
module:模块级别,每个模块.py执行一次,模块中所有测试函数、类方法 或者 其他fixture 都共享这个fixture
session:会话级别,每次会话只执行一次,一次会话中所有的函数、方法都共享这个fixture
集中管理:使用文件conftest.py 集中管理,在不同层级定义,作用于在其所在的目录和子目录,pytest会自动调用
scope、yield、auto的使用
# scope、yield、auto使用
@pytest.fixture(scope = "function", autouse=True)
def function_scope():
pass
@pytest.fixture(scope = "module", autouse=True)
def module_scope():
pass
@pytest.fixture(scope = "session")
def session_scope():
pass
@pytest.fixture(scope = "class", autouse=True)
def class_scope():
pass
import time
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
@pytest.fixture(scope='session', autouse=True)
def timer_session_scope():
start = time.time()
print('\nsession start: {}'.format(time.strftime(DATE_FORMAT, time.localtime(start))))
yield
finished = time.time()
print('\nsession finished: {}'.format(time.strftime(DATE_FORMAT, time.localtime(finished))))
print('session Total time cost: {:.3f}s'.format(finished - start))
def test_1():
time.sleep(1)
def test_2():
time.sleep(2)
'''
执行命令:pytest --setup-show -s
固件执行结果:
test_pytest_study.py
session start: 2020-04-16 17:29:02
SETUP S timer_session_scope
SETUP M module_scope
SETUP C class_scope
SETUP F function_scope
test_pytest_study.py::test_3 (fixtures used: class_scope, function_scope, module_scope, timer_session_scope).
TEARDOWN F function_scope
TEARDOWN C class_scope
SETUP C class_scope
SETUP F function_scope
test_pytest_study.py::test_4 (fixtures used: class_scope, function_scope, module_scope, timer_session_scope).
TEARDOWN F function_scope
TEARDOWN C class_scope
TEARDOWN M module_scope
session finished: 2020-04-16 17:29:05
session Total time cost: 3.087s
TEARDOWN S timer_session_scope
'''
使用文件conftest.py 集中管理
# conftest.py
# conding=utf-8
import pytest
@pytest.fixture()
def postcode():
print("执行postcode fixture")
return "010"
# test_demo.py
# coding=utf-8
import pytest
class TestDemo():
def test_postcode(self, postcode):
assert postcode == "010"
if __name__=="__main__":
pytest.main(["--setup-show", "-s", "test_demo.py"])
python test_demo.py
执行过程:
test_demo.py 执行postcode fixture
SETUP F postcode
test_demo.py::TestDemo::test_postcode (fixtures used: postcode).
TEARDOWN F postcode
# 如果整个文件都用一个fixture,可以用pytestmark标记
pytestmark = pytest.mark.usefixtures("login")
fixture参数化
固件参数化需要使用pytest内置的固件request,并通过 request.param 获取参数。
# test_demo.py
@pytest.fixture(params=[
("user1", "passwd1"),
("user2", "passwd2")
])
def param(request):
return request.param
@pytest.fixture(autouse=True)
def login(param):
print("\n登录成功 %s %s" %param)
yield
print("\n退出成功 %s %s" %param)
def test_api():
assert 1 == 1
'''
pytest -s -v test_demo.py
运行结果:
test_demo.py::test_api[param0]
登录成功 user1 passwd1
PASSED
退出成功 user1 passwd1
test_demo.py::test_api[param1]
登录成功 user2 passwd2
PASSED
退出成功 user2 passwd2
'''
assert
assert "h" in "hello"
assert 3==4
assert 3!=4
assert f()==4
assert 5>6
assert not xx
assert {"0", "1", "2"} == {"0", "1", "2"}
相关推荐
- windows10易升怎么用(微软windows10易升使用教程)
-
windows10易升是微软官方的。windows10易升是微软官方发布的升级助理或者叫升级助手(官方下载),帮助你升级到win10最新版本,同时也帮助Win7Win8.1用户升级到Windows1...
- 300兆光纤买什么路由器(300兆光纤买3000m的路由器有用吗)
-
对于300Mbps的网速,推荐选择支持AC750及以上的路由器型号。比如TP-LinkArcherC20、D-LinkDIR-816、NetgearR6020等,都是性价比不错的选择。此类路由...
- windows10产品密钥查询(查看windows10产品密钥)
-
要查看电脑上Windows10的产品密钥,你可以按照以下步骤进行操作:打开“开始”菜单,然后点击“设置”图标(齿轮状图标)。在“设置”窗口中,点击“更新和安全”选项。在左侧导航栏中,选择“激活”选项...
- 电脑总死机卡住不动怎么办(电脑老是死机卡住)
-
如果你的电脑经常卡死,而且只能强制关机,别忘了说明电脑这个配置不够造成的,你需要提高一下它的配置,比如说加一个内存条或者换一个固态硬盘,这样才能够正常运行,不然的话这种电脑是没有办法使用的,现在电脑都...
- win10自动修复死循环无法开机
-
答:1、请确保电脑有充足的电源供应,确保电源可以正常供电;2、检查U盘是否正常安装;3、检查是否有新的软硬件设备接入;4、运行chkdsk,检查硬盘并修复文件系统;5、检查Windows更新,如果存在...
-
- 查看台式电脑ip地址(查询台式电脑ip地址)
-
如何查看主机名和IP地址:右击我的电脑-属性-网络标识(win2000)/计算机名(winxp)-完整的计算机名称后面的就是你的主机名.右击网上邻居-,属性-右击本地连接-属性-双击INTERNET协议(tcp/ip)就可以看到自己的I...
-
2025-12-15 19:03 off999
- windows7 ultimate(windows7ultimate无法启动)
-
32位的。1、在下载操作系统镜像的时候,带有x86标识的一般是32位系统,指的是CPU地址总线是32位、fetch、decode解压指令时也按32位字长来进行。x64一般表示系统为64位。2、x86是...
- 雨林系统u盘安装步骤(雨林重装系统)
-
如果是ISO镜像那就刻盘安装,如果不想刻盘,就硬盘安装。问题又来了,大部分的都是GHOST的系统,还有就是纯安装版的。我只说一下GHOST的,先把ISO文件给解压了,然后里边会有占主要空间大小的.GH...
-
- 0xc000021a手动修复(修复0xc0000225)
-
出现这样的问题很常见,用以下方法及解决方案就可以解决1、错误代码0xc000021a表示用户模式子系统有所损坏。一般按照蓝屏提示重启系统,即可正常运行。2、如果重启没能解决,则建议通过“最后一次正确的配置”方式启动系统。3、如果系统文件被破...
-
2025-12-15 17:51 off999
-
- windows7网络驱动(win7网络驱动在哪个文件夹)
-
1.Networkcarddriver。2.右键我的电脑,点击“属性”,选择左侧“设备管理器”3.点击“网络适配器”,如果方框内没有驱动,请下载驱动精灵安装网卡驱动。在Windows7操作系统中,网络驱动程序的名称通常以网络适配器的品...
-
2025-12-15 17:03 off999
- diskgenius的功能介绍(diskgenius是什么)
-
先打开DiskGenius(如果系统打不开了,可以在PE下运行),在弹出分区工具Diskgenius工具中,依次点击“硬盘——重建主引导记录(MBR)”选项,无需理会弹出的提示窗口,直接按下“是”即可...
- 网速快但是打开网页慢(网速快但是打开网页慢怎么回事)
-
原因有很多,有可能是路由器的原因,也有可能是其他原因,总的来说,网速慢的常见原因有以下几种:1.wifi被人蹭网,别人占用了带宽或者给你限速了,可以登录路由器管理页面查看连接的设备数。2.路由器性能...
- windowsxp系统还能用吗(xp系统还能不能用)
-
xp系统还能用。但是微软不再为xp系统提供系统更新补丁程序,并且只能适用于以前的老电脑,使用新电脑以及配置高的用户还是选择win7及win10还有后续推出的win11更好。WindowsXP系统已经...
- 自己组装电脑好还是买整机好
-
自己组装电脑的优点是:1.可以根据自己的需求选择每个部件,比如选择更好的显卡、CPU等,从而获得更强的性能。2.自己组装电脑可以更好地了解电脑,如了解和解决问题。3.DIY电脑可以根据需要升级电...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
使用 python-fire 快速构建 CLI_如何搭建python项目架构
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
