I’ve recently started including view tests in my TDD/BDD pratice. In my Django views(templates) tests, I needed a tool to help me test the presence of certain DOM elements. One of my favorite ways to locate DOM element in an HTML document is by using CSS selectors in jQuery. I started looking around for a Python implementation of jQuery and found a great library called PyQuery that (thus far at least) has let me manipulate my views as DOM object just like I wanted to. One way that I’ve used it thus it this far is to test that every single one of my template contains only valid HTML once rendered. When doing TDD/BDD with all my template I start out by writing a test that looks a bit like the following one :

class NewBlogTemplateTests(unittest.TestCase):        def __getNewBlogTemplateRendered(self):          return render_to_string( 'blog/newBlog.html',                                  { 'newBlogForm': NewBlogForm() }                                  )        def itShouldContainOnlyValidHtml(self):          theNewBlogTemplate = self.__getNewBlogTemplateRendered()          assert_that(theNewBlogTemplate, is_(containingValidHTMLOnly()))

Behind the scenes, containingValidHTMLOnly is an Hamcrest matcher I have written using PyQuery and Multipart. I will dig more into Hamcrest‘s expressive power in a future blog. Here is the source code :

from hamcrest.core.base_matcher import BaseMatcher  from pyquery.pyquery import PyQuery  from helpers.tests import Multipart    class ContainsValidHTML(BaseMatcher):        def __init__(self):          pass        def _matches(self, template):          responseFromW3 = Multipart.post_multipart( 'validator.w3.org',                                                    '/check',                                                    {'fragment': template}                                                    )          pyQuery = PyQuery(responseFromW3)          return pyQuery('#congrats') != []        def describe_to(self, description):          description.append_text('ContainsValidHTML')    containingValidHTMLOnly = ContainsValidHTML

W3c compliant HTML guaranteed by my automated test and my continuous integration build. I think this is pretty darn awesome ! Thanks PyQuery ! Special thanks to Jeff Balogh for teaching me in his blog this awesome use of PyQuery. -Nicholas Lemay

gabriel bélanger

Previous post

AtlasCamp 2010 (en)

Next post

De la théorie à la pratique (en)