xmind用例数据上传至禅道

xmind格式参考,只需要在一级子主题填写对应用例模块ID,其余格式随意即可生成用例并直接上传到禅道:

代码里需填写禅道对应登录账号及用例所属产品

python 复制代码
import requests
import json
import re
import hashlib
import pprint
import threading
from xmindparser import xmind_to_dict


def get_sub_topic(topic_data_list, k=0, row=None, result=None):
    '''遍历出所有数据'''
    if row is None:
        row = {}
    if result is None:
        result = []
    for topic_data in topic_data_list:
        # 获取下一行时,清除上一行针对当前索引后面的数据
        k_list = []
        for j in row:
            k_list.append(j)
        for j in k_list:
            if j > k:
                row.pop(j)
        # 赋值当前索引 标题
        row[k] = topic_data['title']
        if 'topics' in topic_data:
            get_sub_topic(topic_data['topics'], k=k + 1, row=row, result=result)
        else:
            result.append(row.copy())
    return result


def get_xmind_data(xmind_file_path):
    data = xmind_to_dict(xmind_file_path)
    topics = data[0]['topic']['topics']
    result = get_sub_topic(topics)
    return result


def get_max_length(data):
    length = 0
    for l in data:
        length = len(l) if len(l) > length else length
    return length


def get_length_first_name(length, data):
    for l in data:
        if length == len(l):
            if length > 4:
                return l[-4], length - 4
            else:
                return l[1], 1


def get_case(title, data: list, index):
    row = []
    tag = -1
    for i, l in enumerate(data):
        if len(l) > index and l[index] == title:
            if tag == -1 or i == tag + 1:
                row.append(l)
                tag = i
    for r in row:
        data.remove(r)
    return row


def case_to_params(row: list, index: int):
    case = {}
    module: str = row[0][0]
    module_id = re.search('#\d+', module)
    if module_id is None:
        return
    module_id = module_id.group()
    row[0][0] = module.replace(f'({module_id})', '').replace(f'({module_id})', '')
    case['module'] = module_id[1:]
    case['title'] = '-'.join(row[0][:index + 1])
    row = [r[index + 1:] for r in row]
    three = []
    group = {}
    for r in row:
        if len(r) == 3:
            three.append(r[0]) if r[0] not in three else ''
    for t in three:
        group[t] = []
        for r in row:
            if r[0] == t:
                group[t].append(r[1:])

    num = 1
    oo = []
    for o in row:
        if len(o)==0:
            continue
        if o[0] in three and o[0] not in oo:
            case[f'steps[{num}]'] = o[0]
            case[f'stepType[{num}]'] = 'group'
            j = 1
            pp = []
            for rr in group[o[0]]:
                num_key = f'{num}.{j}'
                if len(rr) == 1:
                    case[f'steps[{num_key}]'] = rr[0]
                    case[f'stepType[{num_key}]'] = 'item'
                    case[f'expects[{num_key}]'] = ''
                    j += 1
                elif len(rr) == 2:
                    if rr[0] not in pp:
                        case[f'steps[{num_key}]'] = rr[0]
                        case[f'stepType[{num_key}]'] = 'item'
                        case[f'expects[{num_key}]'] = rr[1]
                        j += 1
                        pp.append(rr[0])
                    else:
                        num_key = f'{num}.{j - 1}'
                        case[f'expects[{num_key}]'] += f'\n{rr[1]}'
            oo.append(o[0])
            num += 1
        elif o[0] in three:
            continue
        elif len(o) == 1:
            case[f'steps[{num}]'] = o[0]
            case[f'stepType[{num}]'] = 'item'
            case[f'expects[{num}]'] = ''
            num += 1
        elif len(o) == 2:
            if o[0] not in oo:
                case[f'steps[{num}]'] = o[0]
                case[f'stepType[{num}]'] = 'step'
                case[f'expects[{num}]'] = o[1]
                num += 1
                oo.append(o[0])
            else:
                case[f'expects[{num - 1}]'] += f'\n{o[1]}'
    return case


host = 'https://rhjs.techgp.cn/'


def md5update(args):
    input_name = hashlib.md5()
    input_name.update(args.encode("utf-8"))
    return input_name.hexdigest()


class CaseUpload:

    @staticmethod
    def __get_session():
        url = '{}/api-getsessionid.json'.format(host, )
        rj = requests.get(url)
        data = rj.json()['data']
        if isinstance(data, str):
            data = json.loads(data)
        return data['sessionID']

    def login(self, username, password):
        sid = self.__get_session()
        url = '{}/user-login.json?account={}&password={}&zentaosid={}'.format(host, username, password, sid)
        rj = requests.get(url)
        res = rj.json()
        if res['status'] == 'success':
            return {
                'sid': sid,
                'username': username,
                'password': md5update(password),
                'nickname': res['user']['realname'],
                'email': res['user']['email']
            }
        return False

    def create_case(self, sid, product, payload):
        module = payload['module']
        form = {'product': str(product), 'type': 'feature', 'stage[]': '',
                'story': '0', 'color': '', 'pri': '3', 'precondition': '',
                'keywords': '', 'status': 'wait', 'labels[]': '', 'files[]': ''}
        url = f'{host}/zentao/testcase-create-{product}-0-{module}.json?zentaosid={sid}'
        form.update(payload)
        files = []
        response = requests.request("POST", url, data=form, files=files)
        print('response create', response.text)


def main(xmind_file_path, product: str, account: dict, ):
    '''
    :param xmind_file_path:
    :param account: {'username':'xx.li','password':'123456'}
    :return:
    '''
    data = get_xmind_data(xmind_file_path)
    data = [[i for i in l.values()] for l in data]
    case_list = []
    while data:
        max_length = get_max_length(data)
        title, index = get_length_first_name(max_length, data)
        row = get_case(title, data, index)
        # print('row::',row)
        case = case_to_params(row, index)
        case_list.append(case)
    pprint.pprint(case_list)
    print(len(case_list))
    case_upload=CaseUpload()
    sid = case_upload.login(**account)['sid']
    tlist=[]
    for _case in case_list:
        t=threading.Thread(target=case_upload.create_case,args=(sid,product,_case))
        # case_upload.create_case(sid,product,_case)
        tlist.append(t)
        t.start()
    for t in tlist:
        t.join()


if __name__ == '__main__':
    main('/Users/xx/Desktop/cases/大数据/数字化v1.1.1.xmind', '248',
         {
             'username': 'xx',
             'password': 'xx'
         })
相关推荐
深度学习lover1 小时前
<项目代码>YOLOv8 苹果腐烂识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果腐烂识别
API快乐传递者2 小时前
淘宝反爬虫机制的主要手段有哪些?
爬虫·python
阡之尘埃4 小时前
Python数据分析案例61——信贷风控评分卡模型(A卡)(scorecardpy 全面解析)
人工智能·python·机器学习·数据分析·智能风控·信贷风控
丕羽7 小时前
【Pytorch】基本语法
人工智能·pytorch·python
bryant_meng7 小时前
【python】Distribution
开发语言·python·分布函数·常用分布
m0_594526308 小时前
Python批量合并多个PDF
java·python·pdf
工业互联网专业9 小时前
Python毕业设计选题:基于Hadoop的租房数据分析系统的设计与实现
vue.js·hadoop·python·flask·毕业设计·源码·课程设计
钱钱钱端9 小时前
【压力测试】如何确定系统最大并发用户数?
自动化测试·软件测试·python·职场和发展·压力测试·postman
慕卿扬9 小时前
基于python的机器学习(二)—— 使用Scikit-learn库
笔记·python·学习·机器学习·scikit-learn
Json____9 小时前
python的安装环境Miniconda(Conda 命令管理依赖配置)
开发语言·python·conda·miniconda