案例故事: 接上两篇:Python Testlink用例导入工具excel2xml
有导入,肯定有导出,很不凑巧,只支持Xml格式的用例导出。
我们需要把Xml格式的测试用例再转换成Excel版的测试用例,以方便阅读。
准备阶段
- 操作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) + "\n")
except:
action_list.append( "Step" + str(action_count) + ":" + "" + "\n")
action_count = action_count + 1
if (node_3.tag == "expectedresults"):
try:
result_list.append("Result" + str(result_count) + ":" + self.data_format(
node_3.text) + "\n")
except:
result_list.append("Result" + str(result_count) + ":" + "" + "\n")
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('\n', '').replace('\t', '').replace(
'