Testing Django XML-RPC interfaces

If you have a Django application that with one or more views handling XML-RPC requests, you may have found that it is difficult to test these views thoroughly. Testing business logic can be done by testing the view functions directly, of course, but you may also want to test that the views integrate correctly with the XML-RPC layer.

import httplib
from xmlrpclib import getparser, ProtocolError

class DjangoTestClientTransport(object):
    client = None

    def __init__(self, client):
        self.client = client

    def getparser(self):
        return getparser()

    def request(self, host, handler, request_body, verbose = False):
        parser, unmarshaller = self.getparser()
        response = self.client.post(handler, request_body, 'text/xml')
        if response.status_code != 200:
            raise ProtocolError(
              '%s%s' % (host, handler),
              httplib.responses.get(response.status_code, ''),
        return unmarshaller.close()

Use it in your Django TestCases like this:

from django.test import TestCase
from xmlrpclib import ServerProxy

class MyTestCase(TestCase):
    def get_server_proxy(self):
        return ServerProxy(
          transport = DjangoTestClientTransport(self.client),

    def test_something(self):
        server_proxy = self.get_server_proxy()

It should work with any Django view that handles XML-RPC requests. I've tested it with Greg Abbas's ayp.xmlrpc. I started using that module quite a while ago, so there may be alternatives now.

Good luck with your testing!