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:
- Load the
SessionStoreof the currently used session engine at the import time. - Navigate to a web page and interact with it.
- Check the cookies and read the
sessionidcookie value. - Initiate the
sessionobject from theSessionStoreby the session id. - Access the keys of the
sessionobject.
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
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.