在Python的单元测试中比较XML [英] Comparing XML in a unit test in Python

查看:66
本文介绍了在Python的单元测试中比较XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,可以从XML字符串构建自己,并将其写出到XML字符串。我想编写一个单元测试来测试通过XML的往返,但是我无法比较两个XML版本。空格和属性顺序似乎是问题所在。有关如何执行此操作的任何建议?这是在Python中进行的,而我正在使用ElementTree(因为这里我只是在此级别上处理字符串中的XML,所以这并不是真的很重要)。

I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).

推荐答案

首先规范2个XML,然后可以对其进行比较。我已经使用了以下lxml

First normalize 2 XML, then you can compare them. I've used the following using lxml

obj1 = objectify.fromstring(expect)
expect = etree.tostring(obj1)
obj2 = objectify.fromstring(xml)
result = etree.tostring(obj2)
self.assertEquals(expect, result)

这篇关于在Python的单元测试中比较XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆