Last active
April 18, 2024 22:17
-
-
Save dustinfarris/4982145 to your computer and use it in GitHub Desktop.
Setting session variables whilst testing with Django's TestCase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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) |
"whilst" is an anachronism that's no longer widely used and does not differ from "while" except in its relative disuse.
Where would this go in a Django project?
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.
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
Great work! However import modules shoud change as follow:
django.utils.importlib
has been obsolete since Django 1.7 and was removed in 1.9.import_module
can be imported fromimportlib
directly. See here for more info