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'
...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With