It is possible to create a pre-authenticated session cookie in Django 1.8 and pass it to Selenium.
In order to do this, you'll have to:
Create a new session in your backend;
Produce a cookie with that newly created session data;
Pass that cookie to your Selenium webdriver.
The logic of session and cookie creation is shown below:
# create_session_cookie.py
from django.conf import settings
from django.contrib.auth import (
SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY,
get_user_model
)
from django.contrib.sessions.backends.db import SessionStore
def create_session_cookie(username, password):
# First, create a new test user
user = get_user_model()
user.objects.create_user(username=username, password=password)
# Then using the new user credentials, create the authenticated session
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session[HASH_SESSION_KEY] = user.get_session_auth_hash()
session.save()
# Finally, create the cookie dictionary
cookie = {
'name': settings.SESSION_COOKIE_NAME,
'value': session.session_key,
'secure': False,
'path': '/',
}
return cookie
Now, inside your Selenium tests:
#selenium_tests.py
# assuming self.webdriver is the selenium.webdriver obj.
from create_session_cookie import create_session_cookie
session_cookie = create_session_cookie(
email='[email protected]', password='top_secret'
)
# to setup Selenium, visit some url in your domain.
# (404 pages load the quickest)
self.driver.get('your-url' + '/404-non-existent/')
# add the newly created session cookie to selenium webdriver.
self.driver.add_cookie(session_cookie)
# refresh to exchange cookies with the server.
self.driver.refresh()
# This time users should present as logged in.
self.driver.get('your-url')
I hope it helps!