python-3.x - xml.etree.ElementTree >> Python >> 如何访问子元素并进行断言

标签 python-3.x xml pytest elementtree

我正在使用 PyTest 来验证 xml api 响应。 从 api 请求获取以下响应(response.content)

b'<?xml version="1.0" encoding="UTF-8"?>
<Result0>
<Result1>
<Result3>
<Id>2</Id>
<ItemId>https://purchanse.com/62/E00036415</ItemId>
<Place>kpi:62_CS415-TEN-1080p25-ABC</Place>
<Marks>12</Marks>
<SubId>9, 8</SubId>
<Description>https://purchanse.com/62/E00036416</Description>
</Result3>
<Result4>
<Id>2</Id>
<ItemId>https://purchanse.com/64/E00036417</ItemId>
<Place>kpi:63_CS415-TEN-1080p25-XYZ</Place>
<Marks>12</Marks>
<SubId>9</SubId>
<Description>https://purchanse.com/64/E00036416</Description>
</Result4>
</Result1>
</Result0>'

在测试函数中我有这段代码

def test_CheckResponseContent():
    element = et.fromstring(response.content)
    print("element", element)  # Getting <Element 'Result0' at 0x04A88C58> as output
    links = element.find("Result0/Result1")
    print("L:", links)  # Returns 'None'

element = et.fromstring(response.content)
    for child in element.iter('*'):
        print(child.tag)

我想做这样的断言

Marks == 12
Id == 2
ItemId != "https://purchanse.com/62/E00036416"

我如何为此解析 XML?
有人可以帮忙吗

最佳答案

您有多个 标签提到了名字,所以相应的 应该为每个父级单独执行一组检查 这些标签。

为此,请尝试以下代码,也许没有 print 语句:

for it in element.findall('Result1/*'):
    print(it.tag)
    mrks = it.findtext('Marks')
    id = it.findtext('Id')
    itmId = it.findtext('ItemId')
    print(mrks, id, itmId)
    assert mrks == '12'
    assert id == '2'
    assert itmId != 'https://purchanse.com/62/E00036416'

关于python-3.x - xml.etree.ElementTree >> Python >> 如何访问子元素并进行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62937194/

相关文章:

python-3.x - 安装 Jupyter 扩展,启用失败 'nbextension'

python-3.x - 使用 pytest 运行 trace.py

php - magento:重写模板

pytest - 我怎样才能从 boto3 模拟 ssm?

python - 如何在Python中将数字减法字符串转换为整数?

xml - sql server 2008 xml文件到表

java - 显示方法不正常

python - pytest - 在所有其他测试之后重新运行失败的测试

python - 为单个单元测试用例更改 celery 设置 task_always_eager

python名称错误名称未定义