Calmcode - playwright: playwright in pytest

Combine Playwright and Pytest

1 2 3 4 5 6 7 8 9

Let's now actually write unit tests using Playwright. Having scripts is nice, but the typical use-case is testing. And in Python, that usually means using pytest.

First, install the pytest plugin.

python -m pip install pytest-playwright

From here, you can use playwright codegen to record your steps. You can then copy the code as Pytest code, by selecting "Pytest" from the dropdown.

from playwright.sync_api import Page, expect


def test_example(page: Page) -> None:
    page.goto("https://calmcode.io/")
    page.get_by_role("button", name="More").click()
    page.locator("#dropdown-button-1").get_by_role("link", name="Datasets").click()
    page.get_by_role("row", name="bigmac logo bigmac.csv An economic indicator? csv 1331 71KB Detailed Info").get_by_role("link", name="Detailed Info").click()
    page.get_by_role("button", name="Explore bigmac.csv").click()
    expect(page).to_have_url("https://calmcode-datasette.fly.dev/calmcode/bigmac", timeout=1000)

Assuming this test is saved in a file named test_e2e.py, you can have pytest run it via:

pytest test_e2e.py

The output should look familiar, it's just that right now the browser is running in the background on your behalf.