Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use session in TestCase in Django?

I would like to read some session variables from a test (Django TestCase)

How to do that in a clean way ?

def test_add_docs(self):
    """
    Test add docs
    """
    # I would access to the session here:
    self.request.session['documents_to_share_ids'] = [1]

    response = self.client.get(reverse(self.document_add_view_id, args=[1]), follow=True)
    self.assertEquals(response.status_code, 200)
like image 314
nicolas Avatar asked Sep 21 '11 15:09

nicolas


2 Answers

As of Django 1.7+ this is much easier. Make sure you set the session as a variable instead of referencing it directly.

def test_something(self):
    session = self.client.session
    session['somekey'] = 'test'
    session.save()

andreaspelme's workaround is only needed in older versions of django. See docs

like image 157
Bufke Avatar answered Sep 28 '22 14:09

Bufke


Unfortunately, this is not a easy as you would hope for at the moment. As you might have noticed, just using self.client.session directly will not work if you have not called other views that has set up the sessions with appropriate session cookies for you. The session store/cookie must then be set up manually, or via other views.

There is an open ticket to make it easier to mock sessions with the test client: https://code.djangoproject.com/ticket/10899

In addition to the workaround in the ticket, there is a trick that can be used if you are using django.contrib.auth. The test clients login() method sets up a session store/cookie that can be used later in the test.

If you have any other views that sets sessions, requesting them will do the trick too (you probably have another view that sets sessions, otherwise your view that reads the sessions will be pretty unusable).

from django.test import TestCase
from django.contrib.auth.models import User

class YourTest(TestCase):
    def test_add_docs(self):
        # If you already have another user, you might want to use it instead
        User.objects.create_superuser('admin', '[email protected]', 'admin')

        # self.client.login sets up self.client.session to be usable
        self.client.login(username='admin', password='admin')

        session = self.client.session
        session['documents_to_share_ids'] = [1]
        session.save()

        response = self.client.get('/')  # request.session['documents_to_share_ids'] will be available
like image 42
andreaspelme Avatar answered Sep 28 '22 16:09

andreaspelme