personal web log written by izabeera and dryobates

django browser testing debugging

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:

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)

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 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
[2]webbrowser module
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: