BeginnerLesson 12 of 4712 min read12 runnable examples
Operators are the symbols that do the work in an expression: they add numbers, compare values and combine conditions. This lesson covers all seven groups of Python operators and the booleans they produce.
score=72print(score==72,score!=72)print(score>50,score<=60)print("apple"<"banana")# strings compare alphabeticallyprint(10==10.0)# int and float with the same value are equal
Output
True False
True False
True
True
Python lets you chain comparisons, just like in maths:
and stops at the first falsy value and or stops at the first truthy value. They return that value itself, not always True/False. This gives two handy idioms:
Python
name=""display=nameor"Guest"# default when name is emptyprint(display)items=[]print(len(items)>0anditems[0])# items[0] is never evaluated
Output
Guest
False
Booleans and truthiness
True and False are the two boolean values, and bool is a subclass of int. In an if or while, any value is treated as true or false:
Bitwise operators work on the binary digits of integers. You will meet them in permissions, flags and low-level code.
Python
a,b=6,3# 110 and 011 in binaryprint(a&b,a|b,a^b)print(~a,a<<1,a>>1)
Output
2 7 5
-7 12 3
Operator precedence
From highest to lowest (operators on the same row are evaluated left to right, except **):
Precedence
Operators
1
() parentheses
2
**
3
+x, -x, ~x
4
*, /, //, %
5
+, -
6
bitwise: << and >>, then &, then ^, then bitwise OR
7
comparisons, in, not in, is, is not
8
not
9
and
10
or
Python
print(TrueorFalseandFalse)# and binds tighter: True or (False and False)print(not1==2)# not (1 == 2)
Output
True
True
Check your understanding
Predict the output
x=5print(x>3andx<10,x>3or1/0,0or""or"last")
Output
True True last
The first is True and True. In the second, or stops at the truthy x > 3, so 1 / 0 never runs. The third returns the first truthy value, and since none of the earlier ones are, it returns the last value.
Quick quiz
1. What does 10 != 10.0 return?
10 == 10.0 is True, so != gives False.
2. What does "" or "default" return?
or returns the first truthy value.
3. Which checks whether x is None?
is None is the recommended, fastest and safest check.
4. What does 1 < 3 < 2 evaluate to?
It means 1 < 3 and 3 < 2, and 3 < 2 is False.
Exercise: leap year check
A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Print each year with True or False.
Input
1900, 2000, 2024, 2026
Expected output
1900 False
2000 True
2024 True
2026 False
Hint 1
Combine % with and and or.
Hint 2
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0
1900 is divisible by 100 but not 400, so it is not a leap year. 2000 passes the 400 rule. The parentheses make the grouping obvious even though and already binds tighter than or.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
BeginnerLesson 11 of 479 min read8 runnable examples
Type casting means converting a value from one type to another, such as turning the text “42” from input() into the number 42. Python does some conversions for you, and you do the rest with built-in functions named after the types.
In this lesson
Implicit vs explicit conversion
Convert between numbers and strings
Convert between collections
Handle values that cannot be converted
Implicit conversion
When you mix an int and a float in arithmetic, Python converts the int to a float for you, so no precision is lost:
Python
qty=3# intprice=19.5# floattotal=qty*priceprint(total,type(total).__name__)print(True+True)# bool is a kind of int: True is 1
Output
58.5 float
2
Python will not guess between text and numbers. Mixing them is an error:
Python
age=30print("Age: "+age)
Output
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Age: " + age)
~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str
Explicit conversion functions
Function
Converts to
Example
Result
int(x)
whole number
int("42"), int(9.8)
42, 9
float(x)
decimal
float("3.5"), float(2)
3.5, 2.0
str(x)
text
str(100)
'100'
bool(x)
True/False
bool(0), bool("no")
False, True
list(x)
list
list("abc")
['a', 'b', 'c']
tuple(x)
tuple
tuple([1, 2])
(1, 2)
set(x)
set
set([1, 1, 2])
{1, 2}
dict(x)
dict
dict([("a", 1)])
{'a': 1}
Numbers and strings
Python
age=30print("Age: "+str(age))# number to textprint(int("42")+8)# text to numberprint(float("3.75")*2)print(int(9.99),int(-9.99))# int() truncates towards zeroprint(int(" 15\n"))# surrounding whitespace is ignored
Output
Age: 30
50
7.5
9 -9
15
int() can also read numbers written in other bases:
Python
print(int("ff",16),int("0b1010",0),int("777",8))
Output
255 10 511
Values that cannot be converted
Python
print(int("3.5"))
Output
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(int("3.5"))
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'
int() will not read a decimal string. Convert to float first, or catch the error:
Python
print(int(float("3.5")))fortextin["12","4.0","abc"]:try:print(text,"->",int(text))exceptValueError:print(text,"-> not a whole number")
Output
3
12 -> 12
4.0 -> not a whole number
abc -> not a whole number
Converting to bool
bool() returns False for “empty” or zero values and True for everything else.
bool("False") is True, because it is a non-empty string. To read a yes/no answer, compare the text: answer.strip().lower() in ("yes", "y", "true").
Between collections
Python
letters=list("banana")print(letters)print(set(letters))# duplicates removedprint(tuple(letters[:3]))print("".join(letters))# list of strings back to one stringpairs=[("chrome",120),("firefox",118)]print(dict(pairs))print(list({"x":1,"y":2}))# a dict converts to its keys
How do I convert a string to an integer in Python?
Use int("42"). If the string may contain a decimal point, use int(float(text)), and wrap it in try / except ValueError for user input.
How do I convert an integer to a string?
Use str(42), or put it in an f-string: f"{42}".
What is the difference between implicit and explicit type conversion?
Implicit conversion is done by Python automatically, such as int to float in 3 * 1.5. Explicit conversion is when you call a function such as int() or str() yourself.
How do I convert a list to a string?
Use ", ".join(items) for a list of strings. For other values, convert each one first: ", ".join(map(str, numbers)).
BeginnerLesson 10 of 4711 min read12 runnable examples
Python has three number types and a rich set of tools for working with them. This lesson covers arithmetic, rounding, the float precision trap, the math module and random numbers.
In this lesson
int, float and complex numbers
Arithmetic including // and %
Rounding and float precision
The math and random modules
Three number types
Python
count=42# int: whole number, any sizeratio=0.75# float: decimal numbersignal=3+4j# complex: real + imaginary partprint(type(count).__name__,type(ratio).__name__,type(signal).__name__)print(abs(signal))# length of the complex number
Output
int float complex
5.0
Large numbers are easier to read with underscores. Python ignores them:
n % 2 == 0 is the standard test for an even number. Many practice programs use it.
Order of operations
Python follows the usual maths rules: * first, then , /, //, %, then + and -. Use parentheses to make your intent clear.
Python
print(2+3*4)print((2+3)*4)print(2**3**2)# ** groups from the right: 2 ** 9print(-2**2)# ** binds tighter than the minus sign
Output
14
20
512
-4
Rounding
Python
price=2.675print(round(price,2))print(round(2.5),round(3.5))# ties round to the even numberprint(int(7.9),int(-7.9))# int() cuts off the decimals
Output
2.67
2 4
7 -7
round(2.5) gives 2 because Python uses “banker’s rounding”: a tie goes to the nearest even number. round(2.675, 2) gives 2.67 because 2.675 cannot be stored exactly as a float; it is really slightly less.
The random module picks pseudo-random values. random.seed() makes the sequence repeatable, which is useful in tests.
Python
importrandomrandom.seed(7)print(random.randint(1,6))# dice roll: 1 to 6 inclusiveprint(random.choice(["red","green","blue"]))print(round(random.random(),3))# float from 0.0 up to 1.0
What is the difference between / and // in Python?
/ is true division and always returns a float (7 / 2 is 3.5). // is floor division and rounds down (7 // 2 is 3).
Why does 0.1 + 0.2 not equal 0.3 in Python?
Floats are stored in binary, which cannot represent 0.1 exactly. The result is 0.30000000000000004. Use math.isclose() or decimal.Decimal when exactness matters.
How do I round a number to 2 decimal places in Python?
Use round(x, 2) to get a number, or f"{x:.2f}" to get a string for display.
BeginnerLesson 7 of 478 min read7 runnable examples
input() pauses your program and waits for the user to type something and press Enter. It is the simplest way to make a program interactive, and it is used in many practice programs.
In this lesson
Read text with input()
Convert input to numbers
Read several values from one line
Handle input that is not a number
Read text with input()
input() shows an optional prompt, waits for the user and returns what they typed as a string.
Python
name=input("What is your name? ")print("Hello,",name)
Outputtyped input: Asha
What is your name? Asha
Hello, Asha
Note
When you press Try it and Run on this site, your browser shows a small box for each input(). The recorded output above shows a run where the user typed Asha, exactly as it appears in a terminal.
input() always returns a string
Even if the user types digits, you get a string. Adding two strings joins them instead of adding numbers:
split() breaks a string on spaces and returns a list. Combine it with map() to convert every part:
Python
numbers=input("Enter numbers separated by spaces: ").split()print(numbers)values=list(map(int,numbers))print(sum(values))
Outputtyped input: 10 20 30
Enter numbers separated by spaces: 10 20 30
['10', '20', '30']
60
Unpack directly into variables when you know how many values to expect:
Python
width,height=map(int,input("Width and height: ").split())print("Pixels:",width*height)
Outputtyped input: 1920 1080
Width and height: 1920 1080
Pixels: 2073600
Handle invalid input
If the user types abc, int() cannot convert it and raises a ValueError:
Python
age=int(input("Age: "))
Outputtyped input: abc
Age: abc
Traceback (most recent call last):
File "main.py", line 1, in <module>
age = int(input("Age: "))
ValueError: invalid literal for int() with base 10: 'abc'
Catch the error with try / except and ask again. The Exception Handling lesson explains this pattern fully.
Python
whileTrue:text=input("Age: ")try:age=int(text)exceptValueError:print(f"{text!r} is not a whole number, try again")continueifage<0:print("Age cannot be negative")continuebreakprint("Age saved:",age)
Outputtyped input: abc, -3, 29
Age: abc
'abc' is not a whole number, try again
Age: -3
Age cannot be negative
Age: 29
Age saved: 29
Tip
text.strip() removes spaces the user typed by accident before or after the value. Use it before comparing input, for example input().strip().lower() == "yes".
Check your understanding
Quick quiz
1. The user types 8. What is the type of input()‘s result?
input() always returns a string. Convert it with int() when you need a number.
2. What does "3" + "4" give?
+ joins two strings, so the result is '34'.
3. Which reads two whole numbers typed on one line as 4 9?
split() gives two strings, and map(int, ...) converts each one.
Exercise: rectangle calculator
Ask for the width and height on one line and print the area and the perimeter.
Input
4 6
Expected output
Width and height: 4 6
Area: 24
Perimeter: 20
Hint 1
split() then map(int, ...) gives you two numbers.
Hint 2
Perimeter is 2 * (width + height).
Python
w,h=map(int,input("Width and height: ").split())print("Area:",w*h)print("Perimeter:",2*(w+h))
Outputtyped input: 4 6
Width and height: 4 6
Area: 24
Perimeter: 20
map(int, ...) converts both parts at once and unpacking assigns them to w and h. The rest is plain arithmetic.
Program Practice
Many basic programs read their values with input(). Try changing a solution to ask the user instead of using fixed values.
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
BeginnerLesson 6 of 4710 min read10 runnable examples
print() is how your program talks to you, and comments are how you talk to the next person who reads your code. Both look simple, but a few options make them far more useful.
In this lesson
Print several values at once
Control separators with sep and end
Print variables neatly with f-strings
Write comments and docstrings that help
The print() function
print() writes text to the screen and then moves to a new line. You can give it any value: text, numbers, lists or the result of a calculation.
Python
print("Hello, Python")print(42)print(3.5*2)print([1,2,3])print()# an empty lineprint("after the blank line")
Output
Hello, Python
42
7.0
[1, 2, 3]
after the blank line
Print several values
Separate values with commas. print() converts each one to text and puts a space between them, so you can mix text and numbers without converting anything.
end sets what is printed after the last value. The default is a newline ("\n"), so each print() starts a new line. Change it to keep printing on the same line.
A comment starts with #. Python ignores everything from # to the end of the line. Use comments to explain why the code does something, not what it obviously does.
Python
# Prices are stored in paise to avoid rounding errors with floatsprice_paise=149950discount=0.10# 10% festival discount, ends 15 Novfinal=price_paise*(1-discount)print(final/100)
Output
1349.55
Multi-line comments
Python has no special multi-line comment. Put # at the start of each line. Most editors do this for a selection with Ctrl+/.
Python
# Step 1: read the users file# Step 2: keep only active users# Step 3: print their namesusers=[("asha",True),("ravi",False),("meena",True)]print([nameforname,activeinusersifactive])
Output
['asha', 'meena']
Docstrings
A string written as the first line of a function, class or module is a docstring. Unlike a comment, Python keeps it, and help() shows it.
Python
defarea(width,height):"""Return the area of a rectangle."""returnwidth*heightprint(area(3,4))print(area.__doc__)
Output
12
Return the area of a rectangle.
Note
A triple-quoted string on its own in the middle of code is not a comment. Python creates the string and throws it away. It works, but # is the correct tool for comments.
Check your understanding
Predict the output
print("a","b",sep="*",end="!")print("c")
Output
a*b!c
sep="*" joins a and b, and end="!" replaces the newline, so the next print continues on the same line.
Quick quiz
1. What is the default value of sep in print()?
Values are separated by one space unless you pass sep.
2. Which line prints Total: 5 when n = 5?
Only an f-string fills in {n}. Adding a string and an int raises TypeError.
3. How do you write a comment in Python?
# starts a comment that runs to the end of the line.
Exercise: print a receipt line
Print one receipt line from these variables, with the price to 2 decimal places and | between the fields.
Input
item = "Mouse", qty = 3, price = 349.5
Expected output
Mouse | 3 | 1048.50
Hint 1
Use an f-string and the format :.2f for the total.
Pass end="" (or any other text) to print(), for example print("Loading", end="").
How do I print a variable with text?
Use an f-string, for example print(f"Total: {total}"), or pass several values: print("Total:", total).
How do I write a multi-line comment in Python?
Start each line with #. Triple-quoted strings are for docstrings, not comments.
What is the difference between a comment and a docstring?
Python ignores comments completely. A docstring is a real string stored on the function, class or module, and tools such as help() and IDEs display it.
BeginnerLesson 5 of 479 min read9 runnable examples
Syntax is the set of rules for how Python code must be written. Python’s rules are few, but one of them, indentation, is stricter than in most languages. Learn these rules once and most beginner errors disappear.
In this lesson
How statements and lines work
Why indentation defines blocks
How to split long lines
Python keywords and case sensitivity
Statements and lines
A Python program is a list of statements, normally one per line. Python runs them from top to bottom. No semicolon is needed at the end of a line.
Python
city="Pune"temperature=31print(city,temperature)
Output
Pune 31
Indentation defines blocks
Many languages use curly braces { } to group lines. Python uses indentation: the spaces at the start of a line. A line ending in a colon : starts a block, and every line in that block must be indented by the same amount.
Python
score=82ifscore>=50:print("Passed")# inside the if blockprint("Well done")# also insideprint("Report finished")# outside: runs every time
Output
Passed
Well done
Report finished
Tip
Use 4 spaces per level. Every IDE inserts 4 spaces when you press Tab in a .py file. Never mix tabs and spaces in one file.
Wrong indentation is a syntax error, and Python refuses to run the file:
Python
ifTrue:print("not indented")
Output
File "main.py", line 2
print("not indented")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 1
Indenting a line that should not be indented is also an error:
Python
print("one")print("two")
Output
File "main.py", line 2
print("two")
IndentationError: unexpected indent
Blocks inside blocks
Each new block adds one more level of indentation. Python knows a block has ended when the indentation goes back.
Python ends a statement at the end of the line, except inside brackets (), [] or {}. So the easiest way to split a long line is to wrap it in parentheses.
Asha Ravi
Traceback (most recent call last):
File "main.py", line 4, in <module>
Print("hello")
^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?
Keywords
Keywords are reserved words with a special meaning, such as if, for and def. You cannot use them as variable names. The keyword module lists them:
A flaky test passes on one run and fails on the next, with no change in the code. Flaky tests destroy trust in a test suite: people stop believing red builds. The Playwright TypeScript runner has retries built in; in Python, the pytest-rerunfailures plugin provides them. In this lesson you will learn what makes Playwright tests flaky and how to fix the cause, then use retries correctly: –reruns, delays, the flaky marker, rerunning only specific errors, failing the build on flaky passes, artifacts per attempt, and finding flaky tests with pytest-repeat.
📖 What You’ll Learn: what a flaky test is and why it matters, common causes in browser tests and their fixes, installing pytest-rerunfailures, –reruns and the R progress letter, –reruns-delay, the flaky marker, –only-rerun and –rerun-except, why expect() timeouts are AssertionErrors, –fail-on-flaky, reruns in pytest.ini, screenshots and traces for each attempt, and repeating tests with pytest-repeat to expose flakiness.
🎲 What Is a Flaky Test?
A flaky test gives different results on different runs of the same code: green on your laptop, red in CI, green again when someone clicks “re-run”. It is one of the most expensive problems in test automation:
Real bugs hide among the “probably flaky again” failures.
Teams waste hours re-running pipelines and investigating ghosts.
People stop trusting the suite, and a suite nobody trusts is worth nothing.
A real example from this course: while Lesson 42 was being prepared, about one in six navigations to the public SauceDemo site stalled for more than 30 seconds, and the same unchanged tests failed with Page.goto: Timeout 30000ms exceeded in some runs and passed in others.
🔍 Common Causes and Their Real Fixes
Retries hide symptoms. Before you add them, look for the cause:
Cause
Symptom
Real fix
Checking too early
Passes locally, fails on slow CI
Use expect() assertions, never time.sleep() or one-shot reads like inner_text() (Module 5)
Shared state between tests
Fails only in a certain order or in parallel
Fresh context per test (the default), unique test data, no module-level globals
Animations and transitions
Clicks land on a moving element
Let actionability checks work; disable animations for screenshots
Dependence on live third-party services
Random timeouts
Mock the network (Module 8), or use a stable test environment
Dates, times and random data
Fails around midnight or on certain values
Fix the time zone with timezone_id, control test data
Fragile locators
Fails after small UI changes or with A/B tests
Role-based locators and test ids (Module 4)
Too-short timeouts
Fails under load
Timeouts based on real requirements, not guesses
💡 Tip: The Trace Viewer (Module 5) is the best tool for flaky failures: run CI with --tracing retain-on-failure and compare the trace of a failed attempt with a passing one.
🔁 Retries with pytest-rerunfailures
Install the plugin:
⌨️ Terminal
pip install pytest-rerunfailures
This lesson uses version 16.7. To make the demonstrations repeatable, the test below simulates a flaky server. It shows a search result after a delay: 6 seconds on the first attempt (longer than expect()‘s 5-second timeout) and 1 second on later attempts. pytest-rerunfailures numbers the attempts in request.node.execution_count (1, 2, 3, …).
📄 flaky/test_flaky.py
from playwright.sync_api import Page, expect
RESULT_PAGE = """
<p id="result">Searching...</p>
<script>
setTimeout(() => document.getElementById('result').textContent = '3 products found', {delay});
</script>
"""
def test_search_results(page: Page, request):
attempt = getattr(request.node, "execution_count", 1) # 1 = first try, 2 = first retry, ...
delay = 6_000 if attempt == 1 else 1_000 # simulated slow server on the first try
page.set_content(RESULT_PAGE.replace("{delay}", str(delay)))
expect(page.locator("#result")).to_have_text("3 products found")
getattr(..., 1) returns 1 when the plugin is not active, so the test also runs without it.
In a real suite the delay comes from the server, not from your test. The simulation only makes the behaviour predictable for this lesson.
Without retries, the first attempt fails:
⌨️ Terminal
pytest -q flaky
🖥️ Output
F [100%]
================================== FAILURES ===================================
________________________ test_search_results[chromium] ________________________
page = <Page url='about:blank'>
request = <FixtureRequest for <Function test_search_results[chromium]>>
def test_search_results(page: Page, request):
attempt = getattr(request.node, "execution_count", 1) # 1 = first try, 2 = first retry, ...
delay = 6_000 if attempt == 1 else 1_000 # simulated slow server on the first try
page.set_content(RESULT_PAGE.replace("{delay}", str(delay)))
> expect(page.locator("#result")).to_have_text("3 products found")
E AssertionError: Locator expected to have text '3 products found'
E Actual value: Searching...
E Call log:
E - Expect "to_have_text" locator("#result") with timeout 5000ms
E - waiting for locator("#result")
E 14 × locator resolved to <p id="result">Searching...</p>
E - unexpected value "Searching..."
E
E Aria snapshot:
E - paragraph: Searching...
flaky\test_flaky.py:16: AssertionError
=========================== short test summary info ===========================
FAILED flaky/test_flaky.py::test_search_results[chromium] - AssertionError: L...
1 failed, 1 warning in 5.56s
With retries, --reruns 2 allows up to two more attempts for a failed test:
⌨️ Terminal
pytest -q -rR flaky --reruns 2
🖥️ Output
R. [100%]
=========================== rerun test summary info ===========================
RERUN flaky/test_flaky.py::test_search_results[chromium]
PASSED flaky/test_flaky.py::test_search_results[chromium]
1 passed, 1 warning, 1 rerun in 6.95s
R in the progress line means “failed, then rerun”; the final . is the passing attempt.
The summary counts reruns separately: 1 passed, 1 rerun. The run’s exit code is 0.
-rR adds the “rerun test summary info” section that lists which tests needed a rerun. Keep an eye on this list: every entry is a flaky test to investigate.
Each attempt runs the test’s fixtures again: a new context and a new page.
⚙️ Retry Options
Option
Meaning
--reruns N
Rerun a failed test up to N times
--reruns-delay S
Wait S seconds before each rerun (for example, to let a service recover)
--only-rerun REGEX
Rerun only failures whose error matches the regex; repeatable
--rerun-except REGEX
Do not rerun failures that match the regex; repeatable
--fail-on-flaky
Fail the run with exit code 7 if any test passed only after a rerun
--max-suite-reruns N
Limit the total number of reruns in the whole run
--force-reruns N
Use N reruns for every test, ignoring markers
The same settings work in pytest.ini:
[pytest]
addopts = --reruns 2 --reruns-delay 1
pytest-rerunfailures 16.7 also has its own ini keys, such as reruns = 2, reruns_delay = 1, only_rerun and rerun_except.
Retry only infrastructure errors: –only-rerun
A retry makes sense for problems outside your application, such as a slow network. It makes no sense for a wrong text, which will be wrong again on the next attempt. Here is a real bug and a slow page in one file:
📄 filters/test_filters.py
from playwright.sync_api import Page, expect
SLOW_BUTTON = """
<script>
setTimeout(() => document.body.innerHTML = '<button>Checkout</button>', {delay});
</script>
"""
def test_wrong_heading(page: Page):
page.set_content("<h1>Cart</h1>")
expect(page.locator("h1")).to_have_text("Basket", timeout=1_000) # a real bug: wrong text
def test_slow_button(page: Page, request):
attempt = getattr(request.node, "execution_count", 1)
page.set_content(SLOW_BUTTON.replace("{delay}", "3000" if attempt == 1 else "200"))
page.get_by_role("button", name="Checkout").click(timeout=2_000) # an action timeout
FR. [100%]
================================== FAILURES ===================================
________________________ test_wrong_heading[chromium] _________________________
page = <Page url='about:blank'>
def test_wrong_heading(page: Page):
page.set_content("<h1>Cart</h1>")
> expect(page.locator("h1")).to_have_text("Basket", timeout=1_000) # a real bug: wrong text
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E AssertionError: Locator expected to have text 'Basket'
E Actual value: Cart
E Call log:
E - Expect "to_have_text" locator("h1") with timeout 1000ms
E - waiting for locator("h1")
E 11 × locator resolved to <h1>Cart</h1>
E - unexpected value "Cart"
E
E Aria snapshot:
E - heading "Cart" [level=1]
filters\test_filters.py:12: AssertionError
=========================== short test summary info ===========================
FAILED filters/test_filters.py::test_wrong_heading[chromium] - AssertionError...
1 failed, 1 passed, 1 warning, 1 rerun in 4.07s
test_slow_button failed with Playwright’s TimeoutError on the first attempt, matched TimeoutError, was rerun and passed.
test_wrong_heading failed without a rerun. A failed expect() raises an AssertionError, even when it waited for its timeout, so it does not match TimeoutError.
📝 Note: This difference is useful. Action and navigation timeouts (click, fill, goto) raise TimeoutError, often caused by the environment. Failed expect() checks raise AssertionError, more often a real difference in the application. --only-rerun TimeoutError therefore retries infrastructure problems while real assertion failures fail at once.
Failing the build on flaky passes: –fail-on-flaky
Some teams want retries to keep the pipeline moving, but still want to know about flakiness. --fail-on-flaky lets the tests pass on retry but ends the run with exit code 7:
⌨️ Terminal
pytest -q flaky --reruns 2 --fail-on-flaky
🖥️ Output
R. [100%]
1 passed, 1 warning, 1 rerun in 6.96s
The summary still says 1 passed, 1 rerun, but pytest exited with code 7 (in our run, the verification script recorded exit 7), so CI marks the job as failed and someone has to look at the flaky test.
🏷️ The flaky Marker: Retries for Specific Tests
Instead of retrying the whole suite, mark only the tests you know are affected:
attempt 1
R
attempt 2
R
attempt 3
.
1 passed, 1 warning, 2 rerun in 6.89s
reruns=3 allows three reruns for this test only, without any command-line option.
reruns_delay=1 waits one second between attempts.
only_rerun= (and rerun_except=) work in the marker too. Here the test’s failures are AssertionErrors from expect(), so they are listed explicitly.
The test failed twice (each R) and passed on attempt 3; the summary counts 2 rerun.
When both the marker and --reruns are given, the marker wins by default (--reruns-mode strict).
⚠️ Watch out: A flaky marker is a temporary measure. Add a comment with the reason and a ticket number, and remove the marker once the cause is fixed. A suite where many tests carry it has a flakiness problem that retries only hide.
📸 Artifacts for Each Attempt
When you combine retries with pytest-playwright’s artifacts, each failed attempt keeps its own evidence. Run the simulated flaky test with one rerun and screenshots on failure:
Each repetition gets its own test id (1-3, 2-3, 3-3) and a fresh context.
For a real stability check, use a higher count, such as --count 50, and add -x to stop at the first failure. Combine it with pytest-xdist (Module 12) to finish faster.
Do not combine --count with --reruns for this purpose: retries would hide exactly the failures you are looking for.
✅ A Sensible Retry Policy
Locally: no retries. You want to see every failure while you work.
In CI: a small number, such as --reruns 1 or --reruns 2, ideally with --only-rerun TimeoutError for infrastructure problems.
Always keep evidence: --tracing retain-on-failure and --screenshot only-on-failure.
Track every rerun. Use -rR or the report to list flaky tests, and fix them like bugs; consider --fail-on-flaky once the suite is mostly stable.
Never use retries to hide a real failure. A test that fails 1 time in 10 because of the application is a bug report, not noise.
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Write the command that reruns failed tests up to twice with a 2-second delay, but only for Playwright TimeoutError failures.
Reruns only hide the symptom: the test can still fail, wastes time, and may hide a real intermittent bug. Find the cause (timing, shared data, unstable dependency) with traces and fix it, then remove the marker.
Exercise 3: How do you find out whether a test is flaky before it bothers the team? Write the command.
🤔 Does Playwright Python have built-in retries like playwright.config.ts?
No. The TypeScript test runner has a retries setting. In Python, retries come from the pytest-rerunfailures plugin: --reruns N or the flaky marker.
🤔 Are fixtures run again on a rerun?
Yes. Each attempt is a complete run of the test, with its function-scoped fixtures (including page and context) set up and torn down again. Session-scoped fixtures, such as the browser, are reused.
🤔 Why is my expect() failure not retried with –only-rerun TimeoutError?
A failed expect() raises AssertionError, not TimeoutError. Only actions and navigations (click, fill, goto) raise Playwright’s TimeoutError. Use --only-rerun AssertionError if you really want to retry assertion failures.
🤔 How do I know which tests are flaky?
Look for R in the progress line and use -rR to list rerun tests in the summary. Run suspicious tests many times with pytest-repeat’s --count.
🤔 Can I use –reruns together with pytest-xdist?
Yes. Each worker reruns its own failed tests. Parallel runs are covered in Module 12.
🏁 Summary
Flaky tests pass and fail on the same code; fix their causes first: waits, shared state, live dependencies, data and locators.
pytest-rerunfailures adds retries: --reruns N, --reruns-delay, the flaky marker, and filters with --only-rerun and --rerun-except.
--fail-on-flaky exits with code 7 when a test only passed on retry; -rR lists rerun tests.
Failed attempts keep their screenshots and traces; pytest-repeat’s --count exposes flakiness before CI does.
You have finished Module 6. Test yourself with the Module 6 mock interview, then continue to Module 7: test data, configuration and cross-browser testing at scale.
🎬 Watch the Playwright tutorial series on YouTube!
One of Playwright’s biggest strengths is real cross-browser testing: the same test runs on Chromium, Firefox and WebKit. Sometimes, though, a test should not run everywhere: a feature is missing in one engine, or the test uses a Chromium-only API. pytest-playwright gives you markers for exactly that. In this lesson you will run a suite on all three engines, find a real browser difference on the practice page, and control where each test runs with skip_browser, only_browser, browser_context_args, browser channels and per-test launch options.
📖 What You’ll Learn: running tests on several browsers with –browser, reading the parametrized test ids, a real WebKit difference on the practice page, skip_browser and only_browser, showing skip reasons with -rs, markers on classes and modules, branching on browser_name, the browser_context_args marker for per-test context options, browser channels for Google Chrome and Microsoft Edge, and per-test launch options with indirect parametrization of browser_type_launch_args.
🌍 Running on Several Browsers
By default pytest-playwright runs every test on Chromium. Pass --browser once per engine to run on more:
Each --browser creates one copy of every browser test, with the engine in the test id: test_title[chromium], test_title[firefox], test_title[webkit]. Each engine gets its own browser process; every test still gets a fresh context.
Engine
Used by
Notes
Chromium
Google Chrome, Microsoft Edge, Opera
Playwright’s default
Firefox
Mozilla Firefox
Playwright’s patched build
WebKit
Apple Safari
Playwright’s WebKit build runs on Windows, Linux and macOS
📝 Note: Playwright’s WebKit is close to Safari but not identical: the real Safari also depends on the Apple operating system it runs on. It is still the best way to catch WebKit-specific problems without a Mac.
🔎 A Real Difference Between Engines
All tests in this lesson use the SQA Tools practice page:
The page has a date picker, <input type="date" id="datePicker">. This test asks each browser what kind of input it actually created:
📄 tests/test_cross_browser.py
import pytest
from playwright.sync_api import Page, expect
def test_title(practice: Page, browser_name):
print(f"\n{browser_name} {practice.context.browser.version}")
expect(practice).to_have_title("Automation Practice Page - SQA Tools")
def test_what_is_the_date_input(practice: Page, browser_name):
input_type = practice.locator("#datePicker").evaluate("el => el.type")
print(f"\n{browser_name}: #datePicker has type '{input_type}'")
practice.context.browser.version is the version of the browser that runs the test.
el.type returns the type the browser supports: a browser without a date control falls back to a plain text box and reports "text".
When this lesson was run on Windows, Chromium and Firefox reported date, but **WebKit reported text**: Playwright’s WebKit build on Windows has no native date picker (you will see this in the output below). A test that fills the date picker in the YYYY-MM-DD format and expects a date control would fail there for a reason that has nothing to do with your application.
⏭️ skip_browser and only_browser
pytest-playwright registers two markers for such cases:
📄 tests/test_cross_browser.py
@pytest.mark.skip_browser("webkit")
def test_date_picker(practice: Page):
practice.locator("#datePicker").fill("2026-11-01")
expect(practice.locator("#datePicker")).to_have_value("2026-11-01")
@pytest.mark.only_browser("chromium")
def test_chromium_devtools_protocol(practice: Page):
# CDP sessions exist only in Chromium-based browsers
cdp = practice.context.new_cdp_session(practice)
version = cdp.send("Browser.getVersion")
print("\nCDP product:", version["product"].split("/")[0])
@pytest.mark.skip_browser("webkit"): run on every browser except WebKit.
@pytest.mark.only_browser("chromium"): run only on Chromium; all other browsers are skipped.
new_cdp_session() talks to the Chrome DevTools Protocol, which only Chromium-based browsers support. That makes it a genuine reason for only_browser.
Skipped copies appear as s in the progress line. Add -rs to the pytest command to list each skip with its reason.
⚠️ Watch out: Use these markers for real engine limitations, not to hide bugs. If your application is broken in Safari, a skipped test means your users find the bug instead of you. Mark such tests with xfail and a ticket number, or fix the application.
Markers on a whole class or module
Markers can be applied to a class, and to a whole file with pytestmark:
📄 tests/test_firefox_suite.py
import pytest
from playwright.sync_api import Page, expect
@pytest.mark.only_browser("firefox")
class TestFirefoxSpecific:
def test_user_agent(self, practice: Page):
expect(practice.locator("body")).to_be_visible()
assert "Firefox" in practice.evaluate("navigator.userAgent")
def test_engine_name(self, practice: Page, browser_name):
assert browser_name == "firefox"
For a whole module, write pytestmark = pytest.mark.skip_browser("webkit") at the top of the file.
Branching inside a test with browser_name
When only one step differs, skip that part or adapt the expected value instead of skipping the whole test:
A dictionary keyed by browser_name keeps browser-specific expectations in one readable place.
You can also call pytest.skip("reason") inside the test after checking browser_name or is_webkit. Prefer the markers when the whole test does not apply: the decision is then visible without reading the test body.
🎛️ The browser_context_args Marker
You met this marker in Lesson 6. It adds or overrides context options for one test (or one class), on top of the browser_context_args fixture:
📄 tests/test_context_marker.py
import pytest
from playwright.sync_api import Page
@pytest.mark.browser_context_args(locale="de-DE", timezone_id="Europe/Berlin")
def test_german_user(page: Page):
page.goto("https://sqatools.in/automation-practice-page/")
language = page.evaluate("navigator.language")
zone = page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone")
print(f"\nlanguage={language} timezone={zone}")
assert (language, zone) == ("de-DE", "Europe/Berlin")
The marker’s keyword arguments are passed to browser.new_context() for this test’s context.
Typical uses: a different locale or time zone, color_scheme="dark", permissions=["geolocation"], a mobile viewport, or storage_state for a test that should start logged in.
Now run the whole tests folder on all three engines, with -rs to show skip reasons:
language=de-DE timezone=Europe/Berlin
.
chromium 156.0.8078.4
.
chromium: #datePicker has type 'date'
..
CDP product: HeadlessChrome
..ss
language=de-DE timezone=Europe/Berlin
.
firefox 157.0
.
firefox: #datePicker has type 'date'
..s...
language=de-DE timezone=Europe/Berlin
.
webkit 27.2
.
webkit: #datePicker has type 'text'
.ss.ss
=========================== short test summary info ===========================
SKIPPED [2] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: chromium
SKIPPED [1] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
SKIPPED [4] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: webkit
17 passed, 7 skipped, 1 warning in 38.09s
Read the result:
The #datePicker lines show the real engine difference: date in Chromium and Firefox, text in WebKit.
test_date_picker[webkit] was skipped by skip_browser; the CDP test and the Firefox class were skipped on the other engines by only_browser. The reason for each skip is listed in the short test summary, because of -rs.
pytest groups the run by browser: all Chromium tests first, then Firefox, then WebKit, because each engine’s browser is a separate session fixture.
The skips add up: Chromium skipped the two Firefox-only tests, Firefox skipped the CDP test, and WebKit skipped the date picker, the CDP test and the two Firefox-only tests.
The reason text is fixed by the plugin (“skipped for this browser: …”) and points at the plugin’s code line, not at your test.
🏷️ Browser Channels: Google Chrome and Microsoft Edge
Playwright’s Chromium is an open-source build. To test with the branded browsers installed on the machine, pass a channel:
chromium 156.0.4314.42
.
1 passed, 1 warning in 2.70s
--browser-channel msedge launched the Microsoft Edge installed on this Windows machine, so the version is Edge’s own version number. chrome selects Google Chrome; beta and dev channels exist too (chrome-beta, msedge-beta, …).
The test id still says [chromium], because a channel is a Chromium-based browser.
A channel uses the browser installed on the machine. Install it there first (for Chrome you can also run playwright install chrome).
🚀 Per-Test Launch Options
Context options change the page environment (locale, viewport, permissions). Launch options change the browser process itself: command-line arguments, slow_mo, headless, channel. The suite-wide way to set them is overriding the browser_type_launch_args fixture (Lesson 6). For a single test, parametrize that fixture indirectly:
indirect=True sends the value to the browser_type_launch_argsfixture instead of passing it straight to the test. In pytest-playwright 0.10, the fixture merges it over the command-line launch options.
--lang=de-DE is a Chromium command-line switch, so the test is limited to Chromium with only_browser.
Because browser_type_launch_args and browser are session-scoped, each distinct value launches its own browser. That is slower, so keep per-test launch options for the few tests that really need them.
launch args: {'args': ['--lang=de-DE']}
navigator.language: de
.s
=========================== short test summary info ===========================
SKIPPED [1] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
1 passed, 1 skipped, 1 warning in 0.57s
The browser started with --lang=de-DE, so navigator.language is de, without any context option.
On Firefox the test was skipped by the only_browser marker.
The test id is test_browser_started_in_german[chromium-browser_type_launch_args0]: the parameter gets an automatic id. Pass ids=["german"] to parametrize for a readable one.
browser_name, is_webkit and friends inside the test
Locale, time zone, viewport, permissions for one test
@pytest.mark.browser_context_args(...)
The same for every test
Override the browser_context_args fixture
Branded Chrome or Edge
--browser-channel chrome or msedge
Browser command-line switches for one test
Indirect parametrization of browser_type_launch_args
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Mark a test so it never runs in WebKit, and another so it runs only in Chromium. Then show the command that runs all browsers and prints the skip reasons.
🤔 How do I run Playwright Python tests on all browsers?
Pass --browser once per engine: pytest --browser chromium --browser firefox --browser webkit. Put it in addopts in pytest.ini to make it the default.
🤔 What is the difference between skip_browser and only_browser?
skip_browser("webkit") excludes one engine and runs on the rest. only_browser("chromium") runs on one engine and skips all others.
🤔 Why is my only_browser test always skipped?
It only runs when that browser is part of the run. With only_browser("firefox") and no --browser firefox, every copy of the test is skipped.
🤔 Is WebKit on Windows the same as Safari?
No. It is Playwright’s build of the WebKit engine, so it behaves like Safari in most respects but not all, as the date input in this lesson shows. Run important Safari checks on macOS as well.
🤔 Can I set a different viewport for one test?
Yes: @pytest.mark.browser_context_args(viewport={"width": 390, "height": 844}), or create a context with new_context(viewport=...) inside the test.
🏁 Summary
--browser runs every browser test once per engine; the engine appears in the test id.
Engines differ: on Windows, WebKit has no native date input on the practice page.
skip_browser and only_browser decide where a test runs; -rs shows why tests were skipped.
Apply markers to classes or whole modules (pytestmark), and branch on browser_name for small differences.
The browser_context_args marker changes context options for one test; --browser-channel runs branded Chrome or Edge.
Indirect parametrization of browser_type_launch_args sets launch options for one test, at the cost of a separate browser launch.
Next, you will deal with tests that fail only sometimes: why tests become flaky, and how to retry them with pytest-rerunfailures without hiding real problems.
🎬 Watch the Playwright tutorial series on YouTube!
The built-in page fixture gives every test an empty browser tab. Real tests need more: an opened login page, a user who is already logged in, products in the cart, a check that no JavaScript errors happened. Custom fixtures turn that preparation into one reusable word in the test’s parameter list. In this lesson you will build a small fixture library for the SauceDemo shop on top of pytest-playwright’s fixtures, including a session-scoped login that is reused by every test.
📖 What You’ll Learn: why custom fixtures keep Playwright tests short, a page object fixture, chaining fixtures into a logged-in page, logging in once per session with storage_state and new_context, factory fixtures that take arguments, yield teardown, a fixture that collects console and page errors, parametrized fixtures for desktop and mobile, the ScopeMismatch error and the scope rules for fixtures that use page.
🧩 Why Custom Fixtures?
Compare two versions of the same test. Without fixtures, every test repeats the setup:
def test_cart_badge(page):
page.goto("https://www.saucedemo.com/")
page.get_by_placeholder("Username").fill("standard_user")
page.get_by_placeholder("Password").fill("secret_sauce")
page.get_by_role("button", name="Login").click()
# ... and only now the actual test starts
With fixtures, the test says only what it is about:
You already know how fixtures work (Module 3). This lesson is about Playwright-specific fixtures: building on page, new_context and browser, choosing the right scope, and keeping tests isolated.
All examples use SauceDemo (www.saucedemo.com), a public practice shop. Its login page lists the demo user names and the shared password secret_sauce.
📝 Note: SauceDemo is a shared public site. While this lesson was being prepared, roughly one navigation in six stalled for more than 30 seconds, and the tests then failed with Page.goto: Timeout 30000ms exceeded. If that happens to you, simply run the tests again. Lesson 44 shows how to handle such flaky failures with automatic retries.
🏗️ The Fixture Library: conftest.py
Here is the start of conftest.py. The rest of the file follows in the next sections.
📄 conftest.py
import pytest
from playwright.sync_api import Browser, Page, expect
SAUCE = "https://www.saucedemo.com/"
USER = {"username": "standard_user", "password": "secret_sauce"} # public demo account
class LoginPage:
"""A tiny page object for the SauceDemo login page."""
def __init__(self, page: Page):
self.page = page
self.username = page.get_by_placeholder("Username")
self.password = page.get_by_placeholder("Password")
self.button = page.get_by_role("button", name="Login")
self.error = page.locator("[data-test='error']")
def open(self) -> "LoginPage":
self.page.goto(SAUCE, wait_until="domcontentloaded")
return self
def login(self, username: str, password: str) -> None:
self.username.fill(username)
self.password.fill(password)
self.button.click()
# 1. A page object fixture: the login page, already opened
@pytest.fixture
def login_page(page: Page) -> LoginPage:
return LoginPage(page).open()
# 2. Chained fixture: a page where the user is logged in
@pytest.fixture
def logged_in_page(login_page: LoginPage) -> Page:
login_page.login(**USER)
expect(login_page.page).to_have_url(f"{SAUCE}inventory.html")
return login_page.page
1. A page object fixture
LoginPage groups the login page’s locators and actions in one class. This is the Page Object Model, covered in depth in Module 10.
The login_page fixture builds on pytest-playwright’s page, opens the page and returns the object. A test that asks for login_page starts on the login screen.
wait_until="domcontentloaded": as you saw in Module 5, a public site’s load event can be slow because of third-party resources. The locators wait for the form anyway.
2. Chaining fixtures into a logged-in page
logged_in_page asks for login_page, which asks for page. pytest resolves the chain: page → login_page → logged_in_page.
The fixture ends with an expect(): if the login fails, the fixture fails with a clear message, and pytest reports the test as an error in setup rather than a failure in the test body. That tells you immediately that the problem is in the preparation.
📄 tests/test_login.py
from playwright.sync_api import Page, expect
def test_locked_out_user_sees_error(login_page):
login_page.login("locked_out_user", "secret_sauce")
expect(login_page.error).to_have_text("Epic sadface: Sorry, this user has been locked out.")
def test_products_are_listed(logged_in_page: Page):
expect(logged_in_page.locator(".title")).to_have_text("Products")
expect(logged_in_page.locator(".inventory_item")).to_have_count(6)
🔐 Logging In Once: a Session Fixture with storage_state
Logging in through the form in every test costs time. A faster pattern: log in once per session, save the browser’s cookies and storage to a file, and start every test’s context from that file.
📄 conftest.py
# 3. Log in once for the whole session and save the browser state
@pytest.fixture(scope="session")
def auth_state(browser: Browser, tmp_path_factory) -> str:
context = browser.new_context()
page = context.new_page()
LoginPage(page).open().login(**USER)
page.wait_for_url("**/inventory.html")
path = tmp_path_factory.mktemp("auth") / "state.json"
context.storage_state(path=path) # cookies + localStorage as JSON
context.close()
print(f"\n[auth_state] logged in once, saved {path.name}")
return str(path)
# 4. Each test gets a NEW context that starts from the saved state
@pytest.fixture
def fast_logged_in_page(new_context, auth_state: str) -> Page:
page = new_context(storage_state=auth_state).new_page()
page.goto(f"{SAUCE}inventory.html", wait_until="domcontentloaded")
return page
auth_state is session-scoped, so it may only use session-scoped fixtures. It uses browser (session) and pytest’s built-in tmp_path_factory (session), notpage (function).
context.storage_state(path=...) writes the context’s cookies and localStorage to a JSON file. SauceDemo keeps the login in a cookie named session-username.
fast_logged_in_page calls new_context(storage_state=...): a fresh, isolated context per test, which already contains the login cookie. The test lands directly on the products page.
Run them with --setup-show to see that the login happens only once (an excerpt; ... marks lines removed for brevity):
⌨️ Terminal
pytest -q --setup-show tests/test_fast_login.py
🖥️ Output
...
SETUP S browser (fixtures used: launch_browser)
...
SETUP S tmp_path_factory
SETUP S auth_state (fixtures used: browser, tmp_path_factory)
...
SETUP F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
SETUP F fast_logged_in_page (fixtures used: auth_state, new_context)
tests/test_fast_login.py::test_first_fast_login[chromium] (fixtures used: ...) .
TEARDOWN F fast_logged_in_page
TEARDOWN F new_context
...
SETUP F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
SETUP F fast_logged_in_page (fixtures used: auth_state, new_context)
tests/test_fast_login.py::test_second_fast_login[chromium] (fixtures used: ...) .
TEARDOWN F fast_logged_in_page
TEARDOWN F new_context
...
TEARDOWN S auth_state
TEARDOWN S tmp_path_factory
...
2 passed, 1 warning in 8.65s
SETUP S auth_state appears once, before the first test; both tests then create their own F fast_logged_in_page. Module 8 builds on this pattern for real authentication setups.
⚠️ Watch out: Never commit real credentials in conftest.py. The SauceDemo values are public demo data. For your own applications, read user names and passwords from environment variables or a secrets store (Module 7).
🏭 Factory Fixtures: Fixtures That Take Arguments
A fixture cannot receive arguments from the test directly. The solution is a factory: the fixture returns a function, and the test calls it with the arguments it needs.
📄 conftest.py
# 5. A factory fixture: the test decides which products to add
@pytest.fixture
def add_to_cart(logged_in_page: Page):
added = []
def _add(product: str) -> Page:
item = logged_in_page.locator(".inventory_item").filter(has_text=product)
item.get_by_role("button", name="Add to cart").click()
added.append(product)
return logged_in_page
yield _add
# Teardown: runs after the test, even if it failed
print(f"\n[add_to_cart] teardown, products added in this test: {added}")
yield _add hands the inner function to the test. Everything after yield is teardown.
The added list remembers what the test did, so teardown knows what to clean up.
Here teardown only prints, because the browser context, and with it SauceDemo’s cart, is thrown away after each test anyway. In a real application the cart or order may live in a database: that is where teardown matters, for example to delete the order through an API call.
🚨 A Fixture That Watches the Page: Console and Page Errors
Fixtures can also attach listeners to the page. This one collects JavaScript errors so a test can assert that none happened:
📄 conftest.py
# 6. Collect console errors and uncaught exceptions of the page
@pytest.fixture
def js_errors(page: Page) -> list[str]:
errors: list[str] = []
page.on("console", lambda msg: errors.append(f"console: {msg.text}") if msg.type == "error" else None)
page.on("pageerror", lambda exc: errors.append(f"pageerror: {exc}"))
return errors
📄 tests/test_js_errors.py
from playwright.sync_api import Page, expect
def test_page_with_a_broken_script(page: Page, js_errors):
page.set_content("""
<button onclick="undefinedFunction()">Buy</button>
<script>console.error('Payment widget failed to load')</script>
""")
page.get_by_role("button", name="Buy").click()
expect(page.get_by_role("button")).to_be_visible() # gives the events time to arrive
print("\ncollected:", js_errors)
assert len(js_errors) == 2
page.on("console", ...) receives every console message; the fixture keeps those of type "error".
page.on("pageerror", ...) receives uncaught JavaScript exceptions, such as calling a function that does not exist.
Both js_errors and the test receive the samepage object: within one test, a function-scoped fixture is created only once and shared.
🔀 Parametrized Fixtures: Desktop and Mobile
A fixture with params runs every test that uses it once per parameter:
request.param holds the current parameter; ids gives readable names in the test id.
new_context(viewport=...) creates a context with that window size, without changing the project’s defaults.
⌨️ Terminal
pytest -q -s tests
🖥️ Output
.
[add_to_cart] teardown, products added in this test: ['Sauce Labs Backpack']
.
[add_to_cart] teardown, products added in this test: ['Sauce Labs Backpack', 'Sauce Labs Bike Light']
[auth_state] logged in once, saved state.json
..
collected: ['console: Payment widget failed to load', 'pageerror: undefinedFunction is not defined']
...
1280 px wide
.
390 px wide
.
9 passed, 1 warning in 36.71s
The [add_to_cart] lines come from the fixture’s teardown, after each cart test.
The [auth_state] line is printed once, when the first test that needs it runs; the second fast-login test reuses the saved file.
List the generated test ids with --collect-only:
⌨️ Terminal
pytest -q --collect-only tests/test_sizes.py
🖥️ Output
tests/test_sizes.py::test_login_form_fits[desktop-chromium]
tests/test_sizes.py::test_login_form_fits[mobile-chromium]
2 tests collected in 0.00s
Your fixture’s ids come first and pytest-playwright’s browser name second.
⛔ The Scope Rule: ScopeMismatch
A fixture can only use fixtures with the same or a wider scope. page is function-scoped, so a session-scoped fixture cannot use it:
📄 demos/test_scope_error.py
import pytest
from playwright.sync_api import Page
@pytest.fixture(scope="session")
def shared_home(page: Page) -> Page: # session fixture asking for a function fixture
page.goto("https://www.saucedemo.com/", wait_until="domcontentloaded")
return page
def test_uses_shared_home(shared_home: Page):
assert shared_home.url.startswith("https://www.saucedemo.com")
⌨️ Terminal
pytest -q demos/test_scope_error.py
🖥️ Output
E [100%]
=================================== ERRORS ====================================
______________ ERROR at setup of test_uses_shared_home[chromium] ______________
ScopeMismatch: You tried to access the function scoped fixture page with a session scoped request object. Requesting fixture stack:
demos\test_scope_error.py:5: def shared_home(page: 'Page') -> 'Page'
Requested fixture:
..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:623: def page(context: 'BrowserContext') -> 'Page'
=========================== short test summary info ===========================
ERROR demos/test_scope_error.py::test_uses_shared_home[chromium] - Failed: Sc...
1 error in 0.03s
pytest refuses to start the test and reports a ScopeMismatch error in setup.
The fix depends on your goal. To share something expensive across tests, build it from session fixtures (browser, playwright, tmp_path_factory), as auth_state does. To share a page, do not: share its saved state instead.
page is function-scoped and a session fixture cannot depend on it. Either make logged_in_page function-scoped, or log in once with a session fixture that uses browser (session-scoped), saves storage_state, and let each test create its own context from it.
🧠 MCQ Quiz: Custom Fixtures for Playwright Tests
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
Why write custom fixtures for Playwright tests?
Answer: To move repeated setup (login, data, page objects) out of tests. Tests stay short and focused on behaviour.
Which fixture can a session-scoped login fixture safely use?
Answer:browser. Only same or wider scopes are allowed.
What does a page-object fixture return?
Answer: An instance such as LoginPage(page) ready to use. Tests receive the object directly.
What is the benefit of chaining fixtures (e.g. logged_in_page uses login_page)?
Answer: Each fixture does one job and they compose into richer states. Composition keeps fixtures small and reusable.
Where does clean-up go in a custom fixture?
Answer: After yield. Teardown code runs after the test.
What error appears when a session fixture requests a function fixture?
Answer: ScopeMismatch. Scope rules prevent longer-lived fixtures from depending on shorter-lived ones.
How do you run tests once on desktop and once on mobile with one fixture?
Answer: A parametrized fixture with params=["desktop", "mobile"]. Every test using the fixture runs for each parameter.
What is the advantage of logging in once with storage_state?
Answer: One UI login per run, while each test still gets a fresh context. Speed without losing isolation.
How should a fixture signal that setup failed (e.g. login did not work)?
Answer: Assert or expect inside the fixture so the test errors in setup. Setup errors are reported as errors, not misleading test failures.
What does a factory fixture allow that a plain fixture does not?
Answer: Calling it with arguments, several times per test. It returns a function instead of a fixed value.
Yes, as long as your fixture is function-scoped (the default). The fixture and the test then share the same page object.
🤔 How do I reuse a login across tests without logging in every time?
Log in once in a session-scoped fixture that uses browser, save context.storage_state(path=...), and create each test’s context with new_context(storage_state=path).
🤔 Why is my test reported as an error instead of a failure?
The exception happened in a fixture (setup or teardown), not in the test body. Check the fixture named in the traceback.
🤔 Can I pass arguments to a fixture?
Not directly. Return a function from the fixture (a factory) and call it in the test with the arguments, or use params or indirect parametrization for fixed values.
🏁 Summary
Custom fixtures package preparation, such as an opened page object, a logged-in user or products in the cart, into one parameter.
Every Playwright test you have written so far started with a page parameter. Behind that one word, the pytest-playwright plugin builds a chain of fixtures: it starts Playwright, launches a browser, creates a fresh browser context and opens a page, then cleans everything up. In this lesson you will see the whole chain with pytest’s –setup-show, prove that each test is isolated, and use the other built-in fixtures: new_context, browser, browser_name, is_chromium, device, output_path, base_url and the playwright object itself.
📖 What You’ll Learn: the fixture chain from playwright to page, which fixtures are session-scoped and which run per test, watching setup and teardown with –setup-show, how a fresh context isolates cookies and storage, new_context for several users or settings in one test, using browser for contexts you manage yourself, browser_name and the is_chromium, is_firefox and is_webkit flags, browser_channel and device, output_path, base_url, and the playwright fixture for devices and API requests.
🔗 The Fixture Chain Behind page
When a test asks for page, pytest-playwright resolves a chain of fixtures, each built on the one before:
Fixture
Scope
What it gives you
playwright
session
The started Playwright object (sync_playwright().start())
browser_type
session
playwright.chromium, .firefox or .webkit, chosen by --browser
browser
session
One launched browser, shared by all tests of that browser
new_context
function
A function that creates browser contexts and closes them after the test
context
function
A fresh BrowserContext for this test, made with new_context()
page
function
A new Page in that context
The two scopes are the key idea:
Session scope: started once for the whole run. Launching a browser takes time, so all tests share one browser process.
Function scope: created for each test. Every test gets a brand-new context, which is like a new incognito window: no cookies, no localStorage, no cache from other tests.
So tests are fast (one browser) and isolated (a fresh context each).
Watching the chain with –setup-show
pytest’s --setup-show option prints every fixture as it is set up (SETUP) and torn down (TEARDOWN), with its scope: S for session, F for function.
SETUP S pytestconfig
SETUP S delete_output_dir (fixtures used: pytestconfig)
SETUP S browser_type_launch_args (fixtures used: pytestconfig)
SETUP S _pw_api_request_contexts (fixtures used: pytestconfig)
SETUP S playwright (fixtures used: _pw_api_request_contexts)
SETUP S browser_name (fixtures used: pytestconfig)['chromium']
SETUP S browser_type (fixtures used: browser_name, playwright)
SETUP S connect_options
SETUP S launch_browser (fixtures used: browser_type, browser_type_launch_args, connect_options)
SETUP S browser (fixtures used: launch_browser)
SETUP S device (fixtures used: pytestconfig)
SETUP S base_url (fixtures used: pytestconfig)
SETUP S _pw_artifacts_folder (fixtures used: pytestconfig)
SETUP S browser_context_args (fixtures used: _pw_artifacts_folder, base_url, device, playwright, pytestconfig)
SETUP F _pw_trace_api_requests
SETUP F output_path (fixtures used: pytestconfig)
SETUP F _artifacts_recorder (fixtures used: _pw_api_request_contexts, _pw_artifacts_folder, output_path, playwright, pytestconfig)
SETUP F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
SETUP F context (fixtures used: new_context)
SETUP F page (fixtures used: context)
SETUP F practice (fixtures used: page)
tests/test_isolation.py::test_first_visit[chromium] (fixtures used: _artifacts_recorder, _pw_api_request_contexts, _pw_artifacts_folder, _pw_trace_api_requests, base_url, browser, browser_context_args, browser_name, browser_type, browser_type_launch_args, connect_options, context, delete_output_dir, device, launch_browser, new_context, output_path, page, playwright, practice, pytestconfig, request) .
TEARDOWN F practice
TEARDOWN F page
TEARDOWN F context
TEARDOWN F new_context
TEARDOWN F _artifacts_recorder
TEARDOWN F output_path
TEARDOWN F _pw_trace_api_requests
TEARDOWN S browser_context_args
TEARDOWN S _pw_artifacts_folder
TEARDOWN S base_url
TEARDOWN S device
TEARDOWN S browser
TEARDOWN S launch_browser
TEARDOWN S connect_options
TEARDOWN S browser_type
TEARDOWN S browser_name['chromium']
TEARDOWN S playwright
TEARDOWN S _pw_api_request_contexts
TEARDOWN S browser_type_launch_args
TEARDOWN S delete_output_dir
TEARDOWN S pytestconfig
1 passed, 1 warning in 1.90s
Reading the output from top to bottom:
The session fixtures (playwright, browser_type, browser, browser_context_args and others) are set up first. Fixtures whose names start with _pw are the plugin’s internal helpers; you never use them directly.
browser_name is shown with ['chromium']: pytest-playwright parametrizes every browser test by browser name, which is why test ids end in [chromium].
The function fixtures new_context, context and page are created just for this test, then your practice fixture runs on top of page.
After the test (the .), teardown runs in reverse order: first the function fixtures, and at the end of the session the browser and Playwright.
🧼 Proving Test Isolation
These two tests run one after the other in the same browser. The first one stores data in the browser; the second checks that none of it is left:
📄 tests/test_isolation.py
from playwright.sync_api import Browser, BrowserContext, Page
SEEN = {}
def test_first_visit(practice: Page, context: BrowserContext, browser: Browser):
practice.evaluate("localStorage.setItem('cart', '3 items')")
context.add_cookies([{"name": "session", "value": "abc123", "url": practice.url}])
SEEN["browser"], SEEN["context"] = browser, context
print("\nstored:", practice.evaluate("localStorage.getItem('cart')"), "| cookies:", len(context.cookies()))
def test_second_visit(practice: Page, context: BrowserContext, browser: Browser):
print("\nleft over:", practice.evaluate("localStorage.getItem('cart')"),
"| cookies named session:", [c for c in context.cookies() if c["name"] == "session"])
print("same browser:", browser is SEEN["browser"], "| same context:", context is SEEN["context"])
SEEN is a plain module-level dictionary used only to compare objects between the two tests.
context.add_cookies() adds a cookie; context.cookies() lists the cookies of the context. The count of 7 includes cookies that the live site set itself while loading.
localStorage is read and written with page.evaluate(), which runs JavaScript in the page.
Part of the output of pytest -q -s tests (the full run is at the end of this section):
🖥️ Output
stored: 3 items | cookies: 7
.
left over: None | cookies named session: []
same browser: True | same context: False
The second test sees no localStorage value and no session cookie, because it runs in a new context. The browser object, however, is the very same one.
💡 Tip: Isolation is why Playwright tests can run in any order and in parallel. If one of your tests only passes after another test has run, it secretly depends on that test’s state: fix it with a fixture that sets up what it needs.
👥 new_context: Several Users in One Test
Some scenarios need two independent sessions at once: a buyer and a seller, an admin and a user, a chat between two people. The new_context fixture is a function: each call creates another context, using the same settings as context (browser_context_args), plus any options you pass.
📄 tests/test_new_context.py
from playwright.sync_api import Page
def test_two_users(new_context):
alice = new_context().new_page()
bob = new_context(locale="de-DE", viewport={"width": 800, "height": 600}).new_page()
alice.goto("https://sqatools.in/automation-practice-page/")
bob.goto("https://sqatools.in/automation-practice-page/")
alice.evaluate("localStorage.setItem('user', 'alice')")
print("\nalice sees:", alice.evaluate("localStorage.getItem('user')"))
print("bob sees :", bob.evaluate("localStorage.getItem('user')"))
print("bob locale:", bob.evaluate("navigator.language"), "| bob viewport:", bob.viewport_size)
def test_page_and_extra_context(page: Page, new_context):
# page uses one context; new_context() makes a second, independent one
other = new_context().new_page()
print("\ncontexts in the browser:", len(page.context.browser.contexts))
assert page.context is not other.context
Each new_context() call returns a new, isolated BrowserContext.
Options passed to the call, such as locale or viewport, are added to the configured browser_context_args for that context only.
You do not close these contexts yourself: the fixture closes all of them after the test. They also get the plugin’s tracing, video and screenshot handling.
🌐 browser: Contexts You Manage Yourself
You can also call browser.new_context() directly. The difference: such a context does not use browser_context_args, does not get the plugin’s artifacts, and you must close it.
try / finally makes sure the context is closed even if the test fails.
Prefer new_context in tests. Use browser.new_context() when you deliberately want a context without the project’s default settings.
⌨️ Terminal
pytest -q -s tests
🖥️ Output
browser: chromium 156 | JS enabled: False
.
stored: 3 items | cookies: 7
.
left over: None | cookies named session: []
same browser: True | same context: False
.
alice sees: alice
bob sees : None
bob locale: de-DE | bob viewport: {'width': 800, 'height': 600}
.
contexts in the browser: 2
.
5 passed, 1 warning in 8.88s
🧭 Information Fixtures: browser_name, is_*, channel and device
These session fixtures tell a test where it runs:
Fixture
Value
browser_name
"chromium", "firefox" or "webkit"
is_chromium, is_firefox, is_webkit
True or False
browser_channel
The --browser-channel value, such as "chrome", or None
device
The --device value, such as "iPhone 15", or None
output_path
This test’s artifact folder inside --output (function scope)
📄 info/test_where_am_i.py
from playwright.sync_api import Page
def test_where_am_i(page: Page, browser_name, is_webkit, browser_channel, device, output_path):
print(f"\nbrowser_name={browser_name} is_webkit={is_webkit} channel={browser_channel} device={device}")
print("viewport:", page.viewport_size, "| iPhone user agent:", "iPhone" in page.evaluate("navigator.userAgent"))
print("output_path ends with:", output_path.replace("\\", "/").split("/")[-1])
⌨️ Terminal
pytest -q -s info --browser firefox --device "iPhone 15"
--device "iPhone 15" applies the device’s viewport (393 x 659), user agent and touch support to every context, through browser_context_args.
The iPhone descriptor names WebKit as its default browser, but --browser decides which browser actually runs. Here Firefox ran with the iPhone viewport and user agent. For the most realistic iPhone emulation, run such tests on WebKit.
output_path is a folder name built from the test id. Nothing is written there unless an artifact is kept.
Now run on two browsers:
⌨️ Terminal
pytest -q -s info --browser chromium --browser webkit
Each --browser adds one parametrized copy of every test, so the test ran twice with a different browser_name.
🏠 base_url: Short URLs in Tests
The base_url fixture holds the value of --base-url (or base_url in pytest.ini, or the PYTEST_BASE_URL environment variable). pytest-playwright passes it to every context, so page.goto() accepts paths:
📄 base/test_base_url.py
from playwright.sync_api import Page, expect
def test_relative_goto(page: Page, base_url):
print("\nbase_url:", base_url)
page.goto("/automation-practice-page/") # resolved against base_url
expect(page).to_have_url("https://sqatools.in/automation-practice-page/")
⌨️ Terminal
pytest -q -s base --base-url https://sqatools.in
🖥️ Output
base_url: https://sqatools.in
.
1 passed, 1 warning in 2.46s
📝 Note: The PytestRemovedIn10Warning you have seen in every run’s summary comes from this fixture: pytest-playwright 0.10 defines base_url as a method of a helper class, which pytest 9.2 reports as deprecated. It does not affect your tests. Silence it with a filterwarnings line in pytest.ini if it bothers you, as shown in Module 3.
🎭 The playwright Fixture
The session-scoped playwright fixture is the same object you get from sync_playwright().start(). Two things you will use it for:
📄 pw/test_playwright_fixture.py
def test_device_list(playwright):
iphone = playwright.devices["iPhone 15"] # a device descriptor (a dict)
print(iphone["viewport"], iphone["default_browser_type"])
def test_api(playwright):
api = playwright.request.new_context(base_url="https://sqatools.in")
response = api.get("/automation-practice-page/")
assert response.ok
api.dispose()
playwright.devices contains the device descriptors used by --device. You can pass one to new_context(**playwright.devices["Pixel 7"]).
playwright.request creates API clients without a browser. Module 9 covers API testing in detail.
📋 All Built-in Fixtures at a Glance
Fixture
Scope
Typical use
page
function
Almost every UI test
context
function
Cookies, permissions, routes, a second page in the same session
new_context
function
Several independent users or per-test context options
browser
session
Contexts without the default settings
browser_type, launch_browser
session
Launching another browser yourself
playwright
session
Devices, API request contexts
browser_context_args
session
Override to change context settings (Lesson 6)
browser_type_launch_args
session
Override to change launch options (headless, args, channel)
connect_options
session
Override to connect to a remote browser server
browser_name, browser_channel, device
session
Where the test runs
is_chromium, is_firefox, is_webkit
session
Browser-specific branches
output_path
function
This test’s artifact folder
base_url
session
The --base-url value
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Write a test that uses new_context to open the SQA Shop as two users at once: a guest and a logged-in shopper, and checks both headers.
No. The browser fixture is session-scoped, so one browser is launched per browser type for the whole run (per worker when you use pytest-xdist). Each test gets a fresh context instead, which is fast and fully isolated.
🤔 Can I make the page fixture shared between tests to save time?
You could write your own session-scoped page fixture, but tests would then share cookies and state and depend on each other’s order. Keep the per-test context; to save login time, reuse a saved login state instead (Module 8).
🤔 What is the difference between context and new_context?
context is one ready-made context for the test. new_context is a function that creates as many extra contexts as you need, with optional per-context settings. All of them are closed automatically after the test.
🤔 Why do all my test names end with [chromium]?
pytest-playwright parametrizes browser tests by browser_name. The suffix shows which browser ran that copy of the test, which matters when you pass several --browser options.
🏁 Summary
page sits on a chain: playwright → browser_type → browser (session) → new_context → context → page (per test).
One shared browser makes runs fast; a fresh context per test keeps them isolated.
--setup-show reveals which fixtures run and in which scope.
new_context creates extra isolated contexts with optional settings and closes them for you.
browser.new_context() skips the project settings and must be closed by you.
browser_name, is_*, browser_channel, device, output_path and base_url tell a test where and how it runs.
Next, you will write your own fixtures on top of these: page objects, logged-in pages, test data with cleanup and fixture factories.
🎬 Watch the Playwright tutorial series on YouTube!