Data-Driven Testing in Playwright Python with pytest parametrize
Most bugs hide in the inputs you did not try. Data-driven testing runs the same Playwright test with many sets of data, so one well-written test checks a valid login, a wrong password, a locked account and empty fields. In this lesson you will turn a single login test into a data-driven suite with @pytest.mark.parametrize, give every case a readable id, mark known failures with pytest.param, keep test data in dataclasses, combine parameters, and parametrize fixtures so the same test runs against different setups.
📖 What You’ll Learn: what data-driven testing is, a login test matrix with @pytest.mark.parametrize, readable ids, pytest.param with marks, stacking parametrize for combinations, dataclass test cases, parametrized fixtures with params=, generating cases with pytest_generate_tests, and when not to parametrize.
🧩 What Is Data-Driven Testing?
Data-driven testing separates the steps of a test from the data it uses. You write the steps once (open the login page, type a username and password, click Log in, check the result) and feed them a table of inputs and expected results.
| Username | Password | Expected result |
|---|---|---|
testuser |
Test@123 |
Logged in, header shows “Hi, Test” |
testuser |
wrong |
“Invalid username or password.” |
lockeduser |
Test@123 |
“This account is locked. Please contact support.” |
| (empty) | Test@123 |
“Username is required.” |
testuser |
(empty) | “Password is required.” |
Without data-driven tests you would copy the same test five times. With it, adding a sixth case is one more line of data.
In pytest the main tool is @pytest.mark.parametrize, which you met in Lesson 27. This lesson applies it to real browser tests and adds the techniques that matter in a Playwright framework.
📌 Note: All examples in this lesson run against SQA Shop, the dummy e-commerce website on SQA Tools. Its login page lists the test data: testuser / Test@123 (valid) and lockeduser / Test@123 (locked). Everything runs in your browser, so you can run these tests as often as you like.
🛠️ Project Setup
Create a folder with this pytest.ini. --base-url lets tests call page.goto("/dummy-ecommerce-website/") with a relative URL (the base_url option comes from the pytest-base-url plugin that pytest-playwright installs).
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
The store is a single-page app: its views live after the # in the URL. The login view is #/login. A small helper keeps the URL in one place:
📄 tests/shop.py
SHOP = "/dummy-ecommerce-website/"
def open_login(page):
page.goto(SHOP + "#/login")
🔁 From One Test to a Data-Driven Test
Here is a plain test for the error message when the password is wrong:
📄 tests/test_login_single.py
from playwright.sync_api import Page, expect
from tests.shop import open_login
def test_wrong_password(page: Page):
open_login(page)
page.get_by_test_id("login-username").fill("testuser")
page.get_by_test_id("login-password").fill("wrong")
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("login-error")).to_have_text("Invalid username or password.")
To test the other error cases you only change three values: username, password and the expected message. Move them into @pytest.mark.parametrize:
📄 tests/test_login_errors.py
import pytest
from playwright.sync_api import Page, expect
from tests.shop import open_login
@pytest.mark.parametrize(
"username, password, message",
[
("testuser", "wrong", "Invalid username or password."),
("nobody", "Test@123", "Invalid username or password."),
("lockeduser", "Test@123", "This account is locked. Please contact support."),
("", "Test@123", "Username is required."),
("testuser", "", "Password is required."),
("", "", "Username and password are required."),
],
)
def test_login_error(page: Page, username, password, message):
open_login(page)
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill(password)
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("login-error")).to_have_text(message)
⌨️ Terminal
pytest tests/test_login_errors.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 6 items
tests/test_login_errors.py::test_login_error[chromium-testuser-wrong-Invalid username or password.] PASSED [ 16%]
tests/test_login_errors.py::test_login_error[chromium-nobody-Test@123-Invalid username or password.] PASSED [ 33%]
tests/test_login_errors.py::test_login_error[chromium-lockeduser-Test@123-This account is locked. Please contact support.] PASSED [ 50%]
tests/test_login_errors.py::test_login_error[chromium--Test@123-Username is required.] PASSED [ 66%]
tests/test_login_errors.py::test_login_error[chromium-testuser--Password is required.] PASSED [ 83%]
tests/test_login_errors.py::test_login_error[chromium---Username and password are required.] PASSED [100%]
============================= 6 passed in 10.40s ==============================
pytest created six tests from one function. Notice the chromium- at the start of every id: pytest-playwright parametrizes each test by browser too, so with --browser firefox --browser webkit you would get 18 tests. Each case gets a fresh page (and a fresh browser context), so a failed login in one case can never leak into the next.
💡 Tip: fill("") is valid: it clears the field. That is how the empty-field cases work without any special code.
🏷️ Readable Test IDs
The generated names such as test_login_error[testuser-wrong-Invalid username or password.] are long, and an empty string gives an ugly id like -Test@123-.... Give every case a short name with ids=:
📄 tests/test_login_ids.py
import pytest
from playwright.sync_api import Page, expect
from tests.shop import open_login
CASES = [
("testuser", "wrong", "Invalid username or password."),
("lockeduser", "Test@123", "This account is locked. Please contact support."),
("", "Test@123", "Username is required."),
]
@pytest.mark.parametrize("username, password, message", CASES, ids=["wrong-password", "locked-user", "empty-username"])
def test_login_error(page: Page, username, password, message):
open_login(page)
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill(password)
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("login-error")).to_have_text(message)
⌨️ Terminal
pytest tests/test_login_ids.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 3 items
tests/test_login_ids.py::test_login_error[chromium-wrong-password] PASSED [ 33%]
tests/test_login_ids.py::test_login_error[chromium-locked-user] PASSED [ 66%]
tests/test_login_ids.py::test_login_error[chromium-empty-username] PASSED [100%]
============================== 3 passed in 5.36s ==============================
Now you can run one case by its id with -k:
⌨️ Terminal
pytest tests/test_login_ids.py -k locked -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 3 items / 2 deselected / 1 selected
tests/test_login_ids.py::test_login_error[chromium-locked-user] PASSED [100%]
======================= 1 passed, 2 deselected in 2.38s =======================
ids= also accepts a function that receives each value and returns a string (or None to keep the default). That is handy when the data has a natural name field.
🎯 pytest.param: Per-Case IDs and Marks
A list of ids must stay in the same order as the data, which is easy to break. pytest.param keeps the id next to its data, and it can carry marks such as skip or xfail for a single case:
📄 tests/test_login_param.py
import pytest
from playwright.sync_api import Page, expect
from tests.shop import open_login
@pytest.mark.parametrize(
"username, password, message",
[
pytest.param("testuser", "wrong", "Invalid username or password.", id="wrong-password"),
pytest.param("TESTUSER", "Test@123", "Invalid username or password.", id="username-is-case-sensitive"),
pytest.param(" testuser ", "Test@123", None, id="spaces-are-trimmed"),
pytest.param(
"testuser", "test@123", None, id="password-case-insensitive",
marks=pytest.mark.xfail(reason="passwords are case-sensitive by design", strict=True),
),
],
)
def test_login(page: Page, username, password, message):
open_login(page)
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill(password)
page.get_by_test_id("login-button").click()
if message is None: # None means "login should succeed"
expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
else:
expect(page.get_by_test_id("login-error")).to_have_text(message)
⌨️ Terminal
pytest tests/test_login_param.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_login_param.py::test_login[chromium-wrong-password] PASSED [ 25%]
tests/test_login_param.py::test_login[chromium-username-is-case-sensitive] PASSED [ 50%]
tests/test_login_param.py::test_login[chromium-spaces-are-trimmed] PASSED [ 75%]
tests/test_login_param.py::test_login[chromium-password-case-insensitive] XFAIL [100%]
======================== 3 passed, 1 xfailed in 12.95s ========================
Read the result line by line:
spaces-are-trimmedpassed: the app trims the username, which is a behaviour worth pinning down with a test.password-case-insensitiveis XFAIL: we expected it to fail, and it did. Withstrict=True, if someone ever made passwords case-insensitive, the test would turn into a hard FAIL (XPASS strict), which is exactly the alarm you want.
⚠️ Watch out: Keep the if message is None style for small variations only. If the two branches grow into different flows, split them into two tests: one for successful logins and one for errors. A test full of if statements is hard to read when it fails.
✖️ Combinations: Stacking parametrize
Stack two parametrize decorators and pytest runs every combination (a cross product). Here 2 search terms × 2 sort orders = 4 tests, each checking that the prices on the first results page are sorted:
📄 tests/test_search_sort.py
import re
import pytest
from playwright.sync_api import Page, expect
from tests.shop import SHOP
def prices(page: Page) -> list[int]:
texts = page.get_by_test_id("product-price").all_inner_texts()
return [int(re.sub(r"[^\d]", "", t)) for t in texts]
@pytest.mark.parametrize("term", ["shirt", "watch"])
@pytest.mark.parametrize("sort, reverse", [("price-asc", False), ("price-desc", True)], ids=["low-to-high", "high-to-low"])
def test_search_results_are_sorted(page: Page, term, sort, reverse):
page.goto(SHOP + "#/search/" + term)
expect(page.get_by_test_id("product-card").first).to_be_visible()
page.get_by_test_id("sort-by").select_option(sort)
expect(page.get_by_test_id("product-card").first).to_be_visible()
found = prices(page)
assert len(found) > 1
assert found == sorted(found, reverse=reverse)
⌨️ Terminal
pytest tests/test_search_sort.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_search_sort.py::test_search_results_are_sorted[chromium-low-to-high-shirt] PASSED [ 25%]
tests/test_search_sort.py::test_search_results_are_sorted[chromium-low-to-high-watch] PASSED [ 50%]
tests/test_search_sort.py::test_search_results_are_sorted[chromium-high-to-low-shirt] PASSED [ 75%]
tests/test_search_sort.py::test_search_results_are_sorted[chromium-high-to-low-watch] PASSED [100%]
============================== 4 passed in 8.04s ==============================
⚠️ Watch out: Combinations grow fast: 5 browsers-worth of data × 4 × 6 is already 120 tests. Stack decorators only when every combination is a meaningful test. Otherwise list the combinations you care about in one parametrize.
📦 Test Cases as Dataclasses
Tuples are fine for three values. When a case has six or seven fields, positional tuples become hard to read and easy to get wrong. A dataclass gives every field a name, a type and an optional default:
📄 tests/test_login_cases.py
from dataclasses import dataclass
import pytest
from playwright.sync_api import Page, expect
from tests.shop import open_login
@dataclass(frozen=True)
class LoginCase:
name: str
username: str
password: str = "Test@123"
error: str | None = None # None = the login must succeed
remember: bool = False
CASES = [
LoginCase("valid-user", "testuser"),
LoginCase("valid-user-remember-me", "testuser", remember=True),
LoginCase("locked-user", "lockeduser", error="This account is locked. Please contact support."),
LoginCase("unknown-user", "ghost", error="Invalid username or password."),
]
@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name)
def test_login(page: Page, case: LoginCase):
open_login(page)
page.get_by_test_id("login-username").fill(case.username)
page.get_by_test_id("login-password").fill(case.password)
if case.remember:
page.get_by_test_id("remember-me").check()
page.get_by_test_id("login-button").click()
if case.error:
expect(page.get_by_test_id("login-error")).to_have_text(case.error)
else:
expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
stored = page.evaluate("localStorage.getItem('spUser')")
assert (stored == '"testuser"') is case.remember
⌨️ Terminal
pytest tests/test_login_cases.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_login_cases.py::test_login[chromium-valid-user] PASSED [ 25%]
tests/test_login_cases.py::test_login[chromium-valid-user-remember-me] PASSED [ 50%]
tests/test_login_cases.py::test_login[chromium-locked-user] PASSED [ 75%]
tests/test_login_cases.py::test_login[chromium-unknown-user] PASSED [100%]
============================== 4 passed in 7.35s ==============================
Three things make this version strong:
ids=lambda c: c.nametakes the id from the data itself, so ids and data can never drift apart.- Defaults (
password="Test@123") keep each case short: you only write what is special about it. - The “remember me” case checks a real side effect: the store saves
spUserinlocalStorageonly when the box is ticked. You will use exactly this in Lesson 51 to save and reuse a login.
🧪 Parametrized Fixtures
Sometimes the setup varies rather than the inputs. A fixture with params= runs every test that uses it once per parameter. Here each test runs once for a guest and once for a logged-in shopper:
📄 tests/test_fixture_params.py
import pytest
from playwright.sync_api import Page, expect
from tests.shop import SHOP, open_login
@pytest.fixture(params=["guest", "testuser"])
def shopper(request, page: Page) -> Page:
"""A page on the store home, as a guest or after logging in."""
if request.param != "guest":
open_login(page)
page.get_by_test_id("login-username").fill(request.param)
page.get_by_test_id("login-password").fill("Test@123")
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
page.goto(SHOP + "#/")
return page
def test_cart_starts_empty(shopper: Page):
expect(shopper.get_by_test_id("cart-count")).to_have_text("0")
def test_add_to_cart_updates_badge(shopper: Page):
shopper.get_by_test_id("search-input").fill("earbuds")
shopper.get_by_test_id("search-button").click()
shopper.get_by_role("button", name="Add to cart").first.click()
expect(shopper.get_by_test_id("cart-count")).to_have_text("1")
⌨️ Terminal
pytest tests/test_fixture_params.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_fixture_params.py::test_cart_starts_empty[guest-chromium] PASSED [ 25%]
tests/test_fixture_params.py::test_cart_starts_empty[testuser-chromium] PASSED [ 50%]
tests/test_fixture_params.py::test_add_to_cart_updates_badge[guest-chromium] PASSED [ 75%]
tests/test_fixture_params.py::test_add_to_cart_updates_badge[testuser-chromium] PASSED [100%]
============================== 4 passed in 8.60s ==============================
Two tests × two fixture params = four results. Use parametrized fixtures when many tests need to run under each setup (each user role, each locale, each environment); use @pytest.mark.parametrize when one test needs many inputs.
⚙️ Generating Cases with pytest_generate_tests
For full control, pytest calls the hook pytest_generate_tests for every test function. You can read a command-line option, a file or an environment variable and decide the parameters at collection time. This conftest.py adds a --users option:
📄 tests/conftest.py
def pytest_addoption(parser):
parser.addoption("--users", default="testuser", help="comma-separated usernames for test_user_can_log_in")
def pytest_generate_tests(metafunc):
if "username" in metafunc.fixturenames and metafunc.function.__name__ == "test_user_can_log_in":
users = metafunc.config.getoption("--users").split(",")
metafunc.parametrize("username", users, ids=users)
📄 tests/test_generated.py
from playwright.sync_api import Page, expect
from tests.shop import open_login
def test_user_can_log_in(page: Page, username):
open_login(page)
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill("Test@123")
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
⌨️ Terminal
pytest tests/test_generated.py --users testuser,lockeduser -q
🖥️ Output
.F [100%]
================================== FAILURES ===================================
__________________ test_user_can_log_in[lockeduser-chromium] __________________
page = <Page url='https://sqatools.in/dummy-ecommerce-website/#/login'>
username = 'lockeduser'
def test_user_can_log_in(page: Page, username):
open_login(page)
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill("Test@123")
page.get_by_test_id("login-button").click()
> expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
E AssertionError: Locator expected to contain text 'Hi,'
E Actual value: Login
E Call log:
E - Expect "to_contain_text" get_by_test_id("account-button") with timeout 5000ms
E - waiting for get_by_test_id("account-button")
E 14 × locator resolved to <button type="button" class="sp-tool" id="account-btn" aria-haspopup="true" aria-expanded="false" data-testid="account-button">…</button>
E - unexpected value "Login"
E
E Aria snapshot:
E - button "Login"
tests\test_generated.py:11: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_generated.py::test_user_can_log_in[lockeduser-chromium] - A...
1 failed, 1 passed in 9.86s
The lockeduser case fails, as it should: the generated test expects a successful login. In the next lesson you will use the same idea to load cases from JSON, CSV and Excel files.
✅ Good Practices for Data-Driven Tests
- One behaviour per test function. Parametrize the data, not the flow. Successful and failing logins are two behaviours: two functions.
- Always give readable ids, either with
pytest.param(..., id=...)orids=lambda case: case.name. - Keep the expected result in the data. A case without an expected value is not a test case.
- Prefer named data (dataclasses, dictionaries) once a case has more than three fields.
- Watch the count. Each case starts a fresh browser context; 200 cases × 3 browsers is 600 browser tests. Test the edges in the UI and the bulk of combinations through the API (Module 9).
- Never share state between cases. Every case must pass when run alone with
-k.
🏋️ 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 parametrized test for the SQA Shop search box. For the terms "jeans", "earbuds" and "course", search and assert that at least one product name contains the term (case-insensitive). Give each case the term as its id.
Show answer
import re
import pytest
from playwright.sync_api import Page, expect
SHOP = "/dummy-ecommerce-website/"
@pytest.mark.parametrize("term", ["jeans", "earbuds", "course"], ids=str)
def test_search_finds_term(page: Page, term):
page.goto(SHOP + "#/")
page.get_by_test_id("search-input").fill(term)
page.get_by_test_id("search-button").click()
names = page.get_by_test_id("product-name").filter(has_text=re.compile(term, re.IGNORECASE))
expect(names.first).to_be_visible()ids=str turns each value into its own id. Checking at least one name matters: the store’s search also matches category names, so a search for “jeans” can list “Chino Trousers” first.
Exercise 2: The test below uses a list of ids. Rewrite it with pytest.param so the id sits next to each case, and mark the "FLAT200" case on a small cart as xfail with a reason.
@pytest.mark.parametrize("code, ok", [("SAVE10", True), ("BOGUS", False), ("FLAT200", True)],
ids=["save10", "bogus", "flat200-small-cart"])
def test_coupon(page, code, ok): ...Show answer
@pytest.mark.parametrize("code, ok", [
pytest.param("SAVE10", True, id="save10"),
pytest.param("BOGUS", False, id="bogus"),
pytest.param("FLAT200", True, id="flat200-small-cart",
marks=pytest.mark.xfail(reason="FLAT200 needs a cart over ₹1,499", strict=True)),
])
def test_coupon(page, code, ok): ...Each id now lives with its data, so reordering cases can never attach the wrong name.
Exercise 3: Model this table as a dataclass and a parametrized test: product search term, sort option value (price-asc / price-desc), and whether prices must be ascending. Use ids=lambda c: c.name.
Show answer
from dataclasses import dataclass
import pytest
@dataclass(frozen=True)
class SortCase:
name: str
term: str
sort: str
ascending: bool
CASES = [
SortCase("shirts-cheapest-first", "shirt", "price-asc", True),
SortCase("laptops-dearest-first", "laptop", "price-desc", False),
]
@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name)
def test_sorting(page, case: SortCase):
... # search case.term, select case.sort, compare prices with sorted(..., reverse=not case.ascending)Exercise 4: You want every test in tests/test_header.py to run twice: once at desktop size (1280×720) and once at phone size (390×844). Write a parametrized fixture sized_page that sets the viewport.
Show answer
import pytest
from playwright.sync_api import Page
SIZES = {"desktop": (1280, 720), "phone": (390, 844)}
@pytest.fixture(params=list(SIZES), ids=list(SIZES))
def sized_page(request, page: Page) -> Page:
width, height = SIZES[request.param]
page.set_viewport_size({"width": width, "height": height})
return pageEvery test that asks for sized_page now runs once per size. For full device emulation (user agent, touch, device scale factor) see Lesson 50.
🧠 MCQ Quiz: Data-Driven Tests with parametrize
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does
@pytest.mark.parametrize("a, b", [(1, 2), (3, 4)])do?Answer: Generates two separate tests, one per tuple. Each tuple becomes its own collected test with its own id, fixtures and result. - Two
@pytest.mark.parametrizedecorators are stacked on one test, with 3 and 4 values. How many tests run?Answer: 12. Stacked parametrize decorators produce the cross product: 3 × 4 = 12. - Which is the best way to keep a case id next to its data?Answer:
pytest.param(..., id="name").pytest.paramstores the id (and marks) with the values, so reordering cases never mismatches ids. - How do you mark only one parametrized case as an expected failure?Answer:
pytest.param(..., marks=pytest.mark.xfail(reason=...)). Marks insidepytest.paramapply to that single case; a decorator on the function applies to all cases. - With
xfail(strict=True), what happens if the case unexpectedly passes?Answer: It is reported as a failure.strict=Trueturns an unexpected pass (XPASS) into a failed test, so a silent behaviour change is noticed. - Does each parametrized case of a Playwright test get its own
page?Answer: Yes,pageandcontextare function-scoped, so every case starts fresh. Each generated test is a separate test item, and pytest-playwright creates a new context and page for every test. - When should you prefer a parametrized fixture (
@pytest.fixture(params=...)) over@pytest.mark.parametrize?Answer: When many tests must run under each of several setups, such as user roles. A parametrized fixture multiplies every test that uses it, which suits shared setups like roles or locales. - What does
ids=lambda c: c.namedo?Answer: Builds each case’s test id from itsnameattribute. Whenidsis a function, pytest calls it for each parameter value and uses the returned string as the id. - Which hook lets you decide parameters at collection time, for example from a command-line option?Answer:
pytest_generate_tests.pytest_generate_tests(metafunc)runs for each test function during collection and can callmetafunc.parametrize. - Why should successful and failing logins usually be two test functions instead of one test with an
if?Answer: They are different behaviours; one flow per test keeps failures easy to read. Parametrize the data, not the flow. Branching tests hide which behaviour broke.
Want a longer, timed test? Take the Module 7 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Is data-driven testing the same as parametrization?
Parametrization is how pytest implements data-driven testing. The idea (same steps, many data rows with expected results) is tool-independent; @pytest.mark.parametrize, parametrized fixtures and pytest_generate_tests are the pytest mechanisms.
🤔 How many parameters are too many for a UI test?
There is no fixed number, but every case costs a browser context and several seconds. Keep UI cases to the meaningful edges (valid, each error type, boundaries) and push large combinatorial data sets to API tests, which run in milliseconds.
🤔 Can I parametrize with data from a file?
Yes. Load the file in a helper function and pass the result to parametrize, or use pytest_generate_tests. The next lesson shows JSON, CSV and Excel loaders step by step.
🤔 Why does my parametrized test id contain strange characters?
pytest builds ids from the values. Strings with spaces, symbols or non-ASCII characters are escaped, and empty strings make ids like -Test@123. Pass ids= or use pytest.param(..., id=...) for clean names.
🤔 Do parametrized tests run in parallel?
Not by default. Each case is a separate test, so with pytest-xdist (pytest -n 4) the cases are spread across workers automatically. Lesson 65 covers parallel runs.
🏁 Summary
- Data-driven testing runs one set of steps with many rows of data and expected results.
@pytest.mark.parametrizeturns one Playwright test into many; each case gets a fresh page.- Use
ids=orpytest.param(..., id=...)for readable names, andpytest.param(..., marks=...)to skip or xfail single cases. - Stacked parametrize decorators create every combination; use them only when every combination matters.
- Dataclasses give test cases names, types and defaults; parametrized fixtures vary the setup for many tests;
pytest_generate_testsbuilds cases at collection time.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page