About Reading Django Session in Playwright Tests

To read the Django session values in Playwright tests for a Django website, you would need this sequence:

  1. Load the SessionStore of the currently used session engine at the import time.
  2. Navigate to a web page and interact with it.
  3. Check the cookies and read the sessionid cookie value.
  4. Initiate the session object from the SessionStore by the session id.
  5. Access the keys of the session object.

Here is the full example:

import os
from importlib import import_module
from urllib.parse import unquote
from django.conf import settings
from django.test import LiveServerTestCase
from playwright.sync_api import (
    sync_playwright, Page, Browser, BrowserContext
)

SessionStore = import_module(settings.SESSION_ENGINE).SessionStore


class PlaywrightUserSessionTest(LiveServerTestCase):
    host = "127.0.0.1"
    port = 8001  # pick any free port

    @classmethod
    def setUpClass(cls):
        os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
        super().setUpClass()
        cls.playwright = sync_playwright().start()
        cls.browser = cls.playwright.chromium.launch(headless=True)
        cls.context = cls.browser.new_context(
            viewport={"width": 1280, "height": 720},
        )

    @classmethod
    def tearDownClass(cls):
        cls.context.close()
        cls.browser.close()
        cls.playwright.stop()
        super().tearDownClass()

    def setUp(self):
        super().setUp()
        self.page = self.context.new_page()

    def tearDown(self):
        self.page.close()
        super().tearDown()

    def test_check_session_value(self):
        self.page.goto(f"{self.live_server_url}/interactive/")

        # trigger clicking here and there by Playwright commands...

        cookies = {
            cookie["name"]: unquote(cookie["value"])
            for cookie in self.context.cookies()
        }

        session = SessionStore(session_key=cookies["sessionid"])

        self.assertEqual(session.get("skillpoints"), 50)

Tips and Tricks Programming Testing Django 6.x Django 5.2 Django 4.2 Playwright