About Logging In the User in Selenium Tests

You can log in the user in Selenium tests by copying the session cookie from test client to Selenium driver:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.test import LiveServerTestCase

class BrowserTest(LiveServerTestCase):
    ...
    def test_authenticated_view(self):
        self.client.login(
            email="user@example.com", password="secret"
        )
        # Load any path that doesn't require authentication
        self.browser.get(f"{self.live_server_url}/404/")
        cookie = {
            "name": settings.SESSION_COOKIE_NAME,
            "value": self.client.session.session_key,
            "path": "/",
            "domain": settings.SESSION_COOKIE_DOMAIN,
        }
        self.browser.add_cookie(cookie)

        self.browser.get(f"{self.live_server_url}/")

Tips and Tricks Programming Testing Django 4.2 Django 3.2 Django 2.2 Selenium