Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
       ...
like image 897
user1187968 Avatar asked Jul 05 '16 13:07

user1187968


People also ask

What is Unittest in Django?

Unit Tests are isolated tests that test one specific function. Integration Tests, meanwhile, are larger tests that focus on user behavior and testing entire applications. Put another way, integration testing combines different pieces of code functionality to make sure they behave correctly.


2 Answers

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.

like image 111
tredzko Avatar answered Nov 04 '22 11:11

tredzko


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.

like image 22
lmiguelvargasf Avatar answered Nov 04 '22 10:11

lmiguelvargasf