I am quite confused and want to ask about if statement used in a loop with find()
method.
I wanted to insert these data into a database and each data have a unique value which will only can be identified by its result.
The results available are "Passed"//"Incomplete"//"Failed"//"Failed, Incomplete, Error"//
Here is an example of the file
<TestSuite>
<TestCase>
<TestResult>
Failed
</TestResult>
<VerificationFailed>
Not enough Fuel.
</VerificationFailed>
</TestCase>
<TestCase>
<TestResult>
Passed
</TestResult>
</TestCase>
<TestCase>
<TestResult>
Incomplete
</TestResult>
<TestDescription>
Engine not set up properly.
</TestDescription>
</TestCase>
<TestCase>
<TestResult>
Failed, Incomplete, Error
</TestResult>
<ExceptionThrown>
Error, Capacity Overload.
</ExceptionThrown>
</TestCase>
</TestSuite>
I have tried using this code to get the values of these fields but it only returns "Passed"
tree = ET.parse('NewestReport.xml')
test = tree.findall('TestCase')
for ts in test:
result = ts.find('TestResult').text
if result in "Failed":
description = ts.find('VerificationFailed').text
print(description)
elif result in "Failed, Incomplete, Error":
description = ts.find('ExceptionThrown').text
print(description)
elif result in "Incomplete":
description = ts.find('TestDescription').text
print(description)
else:
description = "Passed"
print(description)
The expected output is 4 results of description that prints out the text from each unique fields (for "Failed" the text will be from <VerificationFailed>
, for "Incomplete" the text will be from <TestDescription>
, for "Failed, Incomplete, Error" the text will be from <ExceptionThrown>
and finally for "Passed" it will be the string "Passed".
I have tried the code but it only gives out the value passed. I need it to be able to get different values.
CodePudding user response:
I think the below is what you are looking for
import xml.etree.ElementTree as ET
xml = '''<TestSuite>
<TestCase>
<TestResult>
Failed
</TestResult>
<VerificationFailed>
Not enough Fuel.
</VerificationFailed>
</TestCase>
<TestCase>
<TestResult>
Passed
</TestResult>
</TestCase>
<TestCase>
<TestResult>
Incomplete
</TestResult>
<TestDescription>
Engine not set up properly.
</TestDescription>
</TestCase>
<TestCase>
<TestResult>
Failed, Incomplete, Error
</TestResult>
<ExceptionThrown>
Error, Capacity Overload.
</ExceptionThrown>
</TestCase>
</TestSuite>'''
root = ET.fromstring(xml)
for tc in root.findall('.//TestCase'):
result = tc.find('TestResult').text.strip()
if result == 'Failed':
print(f'{result} : {tc.find("VerificationFailed").text.strip()}')
elif result == 'Passed':
print(result)
elif result == 'Incomplete':
print(f'{result} : {tc.find("TestDescription").text.strip()}')
elif result == 'Failed, Incomplete, Error':
print(f'{result} : {tc.find("ExceptionThrown").text.strip()}')
output
Failed : Not enough Fuel.
Passed
Incomplete : Engine not set up properly.
Failed, Incomplete, Error : Error, Capacity Overload.