PyQt5+Python-docx实现一键生成测试报告

要使用 PyQt5 和 python-docx 实现一键生成测试报告,可以按照以下步骤进行。这个示例将创建一个简单的 PyQt5 应用程序,用户可以通过界面输入一些测试信息,然后点击按钮生成一个包含这些信息的 Word 文档作为测试报告。

图片[1]_PyQt5+Python-docx实现一键生成测试报告_知途无界

步骤概述

  1. 安装必要的库
  2. 创建 PyQt5 界面
  3. 集成 python-docx 生成 Word 报告
  4. 实现一键生成功能

1. 安装必要的库

首先,确保你已经安装了 PyQt5python-docx。你可以使用 pip 来安装它们:

pip install PyQt5 python-docx

2. 创建 PyQt5 界面

我们将创建一个简单的窗口,包含一些输入字段和一个生成报告的按钮。

import sys
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel,
    QLineEdit, QPushButton, QMessageBox
)
from docx import Document

class TestReportGenerator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("测试报告生成器")
        self.setGeometry(100, 100, 400, 300)

        # 创建主部件和布局
        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)
        self.layout = QVBoxLayout()

        # 添加输入字段
        self.add_input_field("测试项目名称:", "project_name")
        self.add_input_field("测试日期:", "test_date")
        self.add_input_field("测试人员:", "tester")
        self.add_input_field("测试环境:", "test_environment")

        # 添加测试结果描述
        self.description_label = QLabel("测试结果描述:")
        self.layout.addWidget(self.description_label)
        self.description_edit = QLineEdit()
        self.description_edit.setPlaceholderText("请输入测试结果的详细描述...")
        self.layout.addWidget(self.description_edit)

        # 添加生成按钮
        self.generate_button = QPushButton("生成测试报告")
        self.generate_button.clicked.connect(self.generate_report)
        self.layout.addWidget(self.generate_button)

        # 设置布局
        self.main_widget.setLayout(self.layout)

    def add_input_field(self, label_text, object_name):
        label = QLabel(label_text)
        self.layout.addWidget(label)
        line_edit = QLineEdit()
        line_edit.setObjectName(object_name)
        self.layout.addWidget(line_edit)

    def get_input_values(self):
        project_name = self.findChild(QLineEdit, "project_name").text()
        test_date = self.findChild(QLineEdit, "test_date").text()
        tester = self.findChild(QLineEdit, "tester").text()
        test_environment = self.findChild(QLineEdit, "test_environment").text()
        description = self.description_edit.text()
        return project_name, test_date, tester, test_environment, description

    def generate_report(self):
        # 获取输入值
        project_name, test_date, tester, test_environment, description = self.get_input_values()

        # 检查是否所有必填字段都已填写
        if not all([project_name, test_date, tester, test_environment, description]):
            QMessageBox.warning(self, "警告", "请填写所有必填字段!")
            return

        # 创建 Word 文档
        doc = Document()

        # 添加标题
        doc.add_heading('测试报告', level=1)

        # 添加基本信息
        doc.add_heading('基本信息', level=2)
        doc.add_paragraph(f'项目名称: {project_name}')
        doc.add_paragraph(f'测试日期: {test_date}')
        doc.add_paragraph(f'测试人员: {tester}')
        doc.add_paragraph(f'测试环境: {test_environment}')

        # 添加测试结果描述
        doc.add_heading('测试结果描述', level=2)
        doc.add_paragraph(description)

        # 保存文档
        file_path, _ = QFileDialog.getSaveFileName(self, "保存测试报告", "", "Word 文档 (*.docx)")
        if file_path:
            try:
                doc.save(file_path)
                QMessageBox.information(self, "成功", f"测试报告已成功保存到 {file_path}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存文件时出错: {str(e)}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TestReportGenerator()
    window.show()
    sys.exit(app.exec_())

注意: 上述代码中使用了 QFileDialog 来选择保存文件的路径,但未导入 QFileDialog。为了完整起见,需要在代码开头添加:

from PyQt5.QtWidgets import QFileDialog

3. 完整代码

以下是完整的代码,包括 QFileDialog 的导入:

import sys
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel,
    QLineEdit, QPushButton, QMessageBox, QFileDialog
)
from docx import Document

class TestReportGenerator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("测试报告生成器")
        self.setGeometry(100, 100, 400, 300)

        # 创建主部件和布局
        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)
        self.layout = QVBoxLayout()

        # 添加输入字段
        self.add_input_field("测试项目名称:", "project_name")
        self.add_input_field("测试日期:", "test_date")
        self.add_input_field("测试人员:", "tester")
        self.add_input_field("测试环境:", "test_environment")

        # 添加测试结果描述
        self.description_label = QLabel("测试结果描述:")
        self.layout.addWidget(self.description_label)
        self.description_edit = QLineEdit()
        self.description_edit.setPlaceholderText("请输入测试结果的详细描述...")
        self.layout.addWidget(self.description_edit)

        # 添加生成按钮
        self.generate_button = QPushButton("生成测试报告")
        self.generate_button.clicked.connect(self.generate_report)
        self.layout.addWidget(self.generate_button)

        # 设置布局
        self.main_widget.setLayout(self.layout)

    def add_input_field(self, label_text, object_name):
        label = QLabel(label_text)
        self.layout.addWidget(label)
        line_edit = QLineEdit()
        line_edit.setObjectName(object_name)
        self.layout.addWidget(line_edit)

    def get_input_values(self):
        project_name = self.findChild(QLineEdit, "project_name").text()
        test_date = self.findChild(QLineEdit, "test_date").text()
        tester = self.findChild(QLineEdit, "tester").text()
        test_environment = self.findChild(QLineEdit, "test_environment").text()
        description = self.description_edit.text()
        return project_name, test_date, tester, test_environment, description

    def generate_report(self):
        # 获取输入值
        project_name, test_date, tester, test_environment, description = self.get_input_values()

        # 检查是否所有必填字段都已填写
        if not all([project_name, test_date, tester, test_environment, description]):
            QMessageBox.warning(self, "警告", "请填写所有必填字段!")
            return

        # 创建 Word 文档
        doc = Document()

        # 添加标题
        doc.add_heading('测试报告', level=1)

        # 添加基本信息
        doc.add_heading('基本信息', level=2)
        doc.add_paragraph(f'项目名称: {project_name}')
        doc.add_paragraph(f'测试日期: {test_date}')
        doc.add_paragraph(f'测试人员: {tester}')
        doc.add_paragraph(f'测试环境: {test_environment}')

        # 添加测试结果描述
        doc.add_heading('测试结果描述', level=2)
        doc.add_paragraph(description)

        # 保存文档
        file_path, _ = QFileDialog.getSaveFileName(self, "保存测试报告", "", "Word 文档 (*.docx)")
        if file_path:
            try:
                doc.save(file_path)
                QMessageBox.information(self, "成功", f"测试报告已成功保存到 {file_path}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存文件时出错: {str(e)}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TestReportGenerator()
    window.show()
    sys.exit(app.exec_())

4. 功能说明

  • 界面布局: 使用 QVBoxLayout 垂直布局,依次添加标签和输入框。
  • 输入字段: 包括测试项目名称、测试日期、测试人员、测试环境以及测试结果描述。
  • 生成报告: 点击“生成测试报告”按钮后,程序会检查所有必填字段是否已填写。如果未填写完整,会弹出警告提示。如果填写完整,则创建一个新的 Word 文档,添加标题和基本信息,然后保存到用户指定的位置。
  • 错误处理: 如果保存文件时发生错误,会弹出错误提示。

5. 扩展功能

你可以根据需要扩展这个基础示例,例如:

  • 添加更多测试详情: 如测试用例、通过/失败情况、截图等。
  • 美化 Word 文档: 使用 python-docx 的样式功能,设置字体、颜色、表格等。
  • 多页报告: 如果测试结果较多,可以分页显示。
  • 数据导入: 从数据库或其他数据源导入测试结果,自动生成报告。

示例:添加测试用例表格

以下是如何在 Word 报告中添加一个简单的测试用例表格的示例:

# 在 generate_report 方法中,添加以下代码到描述之后

# 添加测试用例表格
doc.add_heading('测试用例', level=2)
table = doc.add_table(rows=1, cols=3)
table.style = 'LightShading-Accent1'  # 选择一个表格样式
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '用例编号'
hdr_cells[1].text = '用例描述'
hdr_cells[2].text = '结果'

# 示例数据
test_cases = [
    {"编号": "TC001", "描述": "登录功能测试", "结果": "通过"},
    {"编号": "TC002", "描述": "注册功能测试", "结果": "失败"},
    # 添加更多测试用例
]

for case in test_cases:
    row_cells = table.add_row().cells
    row_cells[0].text = case["编号"]
    row_cells[1].text = case["描述"]
    row_cells[2].text = case["结果"]

将上述代码添加到 generate_report 方法中的描述部分之后,可以生成包含测试用例表格的报告。

6. 运行程序

确保你已经安装了所需的库,并将上述代码保存为一个 Python 文件(例如 test_report_generator.py),然后在终端或命令提示符中运行:

python test_report_generator.py

这将启动 PyQt5 应用程序,你可以输入测试信息并生成 Word 格式的测试报告。

总结

通过结合 PyQt5 和 python-docx,你可以创建功能强大的测试报告生成工具。这个示例提供了一个基础框架,你可以根据具体需求进行扩展和定制,以满足不同的测试报告生成需求。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞67 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容