Pytest获取测试执行结果

        背景:有时候需要自定义测试报告或者将测试结果发送到企业微信群聊,这个时候需要对测试结果进行计算统计,但是对拿不到测试结果很苦恼,博主总结了一下两种方式。

方法一:使用pytest-json-report插件

首先下载依赖包

pip install pytest-json-report

1.将测试报告保存到json文件中

pytest.main([
        # '-q',  # 代表 "quiet",即安静模式,它可以将 pytest 的输出精简化,只输出测试用例的执行结果,而不会输出额外的信息,如测试用例的名称、执行时间等等
        '-vs',  # 指定输出用例执行信息,并打印程序中的print/logging输出
        'testCase/',  # 执行用例的目录    
        '--json-report', f'--json-report-file=to_path/report.json',  # 生成json报告,并指定存放位置
        ])

结果文件内容如下,其中summary就是测试用例的成功失败情况:

{"created": 1518371686.7981803, ..."environment": {"Python": "3.10.4",...},"summary": {"passed": 9, "total": 9, "collected": 9}, "tests":[{"nodeid": "test_foo.py", "outcome": "passed", ...}, ...]}

这样会将测试结果保存在该路径下的json文件中,这时候就可以使用该文件进行各种测试结果的统计计算了。

2.如果不想保存测试报告文件,也直接选择直接调用的方式(直接调用时,不能在pytest.main([])中加入--json-report参数,否则会导致冲突)

import pytest
from pytest_jsonreport.plugin import JSONReport
 
 
if __name__ == '__main__':
    plugin = JSONReport()
    pytest.main(['-s','testCase/'], plugins=[plugin])
 
    summary = plugin.report.get("summary")
    #得到通过,失败,跳过和总执行的用例数
    passed = summary.get("passed",0)
 
    failed = summary.get("failed",0)
 
    skipped = summary.get("skipped",0)
 
    total = summary.get("total",0)
 
    xfail = summary.get("xfailed", 0)
    
    xpass = summary.get("xpassed", 0)
    
    error = summary.get("error", 0)

方法二:不使用任何插件,通过在conftest文件中添加pytest_runtest_makereport(item, call)手动计算出结果

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):  # description取值为用例说明__doc__
    """获取测试结果、生成测试报告"""
    outcome = yield
    report = outcome.get_result()


    result_dir = BASE_DIR + '/outFiles/pytest_result'
    if not os.path.exists(result_dir):
        os.makedirs(result_dir, exist_ok=True)
    with open(result_dir + '/pytest_result.json', 'w', encoding='utf-8') as f:
        if report.when == 'call':
            if report.outcome == 'passed':
                pytest_result["case_pass"] += 1
            elif report.outcome == 'failed':
                pytest_result["case_fail"] += 1
            elif report.outcome == 'skipped':
                pytest_result["case_skip"] += 1
            elif report.outcome == 'error':
                pytest_result["case_error"] += 1
            elif report.outcome == 'xfailed':
                pytest_result["case_xfailed"] += 1
            elif report.outcome == 'xpassed':
                pytest_result["case_xpassed"] += 1
        if report.when == 'setup':
            if report.outcome == 'skipped':
                pytest_result["case_skip"] += 1
        pytest_result["case_count"] = pytest_result["case_pass"] + pytest_result["case_fail"] + pytest_result[
            "case_skip"] + pytest_result["case_error"]+pytest_result["case_xfailed"]+pytest_result["case_xpassed"]

        # 将用例执行结果写入文件
        f.write(f'{json.dumps(pytest_result)}')

以上两种方法都可以拿到测试结果,根据自己的需要使用

猜你喜欢

转载自blog.csdn.net/weixin_65784341/article/details/131049831