一、用例排序
pytest中用例之間的順序默認是按文件名ASCLL碼排序,文件內的用例默認是按照從上往下順序執行。要改變用例的執行順序,可以安裝第三方插件pytest-ordering
實現自定義用例順序,由此可以解決用例的依賴問題。命令如下:
pip install pytest-ordering
按數字排序用法如下:
@pytest.mark.order
class TestMyCode:
@pytest.mark.run(order=1)
def test_order_001(self):
assert True
@pytest.mark.run(order=-2)
def test_order_002(self):
assert True
@pytest.mark.run(order=3)
def test_order_003(self):
assert True
二、用例依賴
在編寫用例時,有時候用例之前會有依賴,而解決用例之間的依賴關系,可以用到pytest-dependency
第三方插件,如果依賴的用例失敗,則后續的用例會被標識為跳過。所以需要注意的是被依賴的用例一定要先運行,否則后續的用例會直接跳過。
pip install pytest-dependency
示例:
@pytest.mark.dependency()
def test_login():
print("=========login=========")
assert True
@pytest.mark.dependency(depends=["login"], scope="session")
def test_dependency_001():
"""
module:作用范圍為當前文件
class:作用范圍為當前類中
package:作用於當前目錄同級的依賴函數,跨目錄無法找到依賴的函數
session:作用域全局,可跨目錄調用。但被依賴的用例必須先執行,否則用例會執行跳過
"""
assert True
三、fixtures
在同一個腳本內,可以利用fixture函數,解決用例依賴的問題。被依賴的用例,可以把它標注為fixture方法,操作為 @pytest.fixture()
。若被依賴的方法用的地方比較多,比如登陸操作,那么可以將 fixture方法,放在conftest腳本中。
class TestMyCode:
"""用例依賴"""
@pytest.mark.usefixtures("test_login")
@pytest.mark.parametrize("a", [1, 2, 3])
def test_fixture_005(self, a):
"""fixture函數在測試腳本文件中"""
assert a > 1
@pytest.fixture()
def test_login(self):
"""fixture函數在測試腳本文件中"""
print("==============test_login===============")
assert 1 == 1
conftest.py
文件
@pytest.fixture()
def login():
"""fixture函數在conftest腳本文件中"""
print("==============test_login===============")
測試用例:
import pytest
class TestMyCode:
"""用例依賴"""
@pytest.mark.usefixtures("login")
@pytest.mark.parametrize("a", [1, 2, 3])
def test_fixture_005(self, a):
"""fixture函數在測試腳本文件中"""
assert a > 1