日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

pytest?用例執行失敗后其他不再執行_python

作者:qq_37668510 ? 更新時間: 2023-04-10 編程語言

1.hook函數介紹

在執行用例時,遇到用例之前存在有關聯,用例執行失敗后,其余用例也沒有必要再去執行(比如:登錄失敗后,我的列表、我的訂單等用例就沒有比必要執行了)。

完成這個功能我們只要學習pytest給我們提供的兩個Hook函數:

  • pytest_runtest_setup :在執行測試之前執行,類似unittest中的setup方法。
  • pytest_runtest_makereport:測試報告鉤子函數,打印有關測試運行的信息。

2.pytest_runtest_setup

方法只有一個參數item,不需要手動傳遞,pytest會自動的將所需內容傳入給這個方法。
item:主要記錄了用例的名稱、所在模塊、所在類名、文件路徑等信息。

介紹一下item中不太明確的參數:

keywords:當前用例被mark標記的名稱。
- 例如@pytest.mark.somke:keywords == somke

cls:當前用例的類名稱。

3.pytest_runtest_makereport

方法有兩個參數itemcall,item參數與上面一樣的。
參數call :用于了記錄執行過程、測試報告等信息。

call 中的參數介紹:

when:記錄測試用例運行的狀態,總共三個狀態:
- setup:用例“執行前”。
- call:用例"執行中"。
- teardown:用例"執行完成"。

excinfo:如果用例執行失敗,會記錄在這里。

4.解決思路

通過上面的分析,可以得到一個簡單的思路,就是:在每個測試用例執行之前,判斷當前用例所在的類是否有失敗的用例,如果有就使用pytest.xfail標記為失敗的用例,不再執行。

步驟:
1. 定義一個全局變量。
2. 自定一個mark標記,將用例之間有耦合性的用例標記出來(可以通過這個來控制是否需要)。
3. 添加失敗用例:用pytest_runtest_makereport hook函數中使用call中的excinfo信息判斷用例是否失敗,如果失敗就將用例添加到全局變量中。
4. 在用例執行前判斷是否有失敗用例:用pytest_runtest_setuphook函數中實現判斷當前用例所在的類是否有失敗的用例。

實現代碼:
當前代碼最好在conftest.py文件中實現。

# conftest.py

from typing import Dict, Tuple
import pytest

# 全局變量,記錄失敗的用例
_test_failed_incremental: Dict[str, Dict[Tuple[int, ...], str]] = {}


def pytest_runtest_makereport(item, call):
    # 判斷用例執行失敗后是否需要跳過
    if "incremental" in item.keywords:
    	# 如果用例失敗,添加到全局變量中
        if call.excinfo is not None:
            cls_name = str(item.cls)
            parametrize_index = (
                tuple(item.callspec.indices.values())
                if hasattr(item, "callspec")
                else ()
            )
            test_name = item.originalname or item.name
            _test_failed_incremental.setdefault(cls_name, {}).setdefault(
                parametrize_index, test_name
            )


def pytest_runtest_setup(item):
	# 判斷用例執行失敗后是否需要跳過
    if "incremental" in item.keywords:
        cls_name = str(item.cls)
        # 判斷當前用例的類是否在全局變量中
        if cls_name in _test_failed_incremental:
            parametrize_index = (
                tuple(item.callspec.indices.values())
                if hasattr(item, "callspec")
                else ()
            )
            test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
            # 如果當前類中的用例存在失敗用例,就跳過
            if test_name is not None:
                pytest.xfail("previous test failed ({})".format(test_name))

測試代碼:

@pytest.mark.incremental
class TestAdd:

    def test_01(self):
        print('test_01 用例執行中...')

    
    def test_02(self):
        pytest.xfail('以后的用例都失敗了0')

    def test_03(self):
        print('test_03 用例執行中...')
        
if __name__ == "__main__":
    pytest.main()

結果:
test_01用例執行成功,
test_02失敗,
test_03跳過。

原文鏈接:https://blog.csdn.net/qq_37668510/article/details/125232006

欄目分類
最近更新