zoukankan      html  css  js  c++  java
  • 《自拍教程65》Python Testlink用例导出工具xml2excel

    案例故事: 接上两篇:Python Testlink用例导入工具excel2xml
    有导入,肯定有导出,很不凑巧,只支持Xml格式的用例导出。

    我们需要把Xml格式的测试用例再转换成Excel版的测试用例,以方便阅读。

    准备阶段
    1. 操作Xml的模块,我建议首选ElementTree, 本次用官方自动的ElementTree即可
    2. 操作Excel的模块,一直首选openpyxl

    Python面向对象类形式

    由于本案例涉及的代码有些许难度,且相对较长,
    直接以面向对象类的形式来进行建模及程序设计。

    建模:先设想有这么一个空白的世界,这个世界需要哪些类型的事物(名词)。
    我们需要两个类,一个是ExcelParser类用于解析Excel获取Excel数据,
    一个是XMLWriter类,用于将以上获取的Excel数据写入Xml文件里去。

    # coding=utf-8
    
    import os
    import re
    import shutil
    from openpyxl import Workbook
    from openpyxl.styles import Alignment
    from xml.etree.ElementTree import ElementTree
    
    
    class XmlReader():
        '''读取XML文件并获得所有的各用例的详细字段'''
    
        def __init__(self, xml_file):
            self.xml_file = xml_file
            self.all_case_list = []
            self.tree = ElementTree()
            self.tree.parse(self.xml_file)
            self.xmlroot = self.tree.getroot()
    
        def parse_xml(self):
            '''解析并最终把所有数据写到self.all_case_lit'''
            if self.xmlroot.tag == "testcases":
                for node_1 in list(self.xmlroot):
                    if (node_1.tag == "testcase"):
                        temp_casedict = {}
                        temp_casedict["summary"] = node_1.attrib["name"]
                        for node_2 in list(node_1):
                            if (node_2.tag == "steps"):
                                action_list = []
                                result_list = []
                                action_count = 1
                                result_count = 1
                                for node_3 in node_2.iter():
                                    if (node_3.tag == "actions"):
                                        try:
                                            action_list.append("Step" + str(action_count) + ":" + self.data_format(
                                                    node_3.text) + "
    ")
                                        except:
                                            action_list.append( "Step" + str(action_count) + ":" + "" + "
    ")
                                        action_count = action_count + 1
                                    if (node_3.tag == "expectedresults"):
                                        try:
                                            result_list.append("Result" + str(result_count) + ":" + self.data_format(
                                                            node_3.text) + "
    ")
                                        except:
                                            result_list.append("Result" + str(result_count) + ":" + "" + "
    ")
                                        result_count = result_count + 1
                                action_liststr = "".join(action_list)
                                result_list_str = "".join(result_list)
                                temp_casedict["step"] = action_liststr
                                temp_casedict["expectResult"] = result_list_str
                            elif (node_2.tag == "preconditions"):
                                temp_casedict[node_2.tag] = self.data_format_fummary_precondition(node_2.text)
                            elif (node_2.tag == "execution_type"):
                                if (node_2.text == "1"):
                                    temp_casedict[node_2.tag] = u"手动"
                                elif (node_2.text == "2"):
                                    temp_casedict[node_2.tag] = u"自动"
                            elif (node_2.tag == "importance"):
                                if (node_2.text == "1"):
                                    temp_casedict[node_2.tag] = "Low"
                                elif (node_2.text == "2"):
                                    temp_casedict[node_2.tag] = "Medium"
                                elif (node_2.text == "3"):
                                    temp_casedict[node_2.tag] = "High"
                            elif (node_2.tag == "keywords"):
                                for node_3 in node_2.iter():
                                    if (node_3.tag == "keyword"):
                                        temp_casedict[node_2.tag] = node_3.attrib["name"]
                        else:
                            pass
                        self.all_case_list.append(temp_casedict)
            return self.all_case_list
    
        def data_format(self, inputdata):
            '''过滤掉(删掉)一些不必要的html的字符'''
            inputdata = inputdata.strip()
            inputdata = inputdata.replace('<p>', '').replace('</p>', '').replace('
    ', '').replace('	', '').replace(
                    '</div>', ''). 
                replace('<div>', '').replace('&nbsp;', ' ').replace('&gt;', ''). 
                replace('<br />', '').replace("&ldquo;", "", ).replace("&rdquo;", "")
            return inputdata
    
        def data_format_fummary_precondition(self, inputdata):
            '''过滤掉(删掉)一些不必要的html的字符'''
            if inputdata != None:
                inputdata = inputdata.strip()
                inputdata = inputdata.replace('<p>', '').replace('</p>', '').replace('
    ', '').replace('	', '').replace(
                        '</div>', ''). 
                    replace('<div>', '').replace('&nbsp;', ' ').replace('&gt;', '').replace('<br />', '')
            else:
                inputdata = ""
            return inputdata
    
    class ExcelWriter():
        '''Get XML Cases and Generate Excel Cases'''
    
        def __init__(self, all_case_list):
            self.all_case_list = all_case_list
            self.wb = Workbook()
    
        def write_excel(self, save_path):
            ws = self.wb.active
            alignment = Alignment(horizontal="left", vertical="top", wrap_text=True)
            ws.alignment = alignment
            first_row = ["用例标题", "预置条件", "执行方式", "优先级", "测试步骤", "预期结果", "关键字"]
            ws.append(first_row)
            for case in self.all_case_list:
                temp_row = [(case["summary"]), case["preconditions"], case["execution_type"], case["importance"],
                            case["step"],
                            case["expectResult"]]
                if "keywords" in case:
                    temp_row.append(case["keywords"])
                ws.append(temp_row)
            self.wb.save(save_path)
    
    
    if __name__ == '__main__':
        curpath = os.getcwd()
        xml_dir = os.path.join(curpath, "XML_Input") # 输入文件夹
        xml_list = os.listdir(xml_dir)
    
        output_dir = os.path.join(curpath, "Excel_Output") # 输出文件夹
        try:
            shutil.rmtree(output_dir)
        except:
            pass
    
        if not os.path.exists(output_dir):
            os.mkdir(output_dir)
    
        for each_xml in xml_list:
            print("*" * 60)
            print("正在处理%s" % each_xml)
            print("*" * 60)
            xml_name, posfix = os.path.splitext(each_xml)
            exch_xml_path = "%s%s%s" % (xml_dir, os.sep, each_xml)
    
            x_obj = XmlReader(exch_xml_path)
            all_case_list = x_obj.parse_xml()
    
            e_obj = ExcelWriter(all_case_list)
            excel_save_path = "%s%s%s.xlsx" % (output_dir, os.sep, xml_name)
            e_obj.write_excel(excel_save_path)
            print("XML转Excel完毕并保存到了 %s" % excel_save_path)
    

    本案例素材下载

    包括:导出来的测试用例xml,Python脚本
    跳转到官网下载本素材
    武散人出品,请放心下载!

    运行方式与效果视频

    跳转到官网查看本视频

    更多更好的原创文章,请访问官方网站:www.zipython.com
    自拍教程(自动化测试Python教程,武散人编著)
    原文链接:https://www.zipython.com/#/detail?id=2e0f9c3c677045b1b2e9e81891db9387
    也可关注“武散人”微信订阅号,随时接受文章推送。

  • 相关阅读:
    《从零开始学Swift》学习笔记(Day 45)——重写方法
    《从零开始学Swift》学习笔记(Day 44)——重写属性
    浅析Android中ndk-build支持的参数
    texstudio on ubuntu 12.04
    arm上的参数列表传递的分析(以android为例)
    编译错误
    native method与so中function的关联
    Java.lang.NoClassDefFoundError--找不到相应的类
    Sublime Text 3 文档
    JNI 函数注册与管理
  • 原文地址:https://www.cnblogs.com/zipython/p/12887007.html
Copyright © 2011-2022 走看看