目錄
- 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來屏蔽錯誤提示,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/502382.html
標籤:Python
