"Zoom in" on rendered HTML that the test client returns

If you have this as your base class for all unit tests you can do the following:

class TestViews(BaseTestCase):
def test_generated_stats(self):
"test that certain stuff in the response"
...create some content for testing or use fixtures...
response = self.client.get('/some/page/')
# At this point response.content is a huge string filled with HTML tags and
# "junk" that you don't need for testing the content thus making it difficult
# to debug the generated HTML because it so huge.
# So we can zoom in on the <div id="stats>...</div> node
html = self._zoom_html(response.content, '#stats')
# the variable 'html' will now be something like this:
"""
<div id="stats">
<p>
<strong>2</strong> students<br/>
<em>1</em> warning.
</p>
</div>
"""
# This makes it easier to debug the response and easier to test
# against but the HTML might still be in the way so this would fail:
self.assertTrue('2 students' in html) # will fail
# To strip away all html use _strip_html()
content = self._strip_html(html)
# Now this will work
self.assertTrue('2 students' in content) # will work

It works for me and I find this very useful so I thought I'd share it.

# pythonimportrefromcStringIOimportStringIO# djangofromdjango.testimportTestCaseclassBaseTestCase(TestCase):def_zoom_html(self,html,css_selector):try:fromlxml.htmlimportparsefromlxmlimportetreefromlxml.cssselectimportCSSSelectorexceptImportError:returnhtmlparser=etree.HTMLParser()tree=etree.parse(StringIO(html),parser)page=tree.getroot()ifisinstance(css_selector,basestring):selector=CSSSelector(css_selector)else:raiseValueError("css_select must be a string")html_chunks=[]forpartinselector(page):html_chunks.append(etree.tostring(part,pretty_print=True))return''.join(html_chunks)def_strip_html(self,html):returnre.sub('</?\w.*?>','',html)