案例故事: 接上兩篇: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 = https://www.cnblogs.com/zipython/p/inputdata.strip()
inputdata = inputdata.replace('<p>', '').replace('</p>', '').replace('\n', '').replace('\t', '').replace(
'</div>', ''). \
replace('<div>', '').replace(' ', ' ').replace('>', ''). \
replace('<br />', '').replace("“", "", ).replace("”", "")
return inputdata
def data_format_fummary_precondition(self, inputdata):
'''過濾掉(刪掉)一些不必要的html的字符'''
if inputdata != None:
inputdata = https://www.cnblogs.com/zipython/p/inputdata.strip()
inputdata = inputdata.replace('<p>', '').replace('</p>', '').replace('\n', '').replace('\t', '').replace(
'</div>', ''). \
replace('<div>', '').replace(' ', ' ').replace('>', '').replace('<br />', '')
else:
inputdatahttps://www.cnblogs.com/zipython/p/= ""
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
也可關注“武散人”微信訂閱號,隨時接受文章推送,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/146932.html
標籤:Python
上一篇:Python哈希表和決議式
