Friday, November 12, 2010

Testing (Django) views with pyquery

PyQuery is basically what it sounds like. Using jQuery syntax, you can query and even manipulate XML files. Obviously we don't (yet!) have Python in the browser, so it's not useful in the same domain, but it can help out in dealing with XML in general, in the same way as, say, lxml, but without having to learn about things like ElementTree for simple cases. It's particularly good for XHTML because jQuery (and thus PyQuery) uses CSS syntax for class= and id=. Which brings me to how I'm using it:

from django.test.client import Client
from pyquery import PyQuery
from django.test.testcases import TestCase

...

class TestSomeViews(TestCase):

def testAView(self):

client = Client()

...

response = client.get("/someurl/")

self.assertTrue("expected text" in PyQuery(response.content)("#someid").html() )

(If you're unfamiliar with testing Django views, see this.)

For some basic tests, you can just search the entire response html, and not have to worry about where it shows up. But suppose you're searching for a username in a particular part of your response. You're pretty likely to find that username elsewhere on the page, so you have to select out the part of the file you expect it. I think this is much easier than using a regex.

So what this bit of PyQuery does is find the tag with the id of "someid" (presumably there's only only one, being an id), and returns the html within that tag. (If you search for a class that returns multiple tags, it seems that a simple call to .html() will only return the contents of the first one. This very well may match jQuery's behavior, I'm admittedly not that familiar, but just a head's up.) For more details look at the PyQuery API.

No comments: