Writing the code
Right now, the only way to check that our todo list works is to click through it by hand.
Goal
- Understand how pytest and Playwright are set up in this project.
- Write a test that ticks a todo item and checks it gets crossed out, moves to the bottom and stays ticked.
- Write a test that opens and closes a description.
- Run the tests in headless and headed mode.
If you get stuck, you can see the finished code for this goal on the 5-playwright-tests branch.
1. Look at the setup
Everything is already installed. You ran uv sync and uv run playwright install when you set up the project. Let’s look at what’s there.
Open pyproject.toml. The testing packages are in the dev dependency group, next to django-browser-reload, because the app doesn’t need them to run:
pyproject.toml
[dependency-groups]
dev = [
"django-browser-reload>=1.21.0",
"pytest>=9.2.0",
"pytest-django>=4.14.0",
"pytest-env>=1.8.8",
"pytest-playwright>=0.10.0",
]pytestruns our tests.pytest-djangolets pytest talk to Django, and gives us thelive_serverfixture.pytest-playwrightgives us thepagefixture, and installs Playwright itself.pytest-envsets environment variables while the tests run. We’ll see why we need it below.
Further down, there’s the pytest settings:
pyproject.toml
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "config.settings"
[tool.pytest_env]
# Playwright runs an event loop, which makes Django think we're in async code.
DJANGO_ALLOW_ASYNC_UNSAFE= "true"DJANGO_SETTINGS_MODULEtells pytest-django where our Django settings live.[tool.pytest_env]lists environment variables for pytest-env to set before the tests start.DJANGO_ALLOW_ASYNC_UNSAFEturns off one of Django’s safety checks. Without it, every test that touches the database fails.
DJANGO_ALLOW_ASYNC_UNSAFE?
Playwright runs an event loop behind the scenes, the machinery Python uses for async code. When Django sees an event loop running, it assumes it’s inside async code, and refuses to run database queries in case they block it. Without the variable, you’ll see this:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Our tests aren’t really async, so it’s safe to switch the check off. It’s only set while the tests run, never when the real app runs. See the Django async safety docs for more.
There’s already one test. Open todo/tests/test_playwright_installed.py:
todo/tests/test_playwright_installed.py
from playwright.sync_api import Page, expect
def test_home_page_loads(page: Page, live_server):
page.goto(live_server.url)
expect(page).to_have_title("Todo")
expect(page.get_by_role("heading", name="Get this done")).to_be_visible()pageis a fresh browser tab from pytest-playwright.live_serveris a real Django server from pytest-django, running in the background.page.goto(live_server.url)opens the home page in the browser.- The two
expectlines check the page title and the heading.
2. Run the tests headless
Run the tests:
uv run pytestYou should see 1 passed. A browser opened, loaded the page, checked it and closed again. You didn’t see it, because by default Playwright runs headless: no window.
3. Run the tests headed
Now run them headed, so the browser window opens:
uv run pytest --headedA browser window flashes up and disappears. It’s too fast to see much, so slow it down. --slowmo waits the given number of milliseconds before each thing Playwright does:
uv run pytest --headed --slowmo 5000Now you can watch the page load before the window closes.
The page shows no todo items, even if you added some while running the app. That’s expected. When pytest runs, pytest-django creates a separate test database and points the app at it. The test database starts empty, and it’s thrown away when the tests finish, so your real data is never touched.
Headed mode is handy when a test fails and you can’t work out why. Use headless the rest of the time, because it’s faster.
4. Test ticking a todo item
Create a new file, todo/tests/test_todo_list.py. Start with the imports:
todo/tests/test_todo_list.py
import re
from playwright.sync_api import Page, expect
from todo.models import TodoItemThe test database starts empty, so the test creates its own todo items first. Add the test:
todo/tests/test_todo_list.py
def test_ticking_an_item_crosses_it_out_and_moves_it_down(page: Page, live_server):
TodoItem.objects.create(title="Buy milk")
TodoItem.objects.create(title="Walk the dog")
page.goto(live_server.url)
item = page.locator("#todo-list > div").filter(has_text="Buy milk")
item.get_by_role("checkbox").click()
expect(item.get_by_text("Buy milk")).to_have_class(re.compile("line-through"))
expect(page.locator("#todo-list > div").last).to_contain_text("Buy milk")
page.reload()
expect(item.get_by_role("checkbox")).to_be_checked()TodoItem.objects.create(...)adds two items to the test database. “Buy milk” starts at the top of the list.page.locator("#todo-list > div")finds every todo item in the list..filter(has_text="Buy milk")keeps the one with “Buy milk” in it.item.get_by_role("checkbox").click()ticks it, just like a user would.to_have_class(re.compile("line-through"))checks the title is crossed out.re.compilemeans the class only needs to containline-through, because the element has other classes too..lastis the last todo item in the list. We check it’s “Buy milk”, so the item moved to the bottom.page.reload()loads the page again from scratch. If the checkbox is still ticked, the change was saved to the database.
Notice that there’s no waiting code. HTMX takes a moment to send the request and swap in the new list, and expect keeps checking until it does.
Run the tests:
uv run pytestYou should see 2 passed. 🎉
Run it headed and slow, and watch it tick the box:
uv run pytest --headed --slowmo 10005. Test opening and closing a description
Add a second test to the same file. This one creates an item with a description, then checks the arrow opens and closes it:
todo/tests/test_todo_list.py
def test_arrow_shows_and_hides_the_description(page: Page, live_server):
TodoItem.objects.create(title="Buy milk", description="Full cream")
page.goto(live_server.url)
description = page.get_by_text("Full cream")
expect(description).to_be_hidden()
page.get_by_role("button").click()
expect(description).to_be_visible()
page.get_by_role("button").click()
expect(description).to_be_hidden()to_be_hidden()checks the description isn’t showing. Remember, it’s in the HTML, but Alpine hides it withx-show. The test client could never check this.get_by_role("button").click()clicks the arrow.to_be_visible()checks the description is now showing.
Run the tests:
uv run pytestIt doesn’t work! You’ll see an error like this:
playwright._impl._errors.Error: Locator.click: Error: strict mode violation: get_by_role("button") resolved to 2 elements:
1) <button x-on:click="open = ! open" ...>…</button> aka locator("#todo-item-3").get_by_role("button")
2) <button type="submit">Add</button> aka get_by_role("button", name="Add")
Playwright found two buttons: our arrow, and the Add button at the bottom of the form. It doesn’t know which one to click, so it refuses to guess. This is called strict mode, and it stops tests from clicking the wrong thing by accident.
Fix it the same way as the first test: find the todo item, then look for the button inside it.
todo/tests/test_todo_list.py
def test_arrow_shows_and_hides_the_description(page: Page, live_server):
TodoItem.objects.create(title="Buy milk", description="Full cream")
page.goto(live_server.url)
item = page.locator("#todo-list > div").filter(has_text="Buy milk")
description = item.get_by_text("Full cream")
expect(description).to_be_hidden()
item.get_by_role("button").click()
expect(description).to_be_visible()
item.get_by_role("button").click()
expect(description).to_be_hidden()Here’s the whole file now:
todo/tests/test_todo_list.py
import re
from playwright.sync_api import Page, expect
from todo.models import TodoItem
def test_ticking_an_item_crosses_it_out_and_moves_it_down(page: Page, live_server):
TodoItem.objects.create(title="Buy milk")
TodoItem.objects.create(title="Walk the dog")
page.goto(live_server.url)
item = page.locator("#todo-list > div").filter(has_text="Buy milk")
item.get_by_role("checkbox").click()
expect(item.get_by_text("Buy milk")).to_have_class(re.compile("line-through"))
expect(page.locator("#todo-list > div").last).to_contain_text("Buy milk")
page.reload()
expect(item.get_by_role("checkbox")).to_be_checked()
def test_arrow_shows_and_hides_the_description(page: Page, live_server):
TodoItem.objects.create(title="Buy milk", description="Full cream")
page.goto(live_server.url)
item = page.locator("#todo-list > div").filter(has_text="Buy milk")
description = item.get_by_text("Full cream")
expect(description).to_be_hidden()
item.get_by_role("button").click()
expect(description).to_be_visible()
item.get_by_role("button").click()
expect(description).to_be_hidden()6. Try it out
Run the tests headless:
uv run pytestYou should see 3 passed. 🎉
Now watch them run:
uv run pytest --headed --slowmo 1000You’ll see a browser tick “Buy milk” and move it to the bottom, then open and close the description.
Let’s make sure the tests can actually catch a bug. Open todo/templates/todo/partials/todo_item.html and remove x-show="open" from the description <p>. Run the tests again. test_arrow_shows_and_hides_the_description fails, because the description is visible from the start. Put x-show="open" back, and the tests pass again.
Recap
- We use pytest-django’s
live_serverto run a real Django server, and pytest-playwright’spageto drive a real browser. - We use pytest-env to set
DJANGO_ALLOW_ASYNC_UNSAFE, so Django lets Playwright tests use the database. - We run tests headless by default, and use
--headedand--slowmoto watch them. - We create our own test data, because the test database starts empty.
- We use
expectto check what the user sees. It waits for HTMX and Alpine to finish, so we don’t need to. - We narrow locators down to one todo item, so strict mode knows exactly which element we mean.