allure report 报告中文化及其它优化

文章讲述了对Allure报告的改进,包括中文显示的优化、不常用模块的隐藏、常用特性和环境的调整,以及如何通过代码修改报告的语言设置和动态获取环境信息。
摘要由CSDN通过智能技术生成

1. 效果对比

原来的报告:英文显示、趋势等不常使用、特性场景排名靠后、环境显示未空等;
现在的报告:中文显示更加友好、隐藏趋势这种不常用的模块、将常用的特性场景安排到前面、环境补充完毕并实现动态获取;

原报告展示如图:
在这里插入图片描述

现报告展示如图:
在这里插入图片描述

2. 代码运行

run.py

----> 插入点a
# 生成报告
os.system("allure generate ./temp/html -o ./report")

----> 插入点b
# 打开报告
os.system('allure open ./report')

2. 报告修改

2.1 中文修改

思路:在报告生成后,在里面添加修改中文的js文件即可。也就是在生成好的测试报告中的index.html 文件内容在"script src=“app.js”></script" 上一行插入以下js代码。

2.1.1 settings.js 中文修改文件

新建 settings.js,将其放到项目文件下:

// 尝试从 localStorage 中获取 ALLURE_REPORT_SETTINGS 的值
let allureSettings = JSON.parse(localStorage.getItem('ALLURE_REPORT_SETTINGS'));
if (allureSettings) {
    // 如果能获取到值,则修改 language 属性为 "zh"
    allureSettings.language = "zh";
} else {
    // 如果获取不到值,则创建一个新对象并设置默认值
    allureSettings = {
        "language": "zh",
        "sidebarCollapsed": false,
        "sideBySidePosition": [46.83064516129034, 53.16935483870967]
    };
}
// 将修改后的对象或新创建的对象存储回 localStorage
localStorage.setItem('ALLURE_REPORT_SETTINGS', JSON.stringify(allureSettings));
console.log("当前设置", JSON.stringify(allureSettings));

2.1.2 fix_report.py 报告修改工具类

新建 fix_report.py ,将上面写好的 settings.js 复制到生成的报告目录中,并插入到index.html中:

def operate_key(aim_file, aim_key, new_key, aim_type):
    """
    :param aim_file: 目标文件
    :param aim_key: 目标关键字
    :param new_key: 需要替换成
    :param aim_type: 需要使用关键字做什么
    """
    # 打开文件
    with open(aim_file, 'r+', encoding="utf-8") as f:
        # 读取当前文件的所有内容
        all_the_lines = f.readlines()
        f.seek(0)
        f.truncate()
        # 循环遍历每一行的内容
        for line in all_the_lines:
            need_write = True
            # 如果目标关键字包含在line中
            if aim_key in line:
                match aim_type:
                    case "replace_key":
                        # 则替换line为new_line
                        f.write(line.replace(aim_key, new_key))   # 替换关键词
                        need_write = False
                    case "replace_line":
                        f.write(line.replace(line, new_key + '\n'))  # 替换关键句
                        need_write = False
                    case "insert_line":
                        f.write(new_key + '\n')  # 在找到的位置插入新标签,并且仅当需要插入时
                        f.write(line)
                        need_write = False
            if len(all_the_lines) and need_write:
                f.write(line)
        # 关闭文件
        f.close()


if __name__ == '__main__':
    aim_index = os.path.join(项目地址, 'report', 'index.html')    # 找到'index.html'所在处
    tag_to_find = '<script src="app.js"></script>'              # 找到"app.js"这一行
    # 修改中文
    aim_settings = os.path.join('settings.js')  # 找到保存的'settings.js'文件
    os.system(f"cp {aim_settings} {项目地址, 'report')}")   # 复制一份'settings.js'文件到'report'目录下
    operate_key(aim_index, tag_to_find, '<script src="settings.js"></script>', "insert_line")  # 插入 到"app.js" 前面

在这里插入图片描述

run.py 修改报告

run.py中,在生成报告之后,打开报告之前,运行 fix_report.py即可:

----> 插入点a
# 生成报告
os.system("allure generate ./temp/html -o ./report")
# 修改报告
os.system(f"python {os.path.join(项目地址, 'fix_report.py')}")
# 打开报告
os.system('allure open ./report')

2.2 报告首页标题修改

在这里插入图片描述

2.2.1 fix_report.py 报告修改工具类

    # 修改标题
    aim_summary = os.path.join(项目地址, 'report', 'widgets', 'summary.json')
    operate_key(aim_summary, "Allure Report", "报告首页标题修改", "replace_key")

在这里插入图片描述

2.3 报告窗口标题修改

在这里插入图片描述

2.3.1 fix_report.py 报告修改工具类

    # 修改浏览器窗口标题
    operate_key(aim_index, "Allure Report", "报告窗口标题修改", "replace_key")

在这里插入图片描述

2.4 环境和运行器动态获取与显示

思路:老版本的allure可以采用allure.environment(blog=‘https://www.cnblogs.com/xyztank/’);
新版本有两种办法:report目录下添加 environment.properties 文件 或者 environment.xml
这里使用的是添加 environment.properties 文件,并使用operate_key方法动态更改里面的内容。
如果在生成之后,打开之前生成environment.properties,则会不生效,所以必现在生成报告之前添加。

2.4.1 environment.properties 环境文件

新建environment.properties文件放到项目下,里面放一些预设的参数,便于后期动态修改。

systemVersion=win10
pythonVersion=3.7.0
allureVersion=2.13.15
projectLocation=projectName
author=operateName

2.4.2 fix_report_before.py 报告修改前置工具类

addopts = -v -s --alluredir ./temp/html 命令行执行的是这个,所以复制到html目录下,注意不同项目--alluredir地址可能存在区别。

    # 获取测试环境
    aim_environment = os.path.join(项目地址, 'environment.properties')
    copy_environment = os.path.join(项目地址, 'temp', 'html', 'environment.properties')
    os.system(f"cp {aim_environment} {copy_environment}")

    environment_info = {
        "systemVersion": platform.system().lower(),
        "pythonVersion": get_cmd_value("python --version"),   // get_cmd_value 用于获取命令行传回的值
        "allureVersion": get_cmd_value("allure --version"),
        "author": get_cmd_value("git config user.name"),
        "projectLocation": os.getcwd()
    }
    for key in environment_info:
        operate_key(copy_environment, key, f"{key} = {environment_info[key]}", "replace_line")
2.4.3 executor.json 运行器文件

默认的 Allure 测试报告也不显示 Executor,这是因为 Executor 通常是由 Builder 自动生成的,比如通过 Jenkins pluginAllure Jenkins Plugin 来生成。

{
  "name": "operateName",
  "type": "jenkins",
  "buildOrder": 3,
  "buildName": "Email",
  "buildUrl": "xxx.html",
  "reportName": "iTesting Allure Report"
}

2.4.4 fix_report_before.py 报告修改前置工具类

    # 添加作者信息
    aim_executor = os.path.join(项目地址, 'Commons', 'report_tools', 'executor.json')
    copy_executor = os.path.join(项目地址, 'temp', 'html', 'executor.json')
    os.system(f"cp {aim_executor} {copy_executor}")

    operate_key(copy_executor, "name", f'  "name": "{environment_info["author"]}",', "replace_line")

    buildName = get_cmd_value("git config user.email")
    operate_key(copy_executor, "buildName", f'  "buildName": "{buildName}",', "replace_line")

2.4.5 run.py 修改报告

run.py中,在生成报告之前,运行 fix_report_before.py即可;

2.5 报告首页显示优化

思路:直接改报告内容app.js不太好操作,所以选择在报告生成之后,动态获取到首页显示的元素,进行隐藏和切换操作。还得注意时机,需要在首次打开,和页面切换的资源加载完成之后进行修改。

2.5.1 contents.js report首页展示优化

新建contents.js , 放到项目目录下,在fix_report.python 中复制这个文件,并添加到index.js中:

let SwitchWindow = false;          // 是否是从其他界面切换到该界面

// 首次加载
window.addEventListener('load', function() {
    console.log("load, 优化首页显示!");
    changeContents()
});


// 页面切换时
window.addEventListener('popstate', function(event) {
    focus_window = document.location.href
    console.log('当前URL为:', focus_window);           // 当前窗口的url
    if (focus_window.endsWith("index.html#")) {
        let intervalId = null;       // 定时运行器,设置20毫秒判断一次
        let timeoutId = null;        // 超时运行器,设置5s为超时时间
        if (SwitchWindow) {          // 如果当前窗口为首页,并且是从其他页面切换过程的,则执行
            SwitchWindow = false;
            intervalId = setInterval(function() {
                if (document.getElementsByClassName('widget island').length > 0) {
                    console.log("popstate, 优化首页显示!");
                    clearInterval(intervalId);
                    clearTimeout(timeoutId);
                    changeContents()
                }
            }, 20); // 20毫秒
            timeoutId = setTimeout(function() {
                // 如果超过5秒仍未满足条件,清除间隔并执行超时操作
                console.log("超时!");
                clearInterval(intervalId);
            }, 5000); // 5秒
       }
   } else {
       SwitchWindow = true;
   }
});


function changeContents(){
    /*
    原来首页的布局:左边:汇总0、测试套1、环境2、特性场景3;右边:趋势4、类别5、运行器6;
    现在首页的布局:左边:汇总0、特性场景3、测试套1、     右边:运行器6、环境2、类别5;
    */
    var environmentDiv = document.getElementsByClassName('widget island');
    console.log(environmentDiv);
    console.log(environmentDiv.length);

    environmentDiv[4].style.display = 'none';  // 趋势只是隐藏了,并没有消失

    //  0, 1, 2, 3 / *, 5, 6
    //=>0, 2, () / *, 5, 6   (3, 1)  将第二位的1和第四位的3,拉出来互换
    //=>0, 2, 3, 1 / *, 5, 6         重新将3和1放到原来3的位置
    swapElementsByClass(environmentDiv[1], environmentDiv[3]);

    //=>0, 2, 3, 1 / *, 5, 6
    //=>0, 3, 1/ *, 5, ()   (6, 2)  将第二位的2和第七位的6,拉出来互换
    //=>0, 3, 1/ *, 5, 6, 2         重新将6和2放到原来6的位置
    swapElementsByClass(environmentDiv[1], environmentDiv[6]);

    swapElementsByClass(environmentDiv[4], environmentDiv[5]);
    swapElementsByClass(environmentDiv[5], environmentDiv[6]);
}

function swapElementsByClass(div1, div2){
    // 将div1, div2拉到外面互换,再放回div2的位置上
    // 创建一个临时位置用于交换
    let tempDiv = document.createElement('div');
    document.body.appendChild(tempDiv);
    // 将 div1 移动到 tempDiv 的位置
    tempDiv.appendChild(div1);
    // 交换 div1 和 div2 的位置
    div2.parentNode.insertBefore(div1, div2);
    // 将 div2 移动到原来 div1 的位置
    div1.parentNode.insertBefore(div2, div1);
    // 最后,移除临时 div
    document.body.removeChild(tempDiv);
}

参考

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值