【pytest】Hook 方法之 pytest_runtest_protocol:獲取將要執行的用例(item)及下一個測試用例(nextitem)

Hook 方法之 pytest_runtest_protocol:

pytest_runtest_protocol :
官方給的解釋是:爲給定的測試項目執行runtest_setup / call / teardown協議;

@hookspec(firstresult=True)
def pytest_runtest_protocol(item, nextitem):
    """...  
    """

pytest_runtest_protocol 是在每個測試用例執行之前調用一次,它接收兩個參數:

  • item :要執行的測試用例對象;
  • nextitem :預計的下一個測試用例對象;

獲取到當前要執行的測試用例及下一個測試用例:

先準備三條測試用例:

class TestDemoA:

    def test_A_001(self):
        pass

    def test_A_002(self):
        pass

    def test_A_003(self):
        pass
# conftest.py

import pytest
from pluggy import HookspecMarker

hookspec = HookspecMarker("pytest")

# 1. 調用鉤子方法,獲取到用例對象並賦值給全局變量
@hookspec(firstresult=True)
def pytest_runtest_protocol(item, nextitem):
    print()
    print('執行hook方法,將 item,nextitem 賦值全局變量')
    print('當前用例的對象', item)
    print('下一個用例的對象', nextitem)
    global Item, NextItem
    Item = item
    NextItem = nextitem

# 2. 創建一個 fixture,從全局變量的用例對象中獲取用例名
@pytest.fixture(autouse=True)
def print_fix():
    print()
    name = Item.name
    
    # 3. 注意,如果是最後一條用例執行前調用鉤子方法,那麼 NextItem 則是 None;
    if NextItem:
        next_name = NextItem.name
    else:
        next_name = None
    print('要執行用例的名稱:', name)
    print('預計下一個測試用例的名稱', next_name)

if __name__ == '__main__':
    pytest.main(['-s', '-q'])

執行結果:

 

pytest_runtest_protocol 相關的鉤子方法:

這三個鉤子方法都是在 pytest_runtest_protocol 之後調用,分別負責:調用用例的 setup,執行測試用例,調用測試用例 teardown,他們接收的參數也都是測試用例對象(item,  nextitem):

def pytest_runtest_setup(item):
    """ 在 "pytest_runtest_call(item)" 之前調用 """

def pytest_runtest_call(item):
    """ 調用並執行測試用例(item) """

def pytest_runtest_teardown(item, nextitem):
    """ 在 "pytest_runtest_call(item)" 之後調用 """

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章