RobotFramework自定义测试报告制作及Python脚本运行入门求助
先搞懂Robot报告的基本逻辑
Robot默认通过rebot工具解析output.xml生成报告/日志,自定义报告最简单的方式是修改内置的HTML模板,新手不用搞复杂的Python脚本生成,先从改模板入手。
一、分步实现自定义报告
1. 导出默认报告模板
先把Robot自带的报告模板导出到本地,方便修改:
python -m robot.libdoc --report template > report_template.html
执行后会在当前目录生成report_template.html,这就是我们要修改的基础模板。
2. 加自定义Logo
打开report_template.html,找到页面最顶部的标题区域(一般是<h1>标签所在的块),插入你的Logo代码:
<!-- 放在页面头部,标题上方 --> <div style="text-align: center; margin-bottom: 20px;"> <img src="my_logo.png" alt="公司/项目Logo" style="width: 160px; height: auto;"> </div>
注意:把my_logo.png和最终生成的报告放在同一目录,或者写绝对路径(比如/home/user/logo.png)。
3. 显示Set Test Message的自定义文本
默认报告里,测试用例的详情页才会显示Set Test Message的内容,要是想在列表页直接看到,找到模板里循环测试用例的代码块(一般是{% for test in tests %}开头的部分),修改状态列的代码:
<!-- 替换原来的状态显示代码 --> <td class="status {{ test.status.lower() }}"> <span style="font-weight: bold;">{{ test.status }}</span> {% if test.message %} <br><small style="color: #555; font-size: 0.9em;">{{ test.message }}</small> {% endif %} </td>
这样每个测试用例的状态下方会直接显示你设置的自定义消息。
4. 美化页面样式
直接修改模板里的<style>块,替换成你喜欢的样式,比如:
/* 全局样式调整 */ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 1200px; margin: 20px auto; padding: 0 20px; color: #333; } /* 测试用例状态样式优化 */ .passed { background-color: #f0f8f2; color: #2d6a4f; padding: 6px 12px; border-radius: 6px; display: inline-block; } .failed { background-color: #ffe6e6; color: #7f1d1d; padding: 6px 12px; border-radius: 6px; display: inline-block; } /* 表格样式优化 */ table { border-collapse: separate; border-spacing: 0; width: 100%; margin-top: 20px; } th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; } th { background-color: #f8f9fa; font-weight: 600; }
可以根据自己的审美调整颜色、字体、间距,不用太复杂,看着舒服就行。
5. 用自定义模板生成报告
测试执行完(生成output.xml后),用rebot指定模板生成报告:
rebot --reporttemplate report_template.html output.xml
执行后就会生成你自定义的report.html了。
二、测试完成后运行Python文件的方法
测试跑完之后,运行Python脚本很简单:
1. 直接运行脚本
打开终端,进入Python文件所在的目录,执行:
# Python2环境 python your_script.py # Python3环境(大部分情况用这个) python3 your_script.py
2. 结合Robot测试结果运行脚本
如果你的Python脚本需要处理Robot的测试结果(比如统计通过率、提取失败用例),可以用Robot自带的ExecutionResult类解析output.xml,示例代码:
from robot.api import ExecutionResult def process_robot_result(): # 读取测试结果文件 result = ExecutionResult('output.xml') passed_count = 0 failed_count = 0 # 遍历所有测试用例 for suite in result.suites: for test in suite.tests: print(f"用例名称:{test.name} | 状态:{test.status} | 消息:{test.message}") if test.status == 'PASS': passed_count +=1 else: failed_count +=1 print(f"\n测试总结:通过{passed_count}个,失败{failed_count}个") if __name__ == '__main__': process_robot_result()
把代码保存为process_result.py,测试完成后直接运行就行:
python3 process_result.py
新手扩展小提示
- 要是觉得手动改模板麻烦,可以试试第三方库
robotframework-customreport,用pip install robotframework-customreport安装后,直接用命令生成带自定义元素的报告,但新手还是先手动改模板,能搞懂底层逻辑。 - 样式优化可以用本地的前端框架文件(比如Bootstrap),下载CSS文件到本地后,在模板的
<head>里引入:
<link rel="stylesheet" href="./bootstrap.min.css">
这样不用外链也能快速美化页面。
内容的提问来源于stack exchange,提问作者codeforme

