About Manipulating a Session in Unit Tests

You can modify user's session in unit tests using self.client.session:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.test import TestCase

class DashboardTest(TestCase):
    # …
    def test_dashboard_view(self):
        self.client.force_login(user=self.user)
        session = self.client.session
        session["workspace_id"] = self.workspace.pk
        session.save()
        response = self.client.get("/en/dashboard/")
        # … 

Tips and Tricks Programming Testing Django 4.2 Django 3.2 Django 2.2