深入理解python之self(谈谈对python的认识)
281
2022-08-18
《自拍教程65》Python Testlink用例导出工具xml2excel(自拍照教程)
准备阶段
操作Xml的模块,我建议首选ElementTree, 本次用官方自动的ElementTree即可
操作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('
', '').replace('
', '').replace(' ', '').replace(
'', '').
replace('
replace('
', '').replace("“", "", ).replace("”", "")
return inputdata
def data_format_fummary_precondition(self, inputdata):
'''过滤掉(删掉)一些不必要的html的字符'''
if inputdata != None:
inputdata = inputdata.strip()
inputdata = inputdata.replace('
', '').replace('
', '').replace(' ', '').replace(
'
replace('
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)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~