Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Environment for Behave + Django + Selenium
# -*- coding: utf-8 *-*
import os
import urlparse
import logging
from selenium import webdriver
# This is necessary for all installed apps to be recognized, for some reason.
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
def before_all(context):
# Even though DJANGO_SETTINGS_MODULE is set, this may still be
# necessary. Or it may be simple CYA insurance.
from import setup_environ
from myproject import settings
### Take a TestRunner hostage.
from django.test.simple import DjangoTestSuiteRunner
# We'll use thise later to frog-march Django through the motions
# of setting up and tearing down the test environment, including
# test databases.
context.runner = DjangoTestSuiteRunner()
## If you use South for migrations, uncomment this to monkeypatch
## syncdb to get migrations to run.
from import patch_for_test_db_setup
host = = 'localhost'
port = context.port = getattr(settings, 'TESTING_SERVER_PORT', 8081)
from django.test.testcases import LiveServerThread
context.server_thread = LiveServerThread(host, [port])
context.server_thread.daemon = True
# Wait for the live server to be ready
if context.server_thread.error:
raise context.server_thread.error
def browser_url(url):
"""Create a URL for the virtual WSGI server.
e.g context.browser_url('/'), context.browser_url(reverse('my_view'))
return urlparse.urljoin('http://%s:%d/' % (host, port), url)
context.browser_url = browser_url
selenium_logger = logging.getLogger(
context.browser = webdriver.Firefox()
def before_scenario(context, scenario):
# Set up the scenario test environment
# We must set up and tear down the entire database between
# scenarios. We can't just use db transactions, as Django's
# TestClient does, if we're doing full-stack tests with Mechanize,
# because Django closes the db connection after finishing the HTTP
# response.
context.old_db_config = context.runner.setup_databases()
def after_scenario(context, scenario):
# Tear down the scenario test environment.
def after_all(context):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment