Playwright Python First Test
Your First Python Test
A Playwright test in Python is a pytest function that controls a browser.
In this chapter you write the same todo list test as in the First Test chapter, in Python.
The test uses our practice page: Todo List.
Write the Test
Create a file named test_todo.py in the tests folder of your project.
Example
tests/test_todo.py
import re
from playwright.sync_api import Page, expect
def test_has_title(page: Page):
page.goto("https://www.w3schools.com/playwright/practice/todo.html")
expect(page).to_have_title(re.compile("Todo List"))
def test_can_add_todo(page: Page):
page.goto("https://www.w3schools.com/playwright/practice/todo.html")
page.get_by_placeholder("What needs to be done?").fill("Learn Playwright")
page.get_by_role("button", name="Add").click()
expect(page.get_by_text("Learn Playwright")).to_be_visible()
expect(page.get_by_test_id("todo-count")).to_have_text("1 item left")
Example Explained
from playwright.sync_api import Page, expectloads thePagetype and theexpectfunctiondef test_has_title(page: Page)creates a test. pytest runs every function whose name starts withtestpageis a fixture: pytest-playwright sees the argument name and passes in a fresh browser tabpage.goto()opens a URLexpect(page).to_have_title()checks the page title.re.compile()makes it a regular expression, so the title only has to contain "Todo List"get_by_placeholder(),get_by_role(),get_by_text()andget_by_test_id()find elements on the pagename="Add"is a keyword argument, where JavaScript writes{ name: 'Add' }to_be_visible()andto_have_text()check the result
There is no await anywhere.
The Python test uses the sync API: each line finishes before the next one starts.
Each test gets its own clean browser tab, just like in JavaScript.
Run the Test
Run all tests from the project folder:
Example
pytest
Output:
============================= test session starts =============================
platform win32 -- Python 3.9.13, pytest-8.4.2, pluggy-1.6.0
rootdir: /home/user/my-project
plugins: base-url-2.1.0, playwright-0.7.1
collected 2 items
tests/test_todo.py .. [100%]
============================== 2 passed in 2.96s ==============================
Each dot is a passed test.
The platform line shows your own system and versions.
By default the tests run headless (without a visible browser window), in Chromium, one after the other.
Command Line Options
You choose how the tests run with options after pytest.
Add -v to see the name of each test, and --browser to choose the browser:
Example
pytest -v --browser chromium
Output:
============================= test session starts =============================
platform win32 -- Python 3.9.13, pytest-8.4.2, pluggy-1.6.0
rootdir: /home/user/my-project
plugins: base-url-2.1.0, playwright-0.7.1
collecting ... collected 2 items
tests/test_todo.py::test_has_title[chromium] PASSED [ 50%]
tests/test_todo.py::test_can_add_todo[chromium] PASSED [100%]
============================== 2 passed in 1.92s ==============================
The browser name is shown in brackets after each test.
Repeat --browser to run every test in more than one browser, for example --browser chromium --browser webkit.
The most used options:
| Option | Description |
|---|---|
| -v | Show each test by name |
| --browser chromium | The browser to use: chromium, firefox or webkit. Default is chromium |
| --headed | Show the browser window while the tests run |
| --slowmo 500 | Slow down every action by 500 milliseconds, so you can see each step |
| --base-url URL | The start of every relative URL in page.goto() |
| --tracing on | Record a trace of every test. Also retain-on-failure |
| --screenshot on | Save a screenshot after every test. Also only-on-failure |
| -k name | Run only the tests whose name contains this text |
To watch the test in a real window, run it headed and a little slower:
Example
pytest --headed --slowmo 500
Set a Base URL
Writing the full URL in every test is long.
With a base URL, page.goto("todo.html") is enough.
Put the options you always want in a pytest.ini file in the project folder:
Example
pytest.ini
[pytest]
addopts = --base-url https://www.w3schools.com/playwright/practice/ --browser chromium
Now the test can use a short URL:
Example
tests/test_todo.py
from playwright.sync_api import Page, expect
def test_can_add_todo(page: Page):
page.goto("todo.html")
page.get_by_placeholder("What needs to be done?").fill("Learn Playwright")
page.get_by_role("button", name="Add").click()
expect(page.get_by_test_id("todo-count")).to_have_text("1 item left")
Run it with -v:
Example
pytest -v
Output:
============================= test session starts =============================
platform win32 -- Python 3.9.13, pytest-8.4.2, pluggy-1.6.0
baseurl: https://www.w3schools.com/playwright/practice/
rootdir: /home/user/my-project
configfile: pytest.ini
plugins: base-url-2.1.0, playwright-0.7.1
collecting ... collected 1 item
tests/test_todo.py::test_can_add_todo[chromium] PASSED [100%]
============================== 1 passed in 1.83s ==============================
This is the Python version of baseURL in playwright.config.js.
pytest reads pytest.ini on every run, and prints the base URL and the config file at the top.
When a Test Fails
Change the expected text in the second test from "1 item left" to "2 items left", and run the tests again.
Example
expect(page.get_by_test_id("todo-count")).to_have_text("2 items left")
Now pytest marks the test with an F, and shows what Playwright expected and what it got:
Output:
============================= test session starts =============================
platform win32 -- Python 3.9.13, pytest-8.4.2, pluggy-1.6.0
rootdir: /home/user/my-project
plugins: base-url-2.1.0, playwright-0.7.1
collected 2 items
tests/test_todo.py .F [100%]
================================== FAILURES ===================================
_________________________ test_can_add_todo[chromium] _________________________
page = <Page url='https://www.w3schools.com/playwright/practice/todo.html'>
def test_can_add_todo(page: Page):
page.goto("https://www.w3schools.com/playwright/practice/todo.html")
page.get_by_placeholder("What needs to be done?").fill("Learn Playwright")
page.get_by_role("button", name="Add").click()
expect(page.get_by_text("Learn Playwright")).to_be_visible()
> expect(page.get_by_test_id("todo-count")).to_have_text("2 items left")
E AssertionError: Locator expected to have text '2 items left'
E Actual value: 1 item left
E Call log:
E - Expect "to_have_text" with timeout 5000ms
E - waiting for get_by_test_id("todo-count")
E 14 × locator resolved to <p id="count" data-testid="todo-count">1 item left</p>
E - unexpected value "1 item left"
tests/test_todo.py:15: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_todo.py::test_can_add_todo[chromium] - AssertionError: Loca...
========================= 1 failed, 1 passed in 7.19s =========================
The > marks the line that failed.
The call log shows that Playwright checked the text again and again for 5 seconds, and then failed the test.
This is the same auto-waiting as in JavaScript.
Record a Trace
A trace records every step of a test: the actions, the page before and after each one, the network requests and the browser console messages.
Run the tests with tracing on:
Example
pytest --tracing on
pytest-playwright saves one trace.zip per test in the test-results folder:
test-results/
tests-test-todo-py-test-can-add-todo-chromium/
trace.zip
tests-test-todo-py-test-has-title-chromium/
trace.zip
Open a trace in the Trace Viewer:
Example
playwright show-trace test-results/tests-test-todo-py-test-can-add-todo-chromium/trace.zip
The Trace Viewer opens in a window.
It shows a timeline of the test, and you can click each action to see the page at that moment.
It is the same tool as in JavaScript.
Read more about it in the Trace Viewer chapter.
Tip: Use --tracing retain-on-failure to keep traces only for the tests that fail.