7

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'
       ...
user1187968
  • 7,154
  • 16
  • 81
  • 152

2 Answers2

9

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.

aredzko
  • 1,690
  • 14
  • 14
  • Why not set the session up under `setUp`? – alias51 Jul 04 '20 at 16:47
  • @alias51 You can if you want. That's more of a style question. If they're making heavy use of one particular session key, then yes it should be done in the setup. If this is a one-off (maybe testing some kind of data being present for a single case), this is fine. – aredzko Jul 07 '20 at 19:08
1

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.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228