xmlunittest is a Python library that extends the built-in `unittest` framework to provide robust assertion methods for testing XML documents. Leveraging `lxml` and XPath, it allows users to validate XML structure, content, and schema conformance, avoiding the pitfalls of direct XML string comparisons. The current version is 1.0.1, with releases typically focusing on compatibility updates and feature enhancements for XML processing.
pip install xmlunittestVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create an XML test case by inheriting from `xmlunittest.XmlTestCase`. It shows common assertions like `assertXmlDocument` for basic validity, `assertXpathsExist` to check for elements, `assertXpathValues` to check content, and `assertXpathAttributes` to check attributes. It also includes an example of handling XML with namespaces by passing a `namespaces` dictionary to the assertion methods.
Ensure XPath expressions correctly reference namespaces (e.g., by providing a `namespaces` dictionary to assertion methods) or adjust XML if non-namespaced XPath was implicitly relied upon.
Before installing `lxml` (and thus `xmlunittest`), ensure that necessary system libraries and development headers for `libxml2` and `libxslt` are installed. For example, on Debian/Ubuntu: `sudo apt-get install libxml2-dev libxslt1-dev python3-dev`.
Upgrade your Python environment to 3.8 or newer. For projects requiring Python 2.7, stick to `xmlunittest` versions <= 0.3.2, but be aware these are unmaintained.
Always use the assertion methods provided by `xmlunittest.XmlTestCase` (e.g., `assertXmlDocument`, `assertXpathValues`, `assertXpathsExist`) instead of standard `unittest.TestCase` assertions for comparing XML strings.
pip install xmlunittest
from xmlunittest import XmlTestCase
class MyTestClass(XmlTestCase):
# ... tests using assertXmlEquivalent, etc.
Correct the XPath expression to be valid according to XPath syntax (e.g., ensure proper prefixes, axes, and predicate formatting). Example: `self.assertXmlHasXPath(xml_doc, "/root/item[@id='1']")`
Ensure that the XML content passed to `xmlunittest` methods is a valid string, a file-like object (e.g., `io.StringIO`), or an `lxml.etree.Element`.