Django, Testing, and Sessions
- Postfix, iPhone, Apple Mail and the reject
- Updating the SSL certs on the Unifi Controller
- Firefox and org-protocol URL Capture
- System Hangs on Shutdown
- Let's Encrypt Certificates and Arch
- /bin/mail as MTA
- Filtering bots with erc
- DSCP Tagging with iptables
- Bitlbee, Purple-Sipe-Lync, and Certificates
- daemontools, Apache, and the Whole Process Group
- Comma Trouble
- Emacs DNS Mode
- Wrangling Namespaces in Python
- Using Skype from Emacs
- Choosing the Right Technology
- Django, Testing, and Sessions
- KMS, xvideo-intel, and Arch Linux
- Verizon UMW-190 and Arch Linux
- Hawking Range Extender and Linux
- CUPS driver for the Dell 1320C Printer on Arch
- SANE and the Canon LIDE 20
- Getting easypg working in Ubuntu
Django, Testing, and Sessions
Published 2011-01-07
Working on my new site, I wanted to test a view. I’m new to python and the django, so I’m incrementally increasing my tool usage. Currently I’m sticking to unittest. I needed to set a session var, but the docs are a little light — so here’s what I did:
import unittest from django.conf import settings from django.test.client import Client class Test(unittest.TestCase): def setUp(self): # http://code.djangoproject.com/ticket/10899 settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file' engine = importlib.import_module('django.contrib.sessions.backends.file') store = engine.SessionStore() store.save() self.client = Client() self.session = store self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key def tearDown(self): store = self.session os.unlink(store._key_to_file()) def test_exception_no_next_stage(self): session = self.session session['foo'] = 'bar' session.save() response = self.client.get('/') self.assertEquals(...)
Your view for ‘/’ should see the session variable foo set to ‘bar’.
If you want to read a value from session in your unit test after you’ve got the response, then you need to load the data from the session:
session_data = session.load() self.assertEqual(session_data['foo'], 'baz')
Clearly this is a mess and needs more research.