Playwright with Django Reliable end-to-end testing for the web

Playwright with Django

You can use Playwright to test views in Django web apps.

To install Playwright, and the browsers to test on, run:

pip install playwright
python –m playwright install

Playwright integrates with the built-in testing tools in Django.

Specifically, you can use the LiveServerTestCase class to launch a live Django server and run browser tests against it.

 1 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
 2 from playwright import sync_playwright
 3
 4 class MyViewTests(StaticLiveServerTestCase):
 5     @classmethod
 6     def setUpClass(cls):
 7         super().setUpClass()
 8         cls.playwright = sync_playwright().start()
 9         cls.browser = cls.playwright.chromium.launch()
10
11     @classmethod
12     def tearDownClass(cls):
13         cls.browser.close()
14         cls.playwright.stop()
15         super().tearDownClass()
16
17     def test_login(self):
18         page = self.browser.newPage()
19         page.goto('%s%s' % (self.live_server_url, '/login/'))
20         page.fill('#username', 'myuser')
21         page.fill('#password', 'secret')
22         page.click('text=Log in')
23         assert page.url == '%s%s' % (self.live_server_url, '/profile/')
24         page.close()

Another example

 1"""pw_recherche.py
 2
 3- python -m playwright codegen http://localhost:8004/
 4- export MY_IMPRONONCIABLE=
 5
 6"""
 7import logging
 8import os
 9import sys
10import time
11from pathlib import Path
12
13from playwright.sync_api import Page
14from playwright.sync_api import sync_playwright
15from rich import inspect
16
17logger = logging.getLogger(__name__)
18
19
20def get_login(page: Page):
21    # Click text="Login"
22    page.click('text="Login"')
23    # assert page.url == "http://localhost:8004/"
24    # Click input[name="username"]
25    page.click('input[name="username"]')
26    # Fill input[name="username"]
27    page.fill('input[name="username"]', "pvergain")
28    # Click input[name="password"]
29    page.click('input[name="password"]')
30    # Fill input[name="password"]
31    try:
32        le_mot_quon_ne_prononce_pas = os.environ["MY_IMPRONONCIABLE"]
33    except KeyError:
34        logger.error(
35            "La variable d'environnement 'MY_IMPRONONCIABLE' n'est pas initialisée."
36        )
37        logger.error("export MY_IMPRONONCIABLE=")
38        sys.exit(-1)
39    page.fill('input[name="password"]', le_mot_quon_ne_prononce_pas)
40    # Click text="Log id3 intranet"
41    page.click('text="Log id3 intranet"')
42    assert page.url == "http://localhost:8004/"
43
44
45playwright = sync_playwright().start()
46browser = playwright.chromium.launch(headless=False)
47context = browser.new_context()
48page = context.new_page()
49# Go to http://localhost:8004/
50page.goto("http://localhost:8004/")
51# Click text="Masquer »"
52page.click('text="Masquer »"')
53get_login(page)
54# Click text="Demandes"
55page.click('text="Demandes"')
56# Click text="Liste de toutes les demandes"
57page.click('text="Liste de toutes les demandes"')
58assert page.url == "http://localhost:8004/articles/demandes/list/"
59# Click input[name="description"]
60page.click('input[name="description"]')
61# Fill input[name="description"]
62page.fill('input[name="description"]', "câble")
63# Click input[name="btn_form_filtre"]
64page.click('input[name="btn_form_filtre"]')
65assert page.url == "http://localhost:8004/articles/demandes/list/"
66# Click text="2"
67page.fill('input[name="description"]', "câble")
68page.goto(
69    "http://localhost:8004/articles/demandes/list/?page=1&from_date=1/04/1990&to_date=17/02/2021&type_demande=None&demandeur=&projet=&description=câble&etat_demande=None"
70)
71rep_demandes = Path.cwd() / "demandes"
72if not rep_demandes.exists():
73    rep_demandes.mkdir()
74page.screenshot(path=rep_demandes / "page_1_cable.png")
75print(page.url)
76time.sleep(3)
77page.goto(
78    "http://localhost:8004/articles/demandes/list/?page=5&from_date=1/04/1990&to_date=17/02/2021&type_demande=None&demandeur=&projet=&description=câble&etat_demande=None"
79)
80page.screenshot(path=rep_demandes / "page_5_cable.png")
81time.sleep(3)
82browser.close()
83playwright.stop()

Deploy Playwright tests to CI/CD

Running end-to-end tests in your CI/CD pipelines helps catch issues early.

You can deploy Playwright tests to CI/CD with the Playwright GitHub Action or with tools for other CI/CD providers .

Playwright for Python is built in the open on GitHub, and we are eager to learn more on how Playwright works for you.

Feel free to share feedback or feature requests on GitHub issues or join the Playwright Slack community to connect with other users.