默認情況下,pytest測試用例的執(zhí)行是順序是和collect的順序一致的鸡挠。而collect是按測試目錄中test開頭的文件名稱順序來的。
目錄結構.png
如上目錄結構搬男,不同測試文件的執(zhí)行順序是這樣的拣展。
執(zhí)行順序.png
在一個文件中,用例的執(zhí)行順序是從上到下的缔逛。這樣备埃,除了修改文件名稱,想要調整不同測試文件的測試函數(shù)的執(zhí)行順序似乎無從下手褐奴。好在按脚,pytest中有個hook函數(shù)pytest_collection_modifyitems就是派這個用處的。
不過已經(jīng)有人通過插件pytest-ordering實現(xiàn)了這個功能敦冬,詳細用法可以見鏈接中的文檔辅搬。這個插件代碼量不大,適合直接看源碼或者作為自己開始實現(xiàn)插件的參考脖旱。
在這個基礎上可以再自定義一些堪遂,比如根據(jù)不同場景更改用例執(zhí)行順序。
# conftest.py
import pytest
def pytest_collection_modifyitems(config, items):
""" 根據(jù)指定的mark參數(shù)場景萌庆,動態(tài)選擇case的執(zhí)行順序"""
for item in items:
scenarios = [
marker for marker in item.own_markers
if marker.name.startswith('scenarios')
and marker.name in config.option.markexpr
]
if len(scenarios) == 1 and not item.get_closest_marker('run'):
item.add_marker(pytest.mark.run(order=scenarios[0].args[0]))
# test_foo.py
import pytest
def test_1():
print(1)
@pytest.mark.scenarios_1(1)
def test_2():
print(2)
@pytest.mark.scenarios_2(3)
def test_3():
print(3)
@pytest.mark.scenarios_1(2)
@pytest.mark.scenarios_2(1)
def test_4():
print(4)
# test_bar.py
import pytest
@pytest.mark.scenarios_2(2)
def test_a():
print('a')
@pytest.mark.scenarios_1(3)
def test_b():
print('b')
def test_c():
print('c')
下面可以嘗試一下溶褪,使用不同的scenario,用例執(zhí)行順序也會改變践险。
>> pytest -m scenarios_1 -s