Introducing unittest-xml: testing XML in Python

For some reason, I keep finding myself writing unit tests that need to make assertions about an XML document. To keep things DRY, I’ve packaged up my custom assertion methods as a PyPi module: unittest-xml. There’s a small chance it may be useful to others.

Sample Usage

Enable the additional assert methods using a mixin:

import unittest
from xmltest import XMLAssertions

class SampleTestCase(unittest.TestCase, XMLAssertions):

Now suppose that the expected XML from some SUT1 is:

<?xml version="1.0" encoding="UTF-8" ?>
        <issuer country="UK">HSBC</issuer>

then you can make assertions about the document using 3 additional assertions methods.

self.assertXPathNodeCount(RESPONSE, 1, 'CardTxn/authcode')
self.assertXPathNodeText(RESPONSE, 'LIVE', 'mode')
self.assertXPathNodeAttributes(RESPONSE, {'country': 'UK'}, 'CardTxn/issuer')

The first argument to each method is the XML string, the second is the expected value, while the third is the XPath query.


The standard way:

pip install unittest-xml


Note, the implementation uses ElementTree and so only a subset of the XPath specification is implemented. However the above three assertion methods are sufficient for most scenarios.

The code is on Github, as usual.

  1. System under test [return]

Something wrong? Suggest an improvement or add a comment (see article history)
Tagged with: python, testing
Filed in: projects

Previous: Rewriting
Next: Auto-setting terminal titles for python virtual environments

Copyright © 2005-2017 David Winterbottom
Content licensed under CC BY-NC-SA 4.0.