personal web log written by izabeera and dryobates

testing debugging django browser

Preview page in browser during tests in Django

by dryobates

During testing django webpages it is sometimes easier preview rendered responses directly in browser then analyze html code on console. With webbrowser module it’s easy.

You have to write only few lines of code:

import tempfile
import webbrowser

def show_in_browser(data):
    with tempfile.NamedTemporaryFile() as tmp:
        tmp.write(str(data))
        webbrowser.open(tmp.name)

First we have to create temporary file (use tempfile module [1]. We don’t want leave unused files after tests. File needs name so that we can point browser to that file. Now with webbrowser module [2] we open that file in browser. By default page is opened in existing browser window. You can open it in new window or new tab ( methods open_new and open_new_tab respectively).

Now you can start your browser with response returned by Django client:

response = self.client.get(url)
show_in_browser(response.conent)

If you want choose browser other then default then simply set BROWSER environment variable to name of your beloved browser and then start tests:

export BROWSER='uzbl-browser'
python manage.py test

Python won’t stop when it open page in browser so you probably would like to set some breakpoint to have time to analyze response results.

One inconvenience with this method is that you won’t see static files unless you serve them from outside of running Django during testing. Not big deal I think.

[1]tempfile module http://docs.python.org/2/library/tempfile.html#module-tempfile
[2]webbrowser module http://docs.python.org/2/library/webbrowser.html
dryobates
dryobates
Jakub Stolarski. Software engineer. I work professionally as programmer since 2005. Speeding up software development with Test Driven Development, task automation and optimization for performance are things that focus my mind from my early career up to now. If you ask me for my religion: Python, Vim and FreeBSD are my trinity ;) Email: jakub@stolarscy.com

Archive

Tag cloud