一招将从xmind转换成excel格式的测试用例

import xmindparser
import xlwt, xlrd
from xlutils.copy import copy
from xlwt import Worksheet
from xmindparser import xmind_to_dict
import datetime
import os
import re
import traceback

# 当前时间戳
a = datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')
timestp = re.sub(r'-|:|\s', '', str(a))

# 根目录
base_dir = os.path.abspath(os.path.dirname(__file__))

# xmindparser配置
xmindparser.config = {
    'showTopicId': False,  # 是否展示主题ID
    'hideEmptyValue': True  # 是否隐藏空值
}


def traversal_xmind(root, rootstring, lisitcontainer, flag):
    try:
        # 判断数据是否是字典类型
        if isinstance(root, dict):
            print('root1:', root)
            # 如果这个字典的key中同时有title和topics,则可认为这个title有下级分支
            if 'title' in root.keys() and 'topics' in root.keys():
                traversal_xmind(root['topics'], str(rootstring), lisitcontainer, True)
            # 如果这个字典的key中有title且没有topics,则可认为这个title是最末端
            if 'title' in root.keys() and 'topics' not in root.keys():
                traversal_xmind(root['title'], str(rootstring), lisitcontainer, True)

        # 判断数据是否是列表类型
        elif isinstance(root, list):
            #
            flag = True
            # 遍历列表
            for sonroot in root:
                # sonroot只可能是dict类型
                # 如果这个字典的key中同时有title和topics,则可认为这个title有下级分支
                if flag:
                    if 'title' in sonroot.keys() and 'topics' in sonroot.keys():
                        traversal_xmind(sonroot['topics'], str(rootstring) + "!" + sonroot['title'], lisitcontainer,
                                        True)
                    # 如果这个字典的key中有title且没有topics,则可认为这个title是最末端
                    elif 'title' in sonroot.keys() and 'topics' not in sonroot.keys():
                        # # 判断蓝色感叹号标识(前置条件)是否存在
                        if 'makers' in sonroot.keys() and 'symbol-info' in sonroot['makers']:
                            case = str(rootstring) + "!" + root[0]['title'] + "!" + root[1]['title'] + "!" + \
                                   root[1]['topics'][0]['title']
                            # 如果有特殊标签,则改变flag状态
                            flag = False
                            traversal_xmind(case, case, lisitcontainer, flag)
                        else:
                            case = str(rootstring) + "!" + sonroot['title']
                            traversal_xmind(case, case, lisitcontainer, True)

        # 判断数据是否是字符串类型
        elif isinstance(root, str):
            # lisitcontainer.append(str(rootstring.replace('\n', '')))  # 此处是去掉一步骤多结果情况直接拼接
            lisitcontainer.append(str(rootstring))  # 此处是一步骤多结果时,多结果合并
            # print('lisitcontainer:', lisitcontainer)
    except:
        tips = 'xmind处理异常,请联系Dora!!!'
        # 输出异常信息
        traceback.print_exc()

# 将xmind中的每条用例提取出来,放入列表中,以逗号分隔
def get_case(root):
    rootstring = root['title']
    lisitcontainer = []
    traversal_xmind(root, rootstring, lisitcontainer, True)
    return lisitcontainer

# 写入第b行的用例数据内容
def write_sheet(Worksheet, b, organization,tomodoule,casename,precondition, casestep, expectresult,is_maoyan):
    '''
    功能解释:去掉用例中的换行符,写入一条用例到Excel中
    @param Worksheet: excel表对象
    @param b: 写入的数据在表中所处的行数
    @param casename: 用例名称
    @param casestep: 用例操作
    @param expectresult: 期望结果
    '''
    # 用例名称
    caseName = re.sub(r'\r\n', '', str(casename))
    # 用例步骤
    caseStep = re.sub(r'\r\n', '', str(casestep))
    # 期望结果
    expectResult = re.sub(r'\r\n', '', str(expectresult))
    Worksheet.write(b, 1, organization)  # 所属系统
    Worksheet.write(b, 2, tomodoule)  # 所属模块
    Worksheet.write(b, 3, casename)  # 用例名称
    Worksheet.write(b, 4, precondition)  # 前置条件
    Worksheet.write(b, 5, casestep)  # 用例步骤
    Worksheet.write(b, 6, expectresult)  # 预期结果
    Worksheet.write(b, 7, is_maoyan)  # 是否冒烟

# 处理xmind数据
def deal_with_list(Worksheet, case_list):
    '''
    功能解释:处理从xmind转换过来的用例list,并写入Excel中
    @param Worksheet: excel表对象
    @param case_list: 通过xmind转换好的用例列表
    '''
    tips = 'excel表格处理成功!!!'

    b = 1  # 记录写了多少行
    for row_case in case_list:
        case = row_case.split("!")  # 用‘!’分隔,存在list中,这是一条用例
        caselength = len(case)
        try:
                organization = "**系统"# 所属系统
                tomodoule = case[2]# 所属模块
                casename = case[3]# 用例标题
                precondition = case[4]# 预置条件
                casestep = case[5]  # 用例步骤,(倒数第2个下标是步骤)
                expectresult = case[6]  # 预期结果,(倒数第1个下标是预期结果)
                if 'Y' in row_case:
                    is_maoyan = 'Y'
                else:
                    is_maoyan = 'N'
                # print(expectresult)
                write_sheet(Worksheet, b, organization,tomodoule,casename,precondition, casestep, expectresult,is_maoyan)  # 写入Excel
        except:
            tips = 'excel表格处理异常,请联系Dora!!!'
            print('异常tips:', tips)
            # 输出异常信息
            traceback.print_exc()
        b = b + 1
    return tips

def xmindToexcelfile(uploadPath):
    # 创建一个Workbook对象 编码encoding
    Workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)
    # 添加一个sheet工作表、sheet名命名为Sheet1、cell_overwrite_ok=True允许覆盖写
    Worksheet = Workbook.add_sheet('Sheet1', cell_overwrite_ok=True)
    Worksheet.write(0, 0, '用例编号')
    Worksheet.write(0, 1, '所属系统')
    Worksheet.write(0, 2, '所属模块名称')
    Worksheet.write(0, 3, '用例名称')
    Worksheet.write(0, 4, '预置条件')
    Worksheet.write(0, 5, '用例步骤')
    Worksheet.write(0, 6, '预期结果')
    Worksheet.write(0, 7, '冒烟用例')
    root = xmind_to_dict(uploadPath)[0]['topic']  # 解析成dict数据类型xmindparser.xmind_to_dict(filePath)
    print('root:', root)
    case_list = get_case(root)
    print('case:', case_list)
    tips = deal_with_list(Worksheet, case_list)
    # Excel表保存的文件名字
    savepath = os.path.abspath(os.path.dirname(__file__)) + '\\excelFiles\\' + root["title"] + timestp + ".xls"
    Workbook.save(savepath)  # 此处可以填写生成文件的路径
    return tips

xmindToexcelfile('测试用例.xmind')

xmind格式

python转成可执行文件

pyinstaller -F xmind.py

### 回答1: 要将Xmind转换成Excel测试用例,可以使用Python编程语言进行自动化操作。下面是一个简单的步骤: 1. 安装所需的Python库:首先,需要安装一些Python库以便处理XmindExcel文件。可以使用pip命令安装openpyxl和xmindparser库:`pip install openpyxl xmindparser` 2. 导入所需的库:在Python脚本中,导入openpyxl和xmindparser库以及其他可能需要的库文件: ```python import openpyxl import xmindparser ``` 3. 解析Xmind文件:使用xmindparser库将Xmind文件解析为Python对象,以便进一步处理: ```python xmind_file = xmindparser.load("path_to_xmind_file.xmind") ``` 4. 创建Excel文件和工作表:使用openpyxl库创建一个Excel文件并添加一个工作表: ```python excel_file = openpyxl.Workbook() sheet = excel_file.active ``` 5. 遍历Xmind对象并写入Excel文件:使用循环遍历Xmind对象的各个部分,并将它们写入Excel文件中的相应位置。具体如何遍历和写入将根据Xmind文件的结构而定,以下是一个示例: ```python for topic in xmind_file[0]["topic"]["topics"]: sheet.cell(row=row_num, column=1, value=topic["title"]) for subtopic in topic["topics"]: sheet.cell(row=row_num, column=2, value=subtopic["title"]) row_num += 1 ``` 6. 保存并关闭Excel文件:在完成写入后,使用openpyxl库的save方法将Excel文件保存在磁盘上,并使用close方法关闭文件: ```python excel_file.save("path_to_excel_file.xlsx") excel_file.close() ``` 通过以上步骤,就能够使用Python将Xmind转换为Excel测试用例。根据实际需求,可能需要进一步处理和调整代码,例如设置样式、添加其他信息等。 ### 回答2: Python可以使用一些库和工具将Xmind格式的思维导图转换为Excel测试用例。下面介绍一种常见的方法: 1. 首先,我们需要安装并导入相关库,例如`xlwt`用于创建Excel文件、`xmind`用于读取Xmind文件等。 ```python import xlwt from xmindparser import xmind_to_dict ``` 2. 接下来,我们需要将Xmind文件加载并转换为字典。这可以通过`xmind_to_dict`函数来实现。 ```python xmind_file = 'path/to/xmind_file.xmind' data = xmind_to_dict(xmind_file) ``` 3. 现在,我们可以通过遍历字典中的内容来提取测试用例的相关信息,并将其存储到Excel文件中。 ```python workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Test Cases') # 写入表头 header = ['用例名称', '用例编号', '前置条件', '步骤', '预期结果'] for col, name in enumerate(header): worksheet.write(0, col, name) # 遍历Xmind字典 def parse_xmind(data, row): for item in data: if 'topic' in item: topic = item['topic'] case_name = topic['title'] case_id = topic['id'] precondition = '' # 前置条件 steps = '' # 步骤 expected_result = '' # 预期结果 # 检查是否存在子主题 if 'topics' in topic: for sub_topic in topic['topics']: if 'title' in sub_topic: title = sub_topic['title'] if title == '前置条件': precondition = sub_topic['topics'][0]['title'] elif title == '步骤': for step in sub_topic['topics']: steps += step['topics'][0]['title'] + '\n' elif title == '预期结果': for result in sub_topic['topics']: expected_result += result['topics'][0]['title'] + '\n' # 将用例信息写入Excel worksheet.write(row, 0, case_name) worksheet.write(row, 1, case_id) worksheet.write(row, 2, precondition) worksheet.write(row, 3, steps) worksheet.write(row, 4, expected_result) row += 1 # 递归处理子主题 if 'topics' in topic: row = parse_xmind(topic['topics'], row) return row # 开始处理Xmind数据 row = parse_xmind(data, 1) # 保存Excel文件 workbook.save('path/to/test_cases.xls') ``` 以上是将Xmind转换为Excel测试用例的一个简单示例。通过解析Xmind文件的层级结构,并针对每个主题提取相应的信息,我们可以轻松地生成Excel文件,其中包含测试用例的名称、编号、前置条件、步骤和预期结果等内容。 ### 回答3: Python提供了丰富的第三方库和工具,可以帮助我们实现将XMind转换成Excel测试用例的功能。下面是一个简单的示例代码,用于将XMind文件中的测试用例转换成Excel格式: 1. 首先,我们需要使用Python中的xlwt库来创建Excel文件并写入测试用例数据。 ```python import xlwt from xmindparser import xmind_to_dict def convert_xmind_to_excel(xmind_file, excel_file): # 读取XMind文件 workbook_dict = xmind_to_dict(xmind_file) # 创建Excel文件 workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Test Cases') # 写入表头 headers = ['Test Case ID', 'Test Case Name', 'Steps', 'Expected Result'] for index, header in enumerate(headers): worksheet.write(0, index, header) # 写入测试用例数据 row = 1 for sheet in workbook_dict['sheets']: for topic in sheet['rootTopic']['topics']: test_case_id = topic['title'] test_case_name = topic['topics'][0]['title'] steps = topic['topics'][0]['topics'][0]['title'] expected_result = topic['topics'][0]['topics'][0]['topics'][0]['title'] worksheet.write(row, 0, test_case_id) worksheet.write(row, 1, test_case_name) worksheet.write(row, 2, steps) worksheet.write(row, 3, expected_result) row += 1 # 保存Excel文件 workbook.save(excel_file) ``` 2. 在上述代码中,我们使用了`xmindparser`库来解析XMind文件,需要使用`pip install xmindparser`命令来安装该库。 3. `convert_xmind_to_excel`函数接受两个参数,分别是XMind文件路径以及要保存的Excel文件路径。 4. 函数首先使用`xmind_to_dict`函数将XMind文件解析成一个字典,然后创建一个Excel对象。 5. 接下来,我们按照Excel格式,将测试用例的数据逐行写入Excel文件,包括测试用例ID、名称、步骤和预期结果。 6. 最后,使用`workbook.save(excel_file)`保存Excel文件。 通过以上代码,我们可以将XMind文件中的测试用例转换成Excel格式,方便进行测试用例管理和执行。当然,根据实际需求,还可以根据XMind文件的结构进行更复杂的操作,例如解析不同分支、处理更多层级的数据等。可以根据具体情况对代码进行适当的优化和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值