pytest 獲取測試用例執行結果
阿新 • • 發佈:2019-02-09
在用pytest執行測試用例的時候,有時需要根據用例執行的結果,做一些其他的操作,比如:在用selenium做自動化測試的時候,如果用例執行失敗,需要截圖,方便以後排查原因:
方法1:
from _pytest.runner import runtestprotocol
from _pytest.runner import pytest_runtest_makereport
def pytest_runtest_protocol(item):
reports = runtestprotocol(item)
for report in reports:
if report.when == 'call':
if report.outcome == 'failed':
if browser_option.screen_shot:
report_dir = browser_option.report_dir
picture_name = item.name + '.png'
picture_path = join(report_dir, picture_name)
context.browser.save_screenshot(picture_path)
方法2:
from _pytest.runner import runtestprotocol
from _pytest.runner import pytest_runtest_makereport
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, "rep_" + rep.when, rep)
if rep.when == 'call' :
if rep.failed:
if browser_option.screen_shot:
report_dir = browser_option.report_dir
picture_name = item.name + '.png'
picture_path = join(report_dir, picture_name)
context.browser.save_screenshot(picture_path)
方法1雖然也能獲取到中間結果,但是該方法由於呼叫了:runtestprotocol
,而導致同一個測試用例會被執行兩次,而方法2則不會,所以方法2更加合適。