Skip to content

Instantly share code, notes, and snippets.

@dustinfarris
Last active April 18, 2024 22:17
Show Gist options
  • Save dustinfarris/4982145 to your computer and use it in GitHub Desktop.
Save dustinfarris/4982145 to your computer and use it in GitHub Desktop.
Setting session variables whilst testing with Django's TestCase
"""
Attempting to set session variables directly from TestCases can
be error prone. Use this super-class to enable session modifications
from within your tests.
Usage
-----
class MyTest(SessionEnabledTestCase):
def test_with_session_support(self):
session = self.get_session()
session['some-key'] = 'some-value'
session.save()
self.set_session_cookies(session)
response = self.client.get('/')
self.assertIn(
('some-key', 'some-value'),
response.client.session.items())
"""
from django.conf import settings as django_settings
from django.test import TestCase as TestCase
from django.utils.importlib import import_module
class SessionEnabledTestCase(TestCase):
def get_session(self):
if self.client.session:
session = self.client.session
else:
engine = import_module(django_settings.SESSION_ENGINE)
session = engine.SessionStore()
return session
def set_session_cookies(self, session):
# Set the cookie to represent the session
session_cookie = django_settings.SESSION_COOKIE_NAME
self.client.cookies[session_cookie] = session.session_key
cookie_data = {
'max-age': None,
'path': '/',
'domain': django_settings.SESSION_COOKIE_DOMAIN,
'secure': django_settings.SESSION_COOKIE_SECURE or None,
'expires': None}
self.client.cookies[session_cookie].update(cookie_data)
@bunop
Copy link

bunop commented Jul 17, 2018

Great work! However import modules shoud change as follow:

# tested in django 1.11
from django.conf import settings as django_settings
from django.test import TestCase
from importlib import import_module

django.utils.importlib has been obsolete since Django 1.7 and was removed in 1.9. import_module can be imported from importlib directly. See here for more info

@ashilen
Copy link

ashilen commented Aug 2, 2019

"whilst" is an anachronism that's no longer widely used and does not differ from "while" except in its relative disuse.

@carltonsmith
Copy link

Where would this go in a Django project?

@Sabaabdoulaye2
Copy link

Place it at the top-most part of your tests, right below your imports then inherit from it in your tests that require session variables.

@btimby
Copy link

btimby commented Apr 18, 2024

I love the use of "whilst" I am overcome with whimsy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment