我的XML文件類似於下面的一個:Python的XML解析子標籤,以便
<suite name="regression_1">
<test name="Login check" id="s1-t1">
<keyword name="Valid Username and Password">
<keyword name="Invalid Username or Password">
<keyword name="Invalid password">
<message level="TRACE" >Return error</message>
<status status="PASS"/>
</keyword>
<message level="INFO">Return error</message>
<status status="FAIL"/>
</keyword>
<message level="INFO">Return: None</message>
<status status="PASS"/>
</keyword>
<status status="FAIL"/>
</test>
<test name="test-2" id="s1-t1">
<keyword name="abc">
<keyword name="def">
<message level="INFO">Return error</message>
<status status="FAIL"/>
</keyword>
<message level="INFO">Return: None</message>
<status status="PASS"/>
</keyword>
<status status="FAIL"/>
</test>
</suite>
我的輸出應該檢查的關鍵字,讓關鍵字結構對於那些狀態爲「失敗」。測試中會有很多關鍵字,可能有也可能不是子關鍵字。
****樣本輸出*******
套房:regression_1
測試名稱:登錄檢查
關鍵字失敗: 「有效的用戶名密碼&」,「無效用戶名或密碼「]
失敗測試用例消息:返回錯誤
套房:regression_1
測試名稱:測試2
關鍵字失敗: 「ABC」, 「DEF」]
失敗測試用例消息:返回錯誤
我的代碼是能夠挖掘直到最後一個孩子收集失敗狀態。但是無法解析分析所需的正確路徑。另外我認爲完整的循環沒有被執行。即如果第三個孩子是「PASS」,它不會回到第二個孩子來檢查其身份。從該代碼接收
def getStatusForNode(tc):
status_to_be_returned = []
is_just_father = False
for child in tc.childNodes:
if child.nodeName == "keyword":
is_just_father = True
status_to_be_returned.append(getStatusForNode(child)[0])
keyword_track.append(child.getAttribute("name"))
if not is_just_father:
status = tc.getElementsByTagName('status')
return [(tc, status)]
return status_to_be_returned
DOMTree = xml.dom.minidom.parse("output.xml")
collection = DOMTree.documentElement
tc_entry = collection.getElementsByTagName("suite")
top = Element('tests')
comment = Comment("This xml is generated only for failing tests")
top.append(comment)
for tc in tc_entry:
if tc.hasAttribute("name"):
print("Suite name: {}".format(tc.getAttribute("name")))
tests = tc.getElementsByTagName('test')
for test in tests:
keyword_track = []
for child in test.childNodes:
if child.nodeName == "keyword":
children_status = getStatusForNode(child)
for (tc_name, status) in children_status:
for state in status:
if state.getAttribute("status") != "PASS":
print("---")
print("Test name: {}".format(test.getAttribute("name")))
print("Keyword failed: {}".format(tc_name.getAttribute("name")))
print("Status: {}".format(state.getAttribute("status")))
messages = tc_name.getElementsByTagName('msg')
print("Failure test case messages:")
for message in messages:
print(message.childNodes[0].data)
print ("")
輸出:
試驗名稱:ABC
關鍵字名:keyword_1-2-3
狀態:FAIL
失敗測試用例消息:失敗在3級
任何建議優化的代碼?
你的XML無效,錯誤:無效字符「&」和多個根元素。您的_ **示例輸出** _必須錯誤,_Keyword中的** **和**無效**怎麼都失敗:_?第二個示例_ ** [「keyword_1」,「keyword_1-2」,「keyword_1」] ** _,都有** PASS **? – stovfl
修改了xml文件.. – Yadunandana