Test Django session in unit testing for created and modified session by views


Sometimes we need to test Django session in our unit testing to see that view already modified / created a session. Basically, we only need to use File Backend Storage to handle sessions that made in Unit testing. So, let starts with create a new test :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from importlib import import_module

from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.conf import settings

class ExampleTestCase(TestCase):
    """Example Unit Testing"""

    def setUp(self):
        # Set session using file backend
        # http://code.djangoproject.com/ticket/10899
        settings.SESSION_ENGINE = ‘django.contrib.sessions.backends.file’
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()

        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())


When running this unit-testing, it will use File backend storage for storing sessions.
Now, we ready to use :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def test_example_currencies_code(self):
    """
    Cases:
        User already have USD for default currency, then changes into INR.
    """
    # Set user currency for USD
    session = self.session
    session[‘user-currency’] = Currency.objects.get(code="USD")
    session.save()

    # Default currency is USD
    self.assertEqual(self.client.session[‘user-currency’].code, "USD")
    url = reverse("currencies:convert_code", kwargs={"code": "INR"})
    request = self.client.get(url, follow=True)

    # Default currency changes into INR
    self.assertEqual(self.client.session[‘user-currency’].code, "INR")

At this example, you will see that I create a new session called “user-currency” which “USD” as the default value.

Then, I open my convert_code pages and views will modify this “user-currency” session based on given param:

1
reverse("currencies:convert_code", kwargs={"code": "INR"})

Then, the last steps, we need to check if the sessions is modified or not by:

1
self.assertEqual(self.client.session[‘user-currency’].code, "INR")

Now you can test Django Session in your unit testing


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.