前言
- pytest默認按字母順序去執行的(小寫英文--->大寫英文--->0-9數字)
- 用例之間的順序是文件之間按照ASCLL碼排序,文件內的用例按照從上往下執行。
- setup_module->setup_claas->setup_function->testcase->teardown_function->teardown_claas->teardown_module
- 可以通過第三方插件
pytest-ordering
實現自定義用例執行順序 - 官方文檔: https://pytest-ordering.readthedocs.io/en/develop/
- 注意:一旦設置了自定義的執行順序,就必須得延伸
@pytest.mark.run(order=1)
里面得order
字段
代碼實現
安裝插件
pip install pytest-ordering
目錄結構
- 為了演示,新建了個項目,目錄結構。
- 新建用例必須嚴格遵守pytest的規范創建。
# test_login.py
def test_login02():
assert 1 == 1
def test_login01():
assert True
# test_project.py
def test_01():
assert True
# test_three.py
def test_02():
assert True
執行結果
- 用例執行順序:test_three.py > testLogin/test_login.py > testProject/test_project
- 在.py文件內是從上往下執行,不管大小排序。
pytest-ordering
使用
方式一
- 第一個執行:
@ pytest.mark.first
- 第二個執行:
@ pytest.mark.second
- 倒數第二個執行:
@ pytest.mark.second_to_last
- 最后一個執行:
@pytest.mark.last
方式二
- 第一個執行:
@ pytest.mark.run('first')
- 第二個執行:
@ pytest.mark.run('second')
- 倒數第二個執行:
@ pytest.mark.run('second_to_last')
- 最后一個執行:
@ pytest.mark.run('last')
方式三
- 第一個執行:
@ pytest.mark.run(order=1)
- 第二個執行:
@ pytest.mark.run(order=2)
- 倒數第二個執行:
@ pytest.mark.run(order=-2)
- 最后一個執行:
@ pytest.mark.run(order=-1)
以上三種方式可以自行嘗試,以下情況需要特別注意,我們就那上面的文件舉例說明。
# test_login.py
@pytest.mark.run(order=1)
def test_login02():
assert 1 == 1
@pytest.mark.run(order=2)
def test_login01():
assert True
# test_project.py
@pytest.mark.run(order=1)
def test_01():
assert True
# test_three.py
def test_02():
assert True
已經改變了用例執行規則,針對於是全局的,會先執行完@pytest.mark.run(order=1)
才會執行order=2
的用例
其實總體來說,這個插件的實用場景不是很多,如果需要指定某個用例第一個執行和最后執行,可以用該插件實現。
如果要按照你指定的順序執行下去,需要在每個用例前都加上@pytest.mark.run(order=1)
,其中order中的數字
需遞增。