XML Unittest

1.0.1 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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.

import unittest
from xmlunittest import XmlTestCase

class MyXmlTests(XmlTestCase):
    def test_basic_xml_content(self):
        data = """<root><item id='1'>Value A</item><item id='2'>Value B</item></root>"""
        self.assertXmlDocument(data)
        self.assertXpathsExist(data, ['/root', '/root/item', '/root/item[@id="1"]'])
        self.assertXpathsOnlyOne(data, ['/root/item[@id="1"]'])
        self.assertXpathValues(data, '//item[@id="1"]', ['Value A'])
        self.assertXpathAttributes(data, '//item[@id="1"]', {'id': '1'})

    def test_with_namespaces(self):
        data = """<root xmlns:ns='http://example.com/ns'><ns:element>Hello</ns:element></root>"""
        # Pass namespaces explicitly when using XPath with namespaces
        self.assertXpathValues(data, '//ns:element', ['Hello'], namespaces={'ns': 'http://example.com/ns'})

if __name__ == '__main__':
    unittest.main()

view raw JSON →