ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Pytest框架 — 14、Pytest的标记(五)(控制测试用例执行顺序)
[打印本页]
作者:
飞不高
时间:
2022-9-16 17:20
标题:
Pytest框架 — 14、Pytest的标记(五)(控制测试用例执行顺序)
目录
1、前言
2、使用
3、标记最先执行和最后执行
1、前言
在执行自动化测试时,我们通常都希望能够控制执行测试用例的顺序。
在unittest框架中默认按照ACSII码的顺序加载测试用例并执行,顺序为:0~9、A~Z、a~z,测试目录、测试模块、测试类、测试方法/测试函数都按照这个规则来加载测试用例。
在pytest测试框架中,默认从上至下执行,也可以通过pytest-ordering插件来自定义执行顺序。
安装方式:
pip install pytest-ordering
2、使用
直接在要控制顺序的测试用例上使用@pytest.mark.order(order=顺序值)装饰器来标记执行顺序。
示例:
import pytest
@pytest.mark.run(order=4)
def test_pay():
print("第四步:支付订单")
@pytest.mark.run(order=2)
def test_add_cart():
print("第二步:加入购物车")
@pytest.mark.run(order=1)
def test_login():
print("第一步:登录")
@pytest.mark.run(order=3)
def test_place_order():
print("第三步:下订单")
"""
执行结果
mark/ordering/pytest_ordering.py::test_login 第一步:登录
PASSED
mark/ordering/pytest_ordering.py::test_add_cart 第二步:加入购物车
PASSED
mark/ordering/pytest_ordering.py::test_place_order 第三步:下订单
PASSED
mark/ordering/pytest_ordering.py::test_pay 第四步:支付订单
PASSED
"""
复制代码
注意:
@pytest.mark.run()必须以order=顺序值这种形式传递顺序值
order值可以为正数或负数,但遵从值越小优先级越高原则
当order值混用正负数时,采用正数的优先级更高
没有标记顺序的用例优先级高于标记为负数的用例
3、标记最先执行和最后执行
可以通过@pytest.mark.firt和@pytest.mark.last来标记用例的最先执行和最后执行。
示例:
import pytest
@pytest.mark.first
def test_login():
print("登录")
@pytest.mark.last
def test_logout():
print("注销")
def test_place_order():
print("下单")
def test_pay():
print("支付")
"""
执行结果
mark/ordering/order_first_and_last.py::test_login 登录
PASSED
mark/ordering/order_first_and_last.py::test_place_order 下单
PASSED
mark/ordering/order_first_and_last.py::test_pay 支付
PASSED
mark/ordering/order_first_and_last.py::test_logout 注销
PASSED
"""
复制代码
提示:
当我们在使用@pytest.mark.first和@pytest.mark.last装饰器时,python会把first和last当成自定义标记,从而出现如下提示
PytestUnknownMarkWarning: Unknown pytest.mark is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/mark.html
@pytest.mark.last
复制代码
此时我们可以在命令行中添加-p no:warnings来屏蔽错误提示。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4