user1187968
user1187968

Reputation: 8016

Django UnitTest - Setting session variable

I have a Django unit test class that is based on django_webtest.WebTest, and I can't find a proper way to set a session variable during the test. I have tried the following, but I don't work

from django_webtest import WebTest
class TestMyTests(WebTest):
    def test_my_tesst(self):
       ... 
       self.app.session['var1'] = 'val1'
       ...

Upvotes: 7

Views: 2163

Answers (2)

aredzko
aredzko

Reputation: 1730

That is generally what Client is for. It has access to the session data. I can't speak for django_webtest, since that's an outside library for django, but internally for unittesting, you can access and set session data like so:

import unittest
from django.test import Client

class TestMyTests(unittest.TestCase):

    def setUp(self):
        self.client = Client()

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

The above example was gleaned from the Django Documentation on testing tools.

Upvotes: 9

lmiguelvargasf
lmiguelvargasf

Reputation: 69903

If you are using pytest you can do the following:

import pytest

from django.test import Client

@pytest.mark.django_db # this is used if you are using the database
def test_my_tesst():
    # code before setting session
    c = Client()
    session = c.session
    session['var1'] = 'val1'
    session.save()
    # code after setting session

The most important is to save the session after changing it. Otherwise, it has no effect.

Upvotes: 1

Related Questions