pytest 获取测试用例执行结果

在用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更加合适。

参考:
https://stackoverflow.com/questions/35703122/how-to-detect-when-pytest-test-case-failed
https://pytest.readthedocs.io/en/2.7.3/plugins.html
https://stackoverflow.com/questions/14121657/how-to-get-test-name-and-test-result-during-run-time-in-pytest

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值