我的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