Skip to content

Instantly share code, notes, and snippets.

@palibaya
Created April 11, 2013 08:25
Show Gist options
  • Save palibaya/5361696 to your computer and use it in GitHub Desktop.
Save palibaya/5361696 to your computer and use it in GitHub Desktop.
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 django.core.management import setup_environ
from myproject import settings
setup_environ(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 south.management.commands import patch_for_test_db_setup
patch_for_test_db_setup()
host = context.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
context.server_thread.start()
# Wait for the live server to be ready
context.server_thread.is_ready.wait()
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(
'selenium.webdriver.remote.remote_connection')
selenium_logger.setLevel(logging.WARN)
context.browser = webdriver.Firefox()
context.browser.implicitly_wait(3)
def before_scenario(context, scenario):
# Set up the scenario test environment
context.runner.setup_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.
context.runner.teardown_databases(context.old_db_config)
context.runner.teardown_test_environment()
context.browser.delete_all_cookies()
def after_all(context):
context.browser.quit()
context.server_thread.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment