2.8 allure报告定制

该Python脚本(`main.py`)主要用于在不同的环境(dev,test,prd)下运行测试,使用MD5校验过滤并创建测试用例文件,执行pytest生成allure报告。之后,它会从`resource`目录复制文件到报告目录,覆盖原有的报告文件,最后打开allure报告进行查看。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description展示响应部分
Parameters展示请求部分

效果如下

 main.py运行时把resource目录中的文件复制一份,替换报告中的文件

地址:https://github.com/wxwcd/allure_report

resource目录内容如下

 

 main.py

import os
from config.config import setting
from utils.template import Template
from utils.md5 import Md5
import pytest
from utils.type_check import CheckType
import shutil
from utils.delete import del_files


def run():
    data = os.listdir('data')
    m = Md5('case', 'log', 'case_md5.json')
    n = Md5('utils', 'log', 'template_md5.json')
    filter_list = m.filter()
    utils_list = n.filter()
    if 'template.py' not in utils_list:
        filter_list = []
        n.write_md5()
    for i in data:
        file_path = 'data' + '/' + i
        if os.path.isfile(file_path):
            temp = 'test_' + i
            if temp not in filter_list:
                Template.create_test_file(file_path, 'case')
    m.write_md5()


if __name__ == "__main__":
    import sys

    CheckType.check('data', Template)
    if sys.argv[1] == 'dev':
        setting['baseUrl'] = setting['dev']
    elif sys.argv[1] == 'test':
        setting['baseUrl'] = setting['test']
    elif sys.argv[1] == 'prd':
        setting['baseUrl'] = setting['prd']
    else:
        raise Exception("the command must be like 'python main.py dev | test | prd'")
    run()
    del_files('results')
    pytest.main(['-s', '--alluredir=results'])
    os.system('allure generate --clean ./results/ -o ./report/')
    for file_name in os.listdir('resource'):
        src_file = os.path.join('resource', file_name)
        dst_file = os.path.join('report', file_name)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, 'report')
    os.system('allure open -h 127.0.0.1 -p 8883 ./report/')

utils/delete.py

import os


def del_files(dir_path: str):
    if os.path.exists(dir_path):
        for filename in os.listdir(dir_path):
            filepath = os.path.join(dir_path, filename)
            try:
                if os.path.isfile(filepath):
                    os.unlink(filepath)
            except Exception as e:
                print(f"Error deleting {filepath}: {e}")

### Pytest Allure 报告定制方法 #### 1. 配置 `tox.ini` 文件 为了生成自定义的 Allure 报告,可以在项目的根目录下创建或修改 `tox.ini` 文件。通过设置 `addopts` 参数来指定运行选项以及报告存储路径。 以下是配置示例: ```ini [tox] envlist = py38 [testenv] deps = pytest allure-pytest commands = pytest {posargs} [pytest] addopts = -s --alluredir=c:/data/report ``` 上述配置指定了 `-s` 表示显示打印输出,而 `--alluredir` 则用于指定 Allure 报告的 JSON 数据保存位置[^3]。 --- #### 2. 使用标记 (`mark`) 进行测试用例筛选 可以通过 `pytest.mark` 对不同的测试用例进行分类,并利用命令行参数控制哪些用例会被执行。例如: ```python import pytest @pytest.mark.smoke def test_smoke_case(): print('这是冒烟测试用例') assert True @pytest.mark.regression def test_regression_case(): print('这是回归测试用例') assert False ``` 如果只想运行带有特定标签(如 `smoke`)的测试用例,则可以使用如下命令: ```bash pytest -m smoke -s --alluredir=./report ``` 此命令仅运行被标注为 `smoke` 的测试用例并生成对应的 Allure 报告数据[^1]。 --- #### 3. 自定义测试步骤描述 Allure 提供了装饰器支持更详细的测试步骤记录。这有助于提升报告可读性和调试效率。例如: ```python import allure import pytest @allure.step("加法操作: {a} + {b}") def add(a, b): return a + b class TestMathOperations: @allure.title("验证两个正数相加的结果") def test_positive_numbers(self): result = add(3, 4) with allure.step(f"断言结果等于{result}"): assert result == 7 @allure.title("验证负数与正数相加的结果") def test_negative_and_positive(self): result = add(-3, 4) with allure.step(f"断言结果等于{result}"): assert result == 1 ``` 以上代码片段展示了如何通过 `@allure.step` 和 `with allure.step` 来增强测试过程中的日志记录[^2]。 --- #### 4. 添加附件到报告 有时可能希望将截图或其他文件附加到 Allure 报告中以便于分析失败原因。可通过以下方式实现: ```python import allure import pytest def attach_screenshot(file_path): allure.attach.file( file_path, name="屏幕截图", attachment_type=allure.attachment_type.PNG ) def test_with_attachment(): screenshot_path = "/path/to/screenshot.png" try: # 执行某些逻辑... assert False except AssertionError as e: attach_screenshot(screenshot_path) raise e ``` 当该测试用例失败时,所附带的图片将会展示在最终生成的 HTML 报告中。 --- #### 5. 生产环境下的报告发布流程 完成本地测试后,通常还需要将生成的 Allure 报告上传至服务器供团队成员查看。一般做法是先安装 Allure 命令行工具,再执行转换脚本: ```bash # 将JSON/XML格式的数据转化为HTML页面 allure generate c:/data/report -o ./html_report --clean # 启动服务预览效果 allure open ./html_report ``` 最后还可以借助 CI/CD 工具链自动部署这些静态资源到内部网站上。 --- ### 总结 综上所述,通过对 `pytest` 插件灵活运用及合理调整项目结构,能够轻松构建出满足需求的高度定制化的 Allure 测试报告系统。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值