pytest使用allure生成测试报告

发布时间 2023-11-11 22:09:29作者: 搬砖在路上

安装:
pip install allure-pytest
使用:
修改pytest的ini文件:

指定allure报告文件和生成的测试文件目录:

在命令行中:
allure generate report/result --clean -o report/html
--clean是覆盖,如果这个目录已存在,就会覆盖,-o是指定生成的目录位置

在使用时,导入allure,然后给测试用例加上装饰器:@allure

title 可自定义标题
description 测试用例详细说明
feature 定义功能模块,往下是story
story 定义用户故事
serverity 定义用例级别,主要有blocker,critical,minor,normal,trivial等几种类型,默认是normal
allure.dynamic 动态设置相关配置

对于featurestory的效果,类似与一级标签与二级标签,在代码和报告中体现如下:

serverity 效果如下:

动态参数获取效果如下:

动态参数在用例内部使用效果如下:

        # allure
        # sheet名称 feature 一级标签
        allure.dynamic.feature(sheet_name)
        # 模块 story 二级标签
        allure.dynamic.story(case_model)
        # 用例id+接口名称 title
        allure.dynamic.title(case_id + case_name)
        # 请求url 请求类型 期望结果 实际结果描述 description
        desc = "<font color='red'>请求url:{} </font><Br />请求类型:{}<Br/>预期结果:{}<Br/>实际结果:{}".format(url, method, expect_result, res)
        allure.dynamic.description_html(desc)

使用subprocess自动生成测试报告:
定义方法:

def allure_report(result_path, html_path):
    allure_cmd = 'allure generate %s -o %s --clean' % (result_path, html_path)
    my_log().info('测试报告地址:%s' % html_path)
    try:
        subprocess.call(allure_cmd, shell=True)
    except:
        my_log().error('执行用例失败,请检查测试环境相关配置')
        raise

在用例中指定allure的根目录,并设置对应result文件和HTML文件的路径:

if __name__ == '__main__':
    report_path = get_report_path() + os.sep + 'result'
    report_html_path = get_report_path() + os.sep + 'html'
    pytest.main(['-s', 'test_excel_case.py','--alluredir',report_path])
    Base.allure_report(report_path,report_html_path)

get_report_path如下: