07 Sep 2013 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 . 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  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.
|||tempfile module http://docs.python.org/2/library/tempfile.html#module-tempfile|
|||webbrowser module http://docs.python.org/2/library/webbrowser.html|