I work at Tangent Labs, a digital agency, writing applications in python and django. I spend most of my free time hacking. I run commandlinefu.com and am the author of the e-commerce framework django-oscar amongst other things. I used to be a mathematician; I have a PhD in Mathematics from the University of Nottingham and an associated interest in cryptic crosswords, chess and playing devil's advocate. David is a DZone MVB and is not an employee of DZone and has posted 27 posts at DZone. You can read more from them at their website. View Full User Profile

Introducing unittest-xml: testing XML in python

02.17.2012
| 3043 views |
  • submit to reddit

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 System Under Test (SUT) is:

<?xml version="1.0" encoding="UTF-8" ?>
<Response>
    <CardTxn>
        <authcode>060642</authcode>
        <card_scheme>Switch</card_scheme>
        <issuer country="UK">HSBC</issuer>
    </CardTxn>
    <reference>3000000088888888</reference>
    <merchantreference>1000001</merchantreference>
    <mode>LIVE</mode>
    <reason>ACCEPTED</reason>
    <status>1</status>
    <time>1071567305</time>
</Response>


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.

Installation

The standard way:

pip install unittest-xml


Discussion

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.



Source: http://codeinthehole.com/writing/introducing-unittest-xml-testing-xml-in-python/

Published at DZone with permission of David Winterbottom, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: