Run Playwright Python Tests Against Multiple Environments

The same test suite usually has to run against several copies of an application: a QA server, a staging server before release and, carefully, production after release. Copying tests per environment is a maintenance trap. In this lesson you will run one suite anywhere by changing a single command-line option: use --base-url and relative URLs, add a custom --env option with pytest_addoption, keep each environment’s URL, users and flags in one config file, load per-environment .env secrets, and stop destructive tests from ever touching production.

📖 What You’ll Learn: why environments need configuration not code, relative URLs with base_url, the –base-url option and pytest.ini, a custom –env option with pytest_addoption, an environments.json config file, an env_config fixture that also drives base_url, per-environment .env files, markers that skip tests by environment, a production safety guard, and printing the environment in the report header.


🌍 One Suite, Many Environments

A typical company has at least these environments:

Environment Purpose What tests may do
local / dev A developer’s machine Anything
QA Shared test server Create and delete test data
staging Copy of production before a release Mostly read; limited test data
production Real users Read-only smoke tests only

The URLs, accounts and rules differ; the tests stay the same. The goal of this lesson is a command like:

⌨️ Terminal

pytest --env qa
pytest --env staging -m smoke
pytest --env prod -m smoke

🔗 Step 1: Relative URLs and –base-url

pytest-playwright (through the pytest-base-url plugin) gives every test a base_url. When it is set, page.goto() accepts relative URLs and joins them to it:

📄 pytest.ini

[pytest]
base_url = https://sqatools.in
markers =
    smoke: quick checks that are safe on every environment
    destructive: creates, changes or deletes data
    only_env(*names): run only on the named environments

📄 tests/test_relative.py

from playwright.sync_api import Page, expect


def test_store_home(page: Page, base_url):
    page.goto("/dummy-ecommerce-website/")          # becomes https://sqatools.in/dummy-ecommerce-website/
    print("\nopened", page.url, "with base_url", base_url)
    expect(page.get_by_test_id("logo")).to_be_visible()

⌨️ Terminal

pytest tests/test_relative.py -q -s

🖥️ Output

opened https://sqatools.in/dummy-ecommerce-website/ with base_url https://sqatools.in
.
1 passed in 2.52s

The command line beats the ini file, so pytest --base-url https://staging.example.com would run the same test on another host. Rule number one for multi-environment suites: never hard-code a host name in a test.

📌 Note: The base_url value from pytest.ini is also applied to context.new_page() and to the page fixture through browser_context_args, so every page in the test uses it.


⚙️ Step 2: A Custom –env Option

A URL alone is not enough: environments also differ in accounts, feature flags and what is allowed. Add a single --env option and keep the details in a config file.

📄 environments.json

{
  "qa": {
    "base_url": "https://sqatools.in",
    "shop_path": "/dummy-ecommerce-website/",
    "user": "testuser",
    "read_only": false
  },
  "staging": {
    "base_url": "https://sqatools.in",
    "shop_path": "/dummy-ecommerce-website/",
    "user": "testuser",
    "read_only": false
  },
  "prod": {
    "base_url": "https://sqatools.in",
    "shop_path": "/dummy-ecommerce-website/",
    "user": "testuser",
    "read_only": true
  }
}

📌 Note: SQA Tools has a single public practice site, so all three entries point at it and you can run every command in this lesson. In your project each entry would have its own host, for example https://qa.shop.example.com.

Since the host now comes from the config file, remove base_url from pytest.ini (otherwise pytest-base-url copies it into the --base-url option, and the option would always win):

📄 pytest.ini

[pytest]
markers =
    smoke: quick checks that are safe on every environment
    destructive: creates, changes or deletes data
    only_env(*names): run only on the named environments

The root conftest.py registers the option, loads the matching entry once per session, and overrides the base_url fixture so the URL comes from the config:

📄 conftest.py

import json
import os
from dataclasses import dataclass
from pathlib import Path

import pytest
from dotenv import load_dotenv

ROOT = Path(__file__).parent


def pytest_addoption(parser):
    parser.addoption("--env", default=os.getenv("TEST_ENV", "qa"), choices=["qa", "staging", "prod"],
                     help="target environment (default: qa, or $TEST_ENV)")


@dataclass(frozen=True)
class EnvConfig:
    name: str
    base_url: str
    shop_path: str
    user: str
    read_only: bool
    password: str


@pytest.fixture(scope="session")
def env_config(pytestconfig) -> EnvConfig:
    name = pytestconfig.getoption("--env")
    data = json.loads((ROOT / "environments.json").read_text(encoding="utf-8"))[name]
    load_dotenv(ROOT / f".env.{name}")                     # per-environment secrets, if the file exists
    password = os.getenv("SHOP_PASSWORD", "")
    return EnvConfig(name=name, password=password, **data)


@pytest.fixture(scope="session")
def base_url(env_config, pytestconfig) -> str:
    # an explicit --base-url still wins, which is handy for one-off runs
    return pytestconfig.getoption("base_url") or env_config.base_url


def pytest_report_header(config):
    return f"target environment: {config.getoption('--env')}"

Two details matter:

  • default=os.getenv("TEST_ENV", "qa") lets CI choose the environment with a variable instead of editing the command.
  • choices=[...] makes a typo such as --env stagin fail immediately with a clear argparse error.

Secrets come from .env.qa, .env.staging and .env.prod (all git-ignored, see Lesson 47):

📄 .env.qa

SHOP_PASSWORD=Test@123

📄 .env.staging

SHOP_PASSWORD=Test@123

📄 .env.prod

SHOP_PASSWORD=Test@123

🧪 Step 3: Tests That Use the Config

📄 tests/test_shop.py

import pytest
from playwright.sync_api import Page, expect


@pytest.mark.smoke
def test_store_loads(page: Page, env_config):
    page.goto(env_config.shop_path)
    expect(page.get_by_test_id("product-card").first).to_be_visible()


@pytest.mark.smoke
def test_user_can_log_in(page: Page, env_config):
    page.goto(env_config.shop_path + "#/login")
    page.get_by_test_id("login-username").fill(env_config.user)
    page.get_by_test_id("login-password").fill(env_config.password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")


@pytest.mark.destructive
def test_place_order(page: Page, env_config):
    page.goto(env_config.shop_path + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    expect(page.get_by_test_id("cart-count")).to_have_text("1")


@pytest.mark.only_env("qa")
def test_qa_only_feature(page: Page, env_config):
    page.goto(env_config.shop_path + "#/deals")
    expect(page.get_by_test_id("product-card").first).to_be_visible()

⌨️ Terminal

pytest tests/test_shop.py --env qa -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
target environment: qa
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_shop.py::test_store_loads[chromium] PASSED                    [ 25%]
tests/test_shop.py::test_user_can_log_in[chromium] PASSED                [ 50%]
tests/test_shop.py::test_place_order[chromium] PASSED                    [ 75%]
tests/test_shop.py::test_qa_only_feature[chromium] PASSED                [100%]

============================= 4 passed in 10.29s ==============================

The header line target environment: qa comes from pytest_report_header. It makes every CI log and HTML report state which environment was tested.


🛡️ Step 4: Protect Production

Nobody should be able to place orders or delete data on production by running the wrong command. A collection hook skips destructive tests on read-only environments and applies only_env markers:

📄 tests/conftest.py

import json
from pathlib import Path

import pytest

ENVIRONMENTS = json.loads((Path(__file__).parent.parent / "environments.json").read_text(encoding="utf-8"))


def pytest_collection_modifyitems(config, items):
    env = config.getoption("--env")
    read_only = ENVIRONMENTS[env]["read_only"]
    for item in items:
        if read_only and item.get_closest_marker("destructive"):
            item.add_marker(pytest.mark.skip(reason=f"destructive test blocked on read-only environment '{env}'"))
        only = item.get_closest_marker("only_env")
        if only and env not in only.args:
            item.add_marker(pytest.mark.skip(reason=f"runs only on {', '.join(only.args)}"))

⌨️ Terminal

pytest tests/test_shop.py --env prod -v -rs

🖥️ 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
target environment: prod
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_shop.py::test_store_loads[chromium] PASSED                    [ 25%]
tests/test_shop.py::test_user_can_log_in[chromium] PASSED                [ 50%]
tests/test_shop.py::test_place_order[chromium] SKIPPED (destructive ...) [ 75%]
tests/test_shop.py::test_qa_only_feature[chromium] SKIPPED (runs onl...) [100%]

=========================== short test summary info ===========================
SKIPPED [1] tests\test_shop.py:20: destructive test blocked on read-only environment 'prod'
SKIPPED [1] tests\test_shop.py:27: runs only on qa
======================== 2 passed, 2 skipped in 6.59s =========================

On prod the order test and the QA-only test are skipped with clear reasons (-rs prints them), and the smoke tests still run. The guard lives in one place, so a new destructive test is protected as soon as it is marked.

⚠️ Watch out: Skipping is a safety net, not a permission system. Production test accounts should also be restricted on the server side, so a mistake in the hook cannot do real damage.


🔀 Choosing the Environment Without the Option

Because the default comes from TEST_ENV, these are equivalent:

⌨️ Terminal

pytest --env staging
$env:TEST_ENV = "staging"; pytest          # PowerShell
TEST_ENV=staging pytest                    # macOS / Linux

⌨️ Terminal

$env:TEST_ENV = "staging"; pytest tests/test_shop.py -m smoke

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
target environment: staging
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
collected 4 items / 2 deselected / 2 selected

tests\test_shop.py ..                                                    [100%]

======================= 2 passed, 2 deselected in 4.50s =======================

The report header shows target environment: staging. A one-off override of only the host also still works, because the base_url fixture checks --base-url first:

⌨️ Terminal

pytest --env qa --base-url https://qa2.shop.example.com

🧭 What Belongs Where

Kind of value Where it lives
Host names, paths, feature flags, read-only flag environments.json (committed)
Passwords, API keys, tokens .env.<env> locally, CI secrets in pipelines (never committed)
Which environment to test --env option or TEST_ENV variable
Test inputs and expected results data files (Lesson 46)

🏋️ 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: Add a boolean field slow_network to each environment in environments.json and a fixture that sets the default navigation timeout to 60 seconds when it is true. Write the fixture.

Show answer
import pytest
from playwright.sync_api import Page


@pytest.fixture(autouse=True)
def env_timeouts(page: Page, env_config):
    if getattr(env_config, "slow_network", False):
        page.set_default_navigation_timeout(60_000)
    yield

Add slow_network: bool = False to the EnvConfig dataclass so the JSON field is accepted. autouse=True applies it to every test without changing them.

Exercise 2: Write a test marker prod_only and the hook code that skips such tests on every environment except prod.

Show answer
# pytest.ini: markers = prod_only: runs only against production

def pytest_collection_modifyitems(config, items):
    env = config.getoption("--env")
    for item in items:
        if item.get_closest_marker("prod_only") and env != "prod":
            item.add_marker(pytest.mark.skip(reason="production-only check"))

(This is a special case of only_env("prod"); prefer the general marker when you already have it.)

Exercise 3: A teammate runs pytest --env Staging and gets argument --env: invalid choice: 'Staging'. Change the option so the value is case-insensitive.

Show answer
parser.addoption("--env", default=os.getenv("TEST_ENV", "qa"), type=str.lower,
                 choices=["qa", "staging", "prod"], help="target environment")

argparse applies type before checking choices, so Staging becomes staging.

Exercise 4: Why does the lesson override the base_url fixture instead of writing page.goto(env_config.base_url + "/path") in every test?

Show answer

Overriding base_url makes relative goto() calls work everywhere (the page and every new context use it), keeps host names out of tests, and still lets an explicit --base-url win. Concatenating strings in tests repeats the host logic in hundreds of places and breaks easily (double or missing slashes).


🧠 MCQ Quiz: Run Against Multiple Environments

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does page.goto("/login") do when base_url is https://qa.example.com?
  2. Which wins: --base-url on the command line or base_url in pytest.ini?
  3. Which hook registers a custom option such as --env?
  4. What does choices=["qa", "staging", "prod"] on the option give you?
  5. Where should production passwords used by smoke tests live?
  6. What is the purpose of pytest_report_header in this lesson?
  7. How does the lesson stop destructive tests from running on production?
  8. What does item.get_closest_marker("only_env") return?
  9. Why give --env a default of os.getenv("TEST_ENV", "qa")?
  10. Why is skipping destructive tests on prod not enough on its own?

Want a longer, timed test? Take the Module 7 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Should I use separate test folders per environment?

No. Separate copies drift apart. Keep one suite and let configuration (and markers such as smoke or destructive) decide what runs where.

🤔 Can I run the suite against two environments in one command?

Not with one session-scoped env_config. Run pytest twice (for example as two CI jobs in a matrix), which also keeps the reports separate. Lesson 66 shows a GitHub Actions matrix.

🤔 Where do I put environment-specific test data, such as product IDs?

Add it to the environment entry in environments.json (or a data file per environment, such as test_data/qa/products.csv) and read it through env_config.

🤔 What is the difference between base_url and env_config.base_url here?

env_config.base_url is the value from the config file. The base_url fixture is what pytest-playwright uses for relative navigation; the lesson’s override returns --base-url if given, otherwise the config value.

🤔 How do I make API tests use the same environment?

Use env_config (or base_url) when you create the API request context: playwright.request.new_context(base_url=env_config.base_url). Module 9 covers API testing.


🏁 Summary

  • Never hard-code hosts: use relative page.goto() with base_url, which --base-url can override.
  • Add one --env option with pytest_addoption (default from TEST_ENV, validated with choices).
  • Keep URLs and flags in a committed environments.json; keep secrets in git-ignored .env.<env> files or CI secrets.
  • Override the base_url fixture from the environment config and print the environment with pytest_report_header.
  • Guard production with destructive and only_env markers in pytest_collection_modifyitems, plus server-side restrictions.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Environment Variables and .env Files in Playwright Python

A test that contains password = "Test@123" works on your laptop and is a security problem everywhere else. Passwords, API keys and environment URLs belong outside the code, in environment variables. In this lesson you will read environment variables in pytest, load them from a .env file with python-dotenv, commit a safe .env.example instead of the real file, build one validated settings object that fails fast when something is missing, and pass the same values from a CI pipeline.

📖 What You’ll Learn: what environment variables are and why tests need them, os.environ and os.getenv with defaults, setting variables in PowerShell, macOS and Linux, python-dotenv and load_dotenv in conftest.py, .env vs .env.example and .gitignore, precedence and override, a frozen Settings dataclass with validation, PYTEST_BASE_URL and PYTEST_ADDOPTS, masking secrets, and CI secrets.


🔐 Why Environment Variables?

Hard-coded values cause three problems in a test framework:

  1. Secrets leak. Anything committed to Git stays in its history forever, even after you delete the line.
  2. Environments differ. The QA server, staging and production have different URLs and accounts.
  3. People differ. Each tester and the CI server may use their own test account.

An environment variable is a named value that the operating system passes to every program it starts. Your test reads SHOP_USER and gets testuser on your laptop and ci-bot on the build server, with no code change.


🐍 Reading Variables in Python

os.environ is a dictionary-like object with all variables of the current process.

📄 read_env.py

import os

print("HOME or USERPROFILE set:", bool(os.getenv("HOME") or os.getenv("USERPROFILE")))
print("SHOP_USER =", os.getenv("SHOP_USER"))                      # None when missing
print("SHOP_TIMEOUT =", os.getenv("SHOP_TIMEOUT", "5000"))         # default when missing
try:
    os.environ["SHOP_PASSWORD"]                                     # KeyError when missing
except KeyError as e:
    print("missing:", e)

⌨️ Terminal

python read_env.py

🖥️ Output

HOME or USERPROFILE set: True
SHOP_USER = None
SHOP_TIMEOUT = 5000
missing: 'SHOP_PASSWORD'
Call When the variable is missing
os.environ["NAME"] raises KeyError (good for required values)
os.getenv("NAME") returns None
os.getenv("NAME", "default") returns the default (good for optional values)

⚠️ Watch out: Environment variables are always strings. os.getenv("SHOP_TIMEOUT", "5000") returns "5000", and os.getenv("HEADLESS") == "false" is the only safe way to read a flag: bool("false") is True.


⌨️ Setting Variables for One Run

How you set a variable depends on your shell. The value exists only for that terminal window (or that one command).

Windows PowerShell:

⌨️ Terminal

$env:SHOP_USER = "testuser"
$env:SHOP_PASSWORD = "Test@123"
pytest -q

macOS and Linux (bash or zsh):

⌨️ Terminal

export SHOP_USER=testuser
export SHOP_PASSWORD='Test@123'
pytest -q
# or for a single command only:
SHOP_USER=testuser SHOP_PASSWORD='Test@123' pytest -q

Typing these every day is tedious and error-prone, which is where .env files come in.


📄 .env Files with python-dotenv

A .env file is a plain text file of NAME=value lines. The python-dotenv library reads it and puts the values into os.environ.

⌨️ Terminal

pip install python-dotenv

Create the project files:

📄 pytest.ini

[pytest]
base_url = https://sqatools.in

📄 .env

# Local settings for this machine. Never commit this file.
SHOP_USER=testuser
SHOP_PASSWORD=Test@123
SHOP_PATH=/dummy-ecommerce-website/
EXPECT_TIMEOUT=7000

Load the file as early as possible: in the root conftest.py, at import time, so every fixture and test sees the values.

📄 conftest.py

import os
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import expect

load_dotenv(Path(__file__).parent / ".env")          # explicit path: works from any folder

expect.set_options(timeout=int(os.getenv("EXPECT_TIMEOUT", "5000")))

Now a test can log in without any secret in the code:

📄 tests/test_login_env.py

import os

from playwright.sync_api import Page, expect


def test_login_with_env_credentials(page: Page):
    page.goto(os.environ["SHOP_PATH"] + "#/login")
    page.get_by_test_id("login-username").fill(os.environ["SHOP_USER"])
    page.get_by_test_id("login-password").fill(os.environ["SHOP_PASSWORD"])
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")

⌨️ Terminal

pytest tests/test_login_env.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 1 item

tests/test_login_env.py::test_login_with_env_credentials[chromium] PASSED [100%]

============================== 1 passed in 3.25s ==============================

expect.set_options(timeout=...) changes the default timeout of every expect() assertion, here from 5 to 7 seconds, controlled by the .env file.


🙈 .env, .env.example and .gitignore

The real .env must never be committed. Add it to .gitignore and commit a template with the same names and safe placeholder values:

📄 .gitignore

.env
.env.*
!.env.example

📄 .env.example

# Copy this file to .env and fill in your own values.
SHOP_USER=
SHOP_PASSWORD=
SHOP_PATH=/dummy-ecommerce-website/
EXPECT_TIMEOUT=5000

A new team member runs copy .env.example .env (Windows) or cp .env.example .env (macOS/Linux), fills in their account, and is ready. The !.env.example line re-includes the template that .env.* would otherwise ignore. See the Git and GitHub tutorial for more .gitignore patterns.

⚠️ Watch out: If a secret was ever committed, deleting it in a new commit is not enough: it is still in the history. Change the password or rotate the key, then clean the history if your policy requires it.


⚖️ Which Value Wins? Precedence and override

By default load_dotenv() does not overwrite variables that already exist. So a value set in the terminal or by CI beats the .env file, which is exactly what you want: CI can inject its own credentials while developers rely on .env.

📄 precedence.py

import os

from dotenv import load_dotenv

os.environ["SHOP_USER"] = "ci-bot"                 # pretend CI already set it
load_dotenv(".env")
print("default:", os.environ["SHOP_USER"])          # ci-bot: existing value kept

load_dotenv(".env", override=True)
print("override=True:", os.environ["SHOP_USER"])    # testuser: the file wins

⌨️ Terminal

python precedence.py

🖥️ Output

default: ci-bot
override=True: testuser

Use override=True only when the file must win, for example when you load a specific environment file on purpose (next lesson).


🧱 One Validated Settings Object

Scattering os.environ[...] across fifty tests makes it hard to see what the framework needs, and a missing variable fails deep inside a test. Collect everything in one place and check it once, at startup:

📄 settings.py

import os
from dataclasses import dataclass, field
from pathlib import Path

from dotenv import load_dotenv

load_dotenv(Path(__file__).parent / ".env")


@dataclass(frozen=True)
class Settings:
    shop_user: str
    shop_password: str = field(repr=False)          # never printed in logs or reports
    shop_path: str = "/dummy-ecommerce-website/"
    expect_timeout: int = 5000
    headless: bool = True


def load_settings() -> Settings:
    required = ["SHOP_USER", "SHOP_PASSWORD"]
    missing = [name for name in required if not os.getenv(name)]
    if missing:
        raise RuntimeError(f"Missing environment variables: {', '.join(missing)}. Copy .env.example to .env and fill them in.")
    return Settings(
        shop_user=os.environ["SHOP_USER"],
        shop_password=os.environ["SHOP_PASSWORD"],
        shop_path=os.getenv("SHOP_PATH", "/dummy-ecommerce-website/"),
        expect_timeout=int(os.getenv("EXPECT_TIMEOUT", "5000")),
        headless=os.getenv("HEADLESS", "true").lower() != "false",
    )


if __name__ == "__main__":
    print(load_settings())

⌨️ Terminal

python settings.py

🖥️ Output

Settings(shop_user='testuser', shop_path='/dummy-ecommerce-website/', expect_timeout=7000, headless=True)

The password is filled in but not printed: field(repr=False) hides it from repr(), so it never appears in a log, a pytest failure message or an HTML report.

Expose it as a session fixture:

📄 tests/conftest.py

import pytest

from settings import Settings, load_settings


@pytest.fixture(scope="session")
def settings() -> Settings:
    return load_settings()

📄 tests/test_login_settings.py

from playwright.sync_api import Page, expect

from settings import Settings


def test_login_with_settings(page: Page, settings: Settings):
    page.goto(settings.shop_path + "#/login")
    page.get_by_test_id("login-username").fill(settings.shop_user)
    page.get_by_test_id("login-password").fill(settings.shop_password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")

⌨️ Terminal

pytest tests/test_login_settings.py -q

🖥️ Output

.                                                                        [100%]
1 passed in 2.66s

What happens when a variable is missing? Rename the .env file away and run again:

⌨️ Terminal

move .env .env.bak
pytest tests/test_login_settings.py -q

🖥️ Output

E                                                                        [100%]
=================================== ERRORS ====================================
____________ ERROR at setup of test_login_with_settings[chromium] _____________

    @pytest.fixture(scope="session")
    def settings() -> Settings:
>       return load_settings()
               ^^^^^^^^^^^^^^^

tests\conftest.py:8: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    def load_settings() -> Settings:
        required = ["SHOP_USER", "SHOP_PASSWORD"]
        missing = [name for name in required if not os.getenv(name)]
        if missing:
>           raise RuntimeError(f"Missing environment variables: {', '.join(missing)}. Copy .env.example to .env and fill them in.")
E           RuntimeError: Missing environment variables: SHOP_USER, SHOP_PASSWORD. Copy .env.example to .env and fill them in.

settings.py:23: RuntimeError
=========================== short test summary info ===========================
ERROR tests/test_login_settings.py::test_login_with_settings[chromium] - Runt...
1 error in 0.88s

The test errors in setup with a message that says exactly what to do, instead of typing None into a login form.


🌐 Variables pytest Itself Understands

Some tools read environment variables directly, which is handy in CI:

Variable Read by Effect
PYTEST_BASE_URL pytest-base-url Default for --base-url (beats base_url in pytest.ini)
PYTEST_ADDOPTS pytest Extra command-line options added to every run
PWDEBUG=1 Playwright Opens the Playwright Inspector and runs headed (Lesson 61)
DEBUG=pw:api Playwright Logs every Playwright API call to the terminal

📄 tests/test_base_url.py

def test_print_base_url(base_url):
    print("base_url =", base_url)

⌨️ Terminal

$env:PYTEST_BASE_URL = "https://sqatools.in/"
pytest tests/test_base_url.py -q -s

🖥️ Output

base_url = https://sqatools.in/
.
1 passed in 0.01s

The value from the environment replaced the base_url in pytest.ini (notice the trailing slash). The next lesson uses this to switch between environments.


🚀 Environment Variables in CI

In CI you do not create a .env file. The pipeline stores secrets encrypted and exposes them as environment variables to the test step. In GitHub Actions:

- name: Run Playwright tests
  env:
    SHOP_USER: ${{ secrets.SHOP_USER }}
    SHOP_PASSWORD: ${{ secrets.SHOP_PASSWORD }}
    EXPECT_TIMEOUT: "10000"
  run: pytest

Because load_dotenv() does not override existing variables, the same conftest.py works locally (values from .env) and in CI (values from secrets). Lesson 66 builds the full workflow, and Lesson 67 does the same in Jenkins with withCredentials.


🏋️ 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 fixture credentials that returns a (username, password) tuple from SHOP_USER and SHOP_PASSWORD, and calls pytest.fail() with a helpful message when either is missing.

Show answer
import os

import pytest


@pytest.fixture(scope="session")
def credentials() -> tuple[str, str]:
    user, password = os.getenv("SHOP_USER"), os.getenv("SHOP_PASSWORD")
    if not user or not password:
        pytest.fail("Set SHOP_USER and SHOP_PASSWORD (copy .env.example to .env)", pytrace=False)
    return user, password

pytrace=False prints only the message, without a long traceback.

Exercise 2: A teammate writes headless = bool(os.getenv("HEADLESS", "true")) and is surprised that HEADLESS=false still runs headless. Explain and fix it.

Show answer

Environment variables are strings, and every non-empty string is truthy, so bool("false") is True. Compare the text instead:

headless = os.getenv("HEADLESS", "true").strip().lower() not in ("false", "0", "no")

Exercise 3: CI sets SHOP_USER=ci-bot, and the repository also contains a .env with SHOP_USER=testuser (by mistake). Which value do the tests use with load_dotenv(), and with load_dotenv(override=True)?

Show answer

With the default load_dotenv() the existing value wins, so tests use ci-bot. With override=True the file wins and tests use testuser. Keep the default for local .env files, and make sure .env is in .gitignore so it never reaches CI.

Exercise 4: Add an api_key field to the Settings dataclass so that it is required but never appears in logs or in pytest failure output.

Show answer
@dataclass(frozen=True)
class Settings:
    shop_user: str
    shop_password: str = field(repr=False)
    api_key: str = field(repr=False, default="")

and in load_settings() add "API_KEY" to required and pass api_key=os.environ["API_KEY"]. repr=False keeps it out of repr(), which is what pytest and loggers print.


🧠 MCQ Quiz: Environment Variables and .env Files

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does os.getenv("NAME") return when the variable is not set?
  2. What is bool(os.getenv("HEADLESS")) when HEADLESS=false?
  3. Which file should be committed to Git?
  4. By default, does load_dotenv() overwrite a variable that is already set in the environment?
  5. Where is the best place to call load_dotenv() in a pytest project?
  6. What does field(repr=False) on a dataclass field do?
  7. Which environment variable sets the default for pytest-playwright’s --base-url?
  8. How do you set a variable for the current PowerShell session?
  9. A password was committed to Git and removed in the next commit. What must you do?
  10. How should CI provide secrets to Playwright tests?

Want a longer, timed test? Take the Module 7 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Is there a pytest plugin that loads .env automatically?

Yes, pytest-dotenv loads .env files listed in pytest.ini. Calling load_dotenv() yourself in conftest.py does the same with one line and no extra plugin, and makes the precedence explicit.

🤔 Can I keep several .env files, one per environment?

Yes, for example .env.qa and .env.staging, and choose one with a command-line option or an ENV variable. The next lesson builds exactly that.

🤔 Do environment variables work with pytest-xdist workers?

Yes. Worker processes inherit the environment of the main pytest process, and each worker imports conftest.py, so load_dotenv() runs there too.

🤔 Should test data like usernames go in .env?

Only values that differ per machine or environment, or that are secret. Shared test data (search terms, expected messages) belongs in data files (previous lesson).

🤔 How do I see which variables are set?

In PowerShell run Get-ChildItem env:; on macOS or Linux run env or printenv. In Python, print(sorted(os.environ)) lists the names. Never print the values of secrets.


🏁 Summary

  • Keep secrets and per-environment values in environment variables, not in test code.
  • os.environ["X"] for required values, os.getenv("X", default) for optional ones; every value is a string.
  • python-dotenv loads .env into the environment; commit .env.example, ignore .env.
  • Existing variables beat the file unless override=True, so CI secrets win over local files.
  • Validate everything once in a Settings object, hide secrets with repr=False, and use PYTEST_BASE_URL / PYTEST_ADDOPTS in CI.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Read Test Data from JSON, CSV and Excel in Playwright Python

In the previous lesson the test data lived inside the test file. Real teams keep it in files that testers, analysts and even business users can edit: JSON for structured data, CSV for simple tables and Excel because that is where the requirements already are. In this lesson you will build a small, reusable data loader that reads all three formats, turns every row into a named pytest case, validates the rows before any browser starts, and drives real Playwright tests on the SQA Shop practice store.

📖 What You’ll Learn: when to use JSON, CSV or Excel for test data, a test_data folder and paths that work from anywhere, a JSON loader with nested data, csv.DictReader and type conversion, reading .xlsx with openpyxl, turning rows into pytest.param ids, validating rows with a dataclass, caching loaded files, and the encoding and empty-cell traps.


📁 Choosing a Format

Format Good for Watch out for
JSON Nested data (a user with an address and a cart), typed values (numbers, booleans, null) Hard for non-programmers to edit; no comments
CSV Flat tables, easy diffs in Git, editable in any spreadsheet Every value is a string; commas and encodings
Excel (.xlsx) Data owned by business users or copied from requirements Binary file (poor Git diffs), needs openpyxl, empty cells become None

A common, healthy setup: JSON for framework data (users, environments), CSV or Excel for large tables of cases that someone else maintains.


🗂️ Project Layout

project/
├── pytest.ini
├── test_data/
│   ├── login_cases.json
│   ├── search_cases.csv
│   └── coupon_cases.xlsx
└── tests/
    ├── __init__.py
    ├── data_loader.py
    ├── test_login_json.py
    ├── test_search_csv.py
    └── test_coupon_excel.py

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

Install the Excel library once (pytest-playwright is already installed from Lesson 2):

⌨️ Terminal

pip install openpyxl

📍 Paths That Work from Anywhere

The most common data-file bug is a relative path such as open("test_data/login_cases.json"). It works when you run pytest from the project root and fails from an IDE, from a sub-folder or in CI. Build paths from the location of the Python file instead:

from pathlib import Path

DATA_DIR = Path(__file__).resolve().parent.parent / "test_data"   # tests/ -> project/ -> test_data/

Path(__file__) is the loader file itself, so DATA_DIR is correct no matter where pytest was started.


🧾 JSON Test Data

JSON keeps types: true becomes True, null becomes None, numbers stay numbers. It also nests, so one case can hold several related values.

📄 test_data/login_cases.json

[
  {"id": "valid-user", "username": "testuser", "password": "Test@123", "error": null},
  {"id": "wrong-password", "username": "testuser", "password": "nope", "error": "Invalid username or password."},
  {"id": "locked-user", "username": "lockeduser", "password": "Test@123", "error": "This account is locked. Please contact support."},
  {"id": "missing-password", "username": "testuser", "password": "", "error": "Password is required."}
]

The loader reads the file once and turns each object into a pytest.param whose id comes from the data:

📄 tests/data_loader.py

import csv
import json
from functools import cache
from pathlib import Path

import pytest
from openpyxl import load_workbook

DATA_DIR = Path(__file__).resolve().parent.parent / "test_data"


@cache
def read_json(name: str) -> list[dict]:
    with open(DATA_DIR / name, encoding="utf-8") as f:
        return json.load(f)


@cache
def read_csv(name: str) -> list[dict]:
    # utf-8-sig also accepts files saved by Excel, which start with a byte-order mark
    with open(DATA_DIR / name, encoding="utf-8-sig", newline="") as f:
        return list(csv.DictReader(f))


@cache
def read_excel(name: str, sheet: str | None = None) -> list[dict]:
    wb = load_workbook(DATA_DIR / name, read_only=True, data_only=True)
    ws = wb[sheet] if sheet else wb.active
    rows = ws.iter_rows(values_only=True)
    header = [str(h).strip() for h in next(rows)]
    data = [dict(zip(header, row)) for row in rows if any(v is not None for v in row)]
    wb.close()
    return data


def as_params(rows: list[dict], fields: list[str], id_field: str = "id") -> list:
    """Rows -> pytest.param objects with the given fields, named by id_field. Rows with run = no are skipped."""
    params = []
    for row in rows:
        marks = []
        if str(row.get("run", "yes")).strip().lower() in ("no", "false", "0"):
            marks.append(pytest.mark.skip(reason="disabled in the data file"))
        params.append(pytest.param(*(row[f] for f in fields), id=str(row[id_field]), marks=marks))
    return params

Three details are worth copying into your own framework:

  • @cache (from functools) reads each file once per test session, even if 50 tests use it.
  • encoding="utf-8-sig" silently drops the invisible byte-order mark that Excel puts at the start of “CSV UTF-8” files. Without it the first column header becomes 'id' and row["id"] raises KeyError.
  • A run column lets the data owner switch a case off without touching Python code.

Now the test:

📄 tests/test_login_json.py

import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_json

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("username, password, error", as_params(read_json("login_cases.json"), ["username", "password", "error"]))
def test_login_from_json(page: Page, username, password, error):
    page.goto(SHOP + "#/login")
    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 error is None:
        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(error)

⌨️ Terminal

pytest tests/test_login_json.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_json.py::test_login_from_json[chromium-valid-user] PASSED [ 25%]
tests/test_login_json.py::test_login_from_json[chromium-wrong-password] PASSED [ 50%]
tests/test_login_json.py::test_login_from_json[chromium-locked-user] PASSED [ 75%]
tests/test_login_json.py::test_login_from_json[chromium-missing-password] PASSED [100%]

============================== 4 passed in 8.73s ==============================

The ids (valid-user, locked-user …) come straight from the JSON file, so a failure report tells you exactly which row broke.


📊 CSV Test Data

CSV is the simplest format for a table of cases. This file drives search tests: a search term, the minimum number of results and a word that at least one product name must contain.

📄 test_data/search_cases.csv

id,term,min_results,name_contains,run
earbuds,earbuds,1,Earbuds,yes
jeans,jeans,3,Jeans,yes
course,course,3,Course,yes
smart-tv,smart tv,1,Smart TV,yes
not-ready,hoverboard,1,Hoverboard,no

⚠️ Watch out: Every CSV value is a string. min_results arrives as "3", not 3, and "no" is a non-empty string, which is truthy in Python. Convert types explicitly, as the test below does with int(...), and compare flags as text (== "yes"), never with if row["run"]:.

📄 tests/test_search_csv.py

import re

import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_csv

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("term, min_results, name_contains", as_params(read_csv("search_cases.csv"), ["term", "min_results", "name_contains"]))
def test_search_from_csv(page: Page, term, min_results, name_contains):
    page.goto(SHOP + "#/")
    page.get_by_test_id("search-input").fill(term)
    page.get_by_test_id("search-button").click()

    cards = page.get_by_test_id("product-card")
    expect(cards.first).to_be_visible()
    assert cards.count() >= int(min_results)          # CSV gives "3"; convert before comparing
    names = page.get_by_test_id("product-name").filter(has_text=re.compile(name_contains, re.IGNORECASE))
    expect(names.first).to_be_visible()                # search also matches categories, so not every card has the word

⌨️ Terminal

pytest tests/test_search_csv.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 5 items

tests/test_search_csv.py::test_search_from_csv[chromium-earbuds] PASSED  [ 20%]
tests/test_search_csv.py::test_search_from_csv[chromium-jeans] PASSED    [ 40%]
tests/test_search_csv.py::test_search_from_csv[chromium-course] PASSED   [ 60%]
tests/test_search_csv.py::test_search_from_csv[chromium-smart-tv] PASSED [ 80%]
tests/test_search_csv.py::test_search_from_csv[chromium-not-ready] SKIPPED [100%]

======================== 4 passed, 1 skipped in 9.74s =========================

The not-ready row shows as SKIPPED with the reason “disabled in the data file”, because its run column is no.


📗 Excel Test Data with openpyxl

Excel is common when manual testers or product owners write the cases. To keep this lesson repeatable, a short script creates the workbook. In a real project someone would create it in Excel or Google Sheets and save it as .xlsx.

📄 make_coupon_workbook.py

from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "coupons"
ws.append(["id", "product", "code", "message", "discount"])
ws.append(["save10-capped", "Wireless Earbuds", "SAVE10", "Coupon SAVE10 applied.", 500])
ws.append(["flat200", "Wireless Earbuds", "FLAT200", "Coupon FLAT200 applied.", 200])
ws.append(["save10-below-minimum", "Agile Testing Handbook", "SAVE10", "Add ₹500 more to use SAVE10.", None])
ws.append(["unknown-code", "Wireless Earbuds", "BOGUS", "This coupon code is not valid.", None])
wb.save("test_data/coupon_cases.xlsx")
print("saved", ws.max_row - 1, "cases")

⌨️ Terminal

python make_coupon_workbook.py

🖥️ Output

saved 4 cases

Two Excel facts show up immediately:

  • The discount column holds numbers (500), not text, because openpyxl reads real cell types.
  • Empty cells come back as None. In this workbook None means “no discount line is shown”.

Look at the rows the loader returns:

📄 show_rows.py

from tests.data_loader import read_excel

for row in read_excel("coupon_cases.xlsx", "coupons"):
    print(row)

⌨️ Terminal

python show_rows.py

🖥️ Output

{'id': 'save10-capped', 'product': 'Wireless Earbuds', 'code': 'SAVE10', 'message': 'Coupon SAVE10 applied.', 'discount': 500}
{'id': 'flat200', 'product': 'Wireless Earbuds', 'code': 'FLAT200', 'message': 'Coupon FLAT200 applied.', 'discount': 200}
{'id': 'save10-below-minimum', 'product': 'Agile Testing Handbook', 'code': 'SAVE10', 'message': 'Add ₹500 more to use SAVE10.', 'discount': None}
{'id': 'unknown-code', 'product': 'Wireless Earbuds', 'code': 'BOGUS', 'message': 'This coupon code is not valid.', 'discount': None}

The test adds the product to the cart, applies the coupon and checks both the message and the discount line:

📄 tests/test_coupon_excel.py

import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_excel

SHOP = "/dummy-ecommerce-website/"
CASES = as_params(read_excel("coupon_cases.xlsx", "coupons"), ["product", "code", "message", "discount"])


@pytest.mark.parametrize("product, code, message, discount", CASES)
def test_coupon_from_excel(page: Page, product, code, message, discount):
    page.goto(SHOP + "#/search/" + product)
    card = page.get_by_test_id("product-card").filter(has_text=product).first
    card.get_by_role("button", name="Add to cart").click()
    expect(page.get_by_test_id("cart-count")).to_have_text("1")

    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill(code)
    page.get_by_test_id("apply-coupon").click()

    expect(page.get_by_test_id("coupon-message")).to_have_text(message)
    discount_line = page.get_by_test_id("coupon-discount")
    if discount is None:
        expect(discount_line).to_have_count(0)
    else:
        expect(discount_line).to_have_text(f"−₹{discount:,}")

⌨️ Terminal

pytest tests/test_coupon_excel.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_coupon_excel.py::test_coupon_from_excel[chromium-save10-capped] PASSED [ 25%]
tests/test_coupon_excel.py::test_coupon_from_excel[chromium-flat200] PASSED [ 50%]
tests/test_coupon_excel.py::test_coupon_from_excel[chromium-save10-below-minimum] PASSED [ 75%]
tests/test_coupon_excel.py::test_coupon_from_excel[chromium-unknown-code] PASSED [100%]

============================== 4 passed in 8.94s ==============================

Note f"−₹{discount:,}": the store prints a real minus sign (−, not a hyphen) and Indian-style digit grouping. Copy expected text from the page, not from memory.

💡 Tip: data_only=True makes openpyxl return the calculated value of formula cells (=A2*2 gives the number) instead of the formula text. It only works if the file was last saved by Excel or LibreOffice, which store the computed values.


🛡️ Validate Rows Before the Browser Starts

A typo in a data file (usrname instead of username) should fail fast with a clear message, not 30 seconds later inside a browser. A frozen dataclass checks every row at collection time:

📄 tests/test_validated.py

from dataclasses import dataclass, fields

import pytest

from tests.data_loader import read_json


@dataclass(frozen=True)
class LoginRow:
    id: str
    username: str
    password: str
    error: str | None

    @classmethod
    def from_row(cls, row: dict) -> "LoginRow":
        expected = {f.name for f in fields(cls)}
        missing, extra = expected - row.keys(), row.keys() - expected
        if missing or extra:
            raise ValueError(f"row {row.get('id', '?')}: missing {sorted(missing)}, unexpected {sorted(extra)}")
        return cls(**row)


ROWS = [LoginRow.from_row(r) for r in read_json("login_cases.json")]


@pytest.mark.parametrize("row", ROWS, ids=lambda r: r.id)
def test_rows_are_valid(row: LoginRow):
    assert row.username or row.error, "a row with no username must expect an error"

⌨️ Terminal

pytest tests/test_validated.py -q

🖥️ Output

....                                                                     [100%]
4 passed in 0.25s

Now break the file on purpose: add a row with a misspelt key and run again.

📄 break_data.py

import json
from pathlib import Path

path = Path("test_data/login_cases_broken.json")
rows = json.loads(Path("test_data/login_cases.json").read_text(encoding="utf-8"))
rows.append({"id": "typo", "usrname": "testuser", "password": "x", "error": None})
path.write_text(json.dumps(rows, indent=1), encoding="utf-8")

from tests.test_validated import LoginRow  # noqa: E402

for r in rows:
    try:
        LoginRow.from_row(r)
    except ValueError as e:
        print("Invalid data:", e)

⌨️ Terminal

python break_data.py

🖥️ Output

Invalid data: row typo: missing ['username'], unexpected ['usrname']

The error names the row and the exact problem before any browser opens.


⚖️ Data Files: Good Practices

  1. One loader module for the whole framework, so encoding, paths and skipping work the same everywhere.
  2. An id column in every file. Readable ids are the difference between “row 37 failed” and “save10-capped failed”.
  3. Keep expected results in the data, next to the inputs.
  4. Never put real passwords or personal data in data files. Use test accounts, and read secrets from environment variables (next lesson).
  5. Prefer CSV or JSON in Git, because reviewers can see changes line by line. If business users own an Excel file, export it to CSV in CI or review it with a script.
  6. Validate rows at collection time so broken data fails in milliseconds with a clear message.

🏋️ 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 read_json call and a parametrized test that loads test_data/users.json (a list of objects with id, username and display_name) and checks that after logging in, the account button contains "Hi, " + display_name.split()[0]. Assume the password is always Test@123.

Show answer
import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_json


@pytest.mark.parametrize("username, display_name", as_params(read_json("users.json"), ["username", "display_name"]))
def test_greeting(page: Page, username, display_name):
    page.goto("/dummy-ecommerce-website/#/login")
    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, " + display_name.split()[0])

Exercise 2: A CSV file saved from Excel makes row["id"] raise KeyError: 'id', although the header clearly says id. What is wrong and how do you fix it?

Show answer

Excel’s “CSV UTF-8” format starts the file with a byte-order mark (BOM), so the first header is read as 'id'. Open the file with encoding="utf-8-sig", which removes the BOM:

with open(path, encoding="utf-8-sig", newline="") as f:
    rows = list(csv.DictReader(f))

Exercise 3: Your CSV has a column expected_count and a column active with values yes/no. Write the two conversions you need before using them in a test.

Show answer
count = int(row["expected_count"])               # "3" -> 3
active = row["active"].strip().lower() == "yes"  # never `if row["active"]:` - "no" is truthy

Every value from csv.DictReader is a string, so numbers and flags must be converted explicitly.

Exercise 4: Extend read_excel so it raises a clear error when a required column is missing from the header row. The function should take required: set[str].

Show answer
def read_excel(name: str, sheet: str | None = None, required: set[str] = frozenset()) -> list[dict]:
    wb = load_workbook(DATA_DIR / name, read_only=True, data_only=True)
    ws = wb[sheet] if sheet else wb.active
    rows = ws.iter_rows(values_only=True)
    header = [str(h).strip() for h in next(rows)]
    missing = required - set(header)
    if missing:
        wb.close()
        raise ValueError(f"{name}: missing columns {sorted(missing)}")
    data = [dict(zip(header, row)) for row in rows if any(v is not None for v in row)]
    wb.close()
    return data

(Remove @cache or make required a frozenset, because cached functions need hashable arguments.)


🧠 MCQ Quiz: Read Test Data from JSON, CSV and Excel

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why build data paths with Path(__file__).resolve().parent?
  2. What type does csv.DictReader return for a cell containing 42?
  3. What does encoding="utf-8-sig" fix when reading CSV files?
  4. In openpyxl, what does an empty cell return with iter_rows(values_only=True)?
  5. What does load_workbook(..., data_only=True) do?
  6. What is the benefit of decorating a loader with functools.cache?
  7. A CSV column run contains no. Why is if row["run"]: wrong?
  8. Which format keeps nested data and real types such as booleans and null?
  9. Why validate data rows at collection time with a dataclass?
  10. Which is the best place for a real production password used by tests?

Want a longer, timed test? Take the Module 7 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Should I use pandas to read test data?

You can, but it is a large dependency for reading a few hundred rows, and it converts types in ways that surprise testers (for example, IDs such as 007 become 7). csv, json and openpyxl are enough for test data and keep values predictable.

🤔 Can I read Google Sheets directly?

Yes, through the Google Sheets API (for example with the gspread library), but tests then depend on the network and on credentials. A safer pattern is to export the sheet to CSV in a pipeline step and commit or cache the file.

🤔 How do I read the old .xls format?

openpyxl reads only .xlsx. Save old files as .xlsx, or use the xlrd library, which still supports .xls.

🤔 Where should the data loader live?

In a shared module such as utils/data_loader.py or tests/data_loader.py, imported by every test. Lesson 57 shows a full framework folder structure.

🤔 How do I parametrize with YAML?

Install PyYAML, read the file with yaml.safe_load(f) and pass the resulting list to as_params exactly like JSON. Always use safe_load, never load, for files you did not write.


🏁 Summary

  • Use JSON for typed or nested data, CSV for flat tables in Git, Excel when business users own the cases.
  • Build paths from Path(__file__), read files once with @cache, and use utf-8-sig for CSV from Excel.
  • CSV values are strings; openpyxl returns real types and None for empty cells.
  • Turn rows into pytest.param with ids from an id column, and let a run column skip cases.
  • Validate rows at collection time so broken data fails fast and clearly.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

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-trimmed passed: the app trims the username, which is a behaviour worth pinning down with a test.
  • password-case-insensitive is XFAIL: we expected it to fail, and it did. With strict=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:

  1. ids=lambda c: c.name takes the id from the data itself, so ids and data can never drift apart.
  2. Defaults (password="Test@123") keep each case short: you only write what is special about it.
  3. The “remember me” case checks a real side effect: the store saves spUser in localStorage only 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

  1. One behaviour per test function. Parametrize the data, not the flow. Successful and failing logins are two behaviours: two functions.
  2. Always give readable ids, either with pytest.param(..., id=...) or ids=lambda case: case.name.
  3. Keep the expected result in the data. A case without an expected value is not a test case.
  4. Prefer named data (dataclasses, dictionaries) once a case has more than three fields.
  5. 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).
  6. 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 page

Every 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.

  1. What does @pytest.mark.parametrize("a, b", [(1, 2), (3, 4)]) do?
  2. Two @pytest.mark.parametrize decorators are stacked on one test, with 3 and 4 values. How many tests run?
  3. Which is the best way to keep a case id next to its data?
  4. How do you mark only one parametrized case as an expected failure?
  5. With xfail(strict=True), what happens if the case unexpectedly passes?
  6. Does each parametrized case of a Playwright test get its own page?
  7. When should you prefer a parametrized fixture (@pytest.fixture(params=...)) over @pytest.mark.parametrize?
  8. What does ids=lambda c: c.name do?
  9. Which hook lets you decide parameters at collection time, for example from a command-line option?
  10. Why should successful and failing logins usually be two test functions instead of one test with an if?

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.parametrize turns one Playwright test into many; each case gets a fresh page.
  • Use ids= or pytest.param(..., id=...) for readable names, and pytest.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_tests builds cases at collection time.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Query into pandas

Python Practice › SQLite Programs › Program 20

Query into pandas

EasySQLite Programs · 20 of 20

Write a Python program to load a query result into a pandas DataFrame.

Output
    city  total
0   Pune   2180
1  Delhi    450

Approach

  1. pd.read_sql_query(sql, conn).

Solution

Python
import sqlite3import pandas as pd conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE sales (city TEXT, amount INTEGER)")conn.executemany("INSERT INTO sales VALUES (?, ?)", [("Pune", 1200), ("Delhi", 450), ("Pune", 980)])df = pd.read_sql_query("SELECT city, SUM(amount) AS total FROM sales GROUP BY city ORDER BY total DESC", conn)print(df)
Output
    city  total
0   Pune   2180
1  Delhi    450

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Python SQLite Programs with Solutions

Python Practice › SQLite Programs

Python SQLite Programs with Solutions

20 programs19 easy1 medium0 hard

20 SQLite programs using Python’s built-in sqlite3 module: creating tables, inserting with parameters, querying, updating, deleting, joins, aggregates, transactions and exporting to CSV. Most use an in-memory database so they run anywhere.

Before you start

Read the SQLite lesson first if the topic is new to you.

All programs

Export a table to CSV

Python Practice › SQLite Programs › Program 18

Export a table to CSV

EasySQLite Programs · 18 of 20

Write a Python program to export a table to a CSV file.

Output
name,marks
Asha,91
Ravi,74

Approach

  1. Read rows and column names, then use csv.writer.

Solution

Python
import csvimport sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (name TEXT, marks INTEGER)")conn.executemany("INSERT INTO students VALUES (?, ?)", [("Asha", 91), ("Ravi", 74)])cur = conn.execute("SELECT * FROM students")with open("students.csv", "w", newline="") as f:    writer = csv.writer(f)    writer.writerow([c[0] for c in cur.description])    writer.writerows(cur)print(open("students.csv").read())
Output
name,marks
Asha,91
Ravi,74

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Why parameters prevent SQL injection

Python Practice › SQLite Programs › Program 19

Why parameters prevent SQL injection

EasySQLite Programs · 19 of 20

Write a Python program that shows how an f-string query is unsafe and a parameter is safe.

Output
unsafe query returned: [('asha',), ('ravi',)]
safe query returned: []

Approach

  1. Use a malicious input with both styles.

Solution

Python
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE users (name TEXT, secret TEXT)")conn.executemany("INSERT INTO users VALUES (?, ?)", [("asha", "s1"), ("ravi", "s2")]) user_input = "nobody' OR '1'='1"unsafe = conn.execute(f"SELECT name FROM users WHERE name = '{user_input}'").fetchall()safe = conn.execute("SELECT name FROM users WHERE name = ?", (user_input,)).fetchall()print("unsafe query returned:", unsafe)print("safe query returned:", safe)
Output
unsafe query returned: [('asha',), ('ravi',)]
safe query returned: []

Line by line

Line 7

The input closes the quote and adds OR '1'='1, so the unsafe query returns every user.

Line 8

With a parameter the whole input is treated as a name, which matches nobody.

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Search with LIKE

Python Practice › SQLite Programs › Program 16

Search with LIKE

EasySQLite Programs · 16 of 20

Write a Python program to find products whose name contains a word.

Output
[('USB cable',), ('USB hub',)]

Approach

  1. LIKE '%' || ? || '%' keeps the value as a parameter.

Solution

Python
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE products (name TEXT)")conn.executemany("INSERT INTO products VALUES (?)", [("USB cable",), ("Wireless mouse",), ("USB hub",), ("Keyboard",)])term = "usb"print(conn.execute("SELECT name FROM products WHERE name LIKE '%' || ? || '%'", (term,)).fetchall())
Output
[('USB cable',), ('USB hub',)]

Line by line

Line 6

SQLite’s LIKE ignores case for English letters.

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Top N rows

Python Practice › SQLite Programs › Program 17

Top N rows

EasySQLite Programs · 17 of 20

Write a Python program to get the top 3 scores.

Output
[('Gill', 90), ('Virat', 82), ('Rahul', 61)]

Approach

  1. ORDER BY ... DESC LIMIT 3.

Solution

Python
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE scores (player TEXT, runs INTEGER)")conn.executemany("INSERT INTO scores VALUES (?, ?)", [("Virat", 82), ("Rohit", 45), ("Gill", 90), ("Rahul", 61)])print(conn.execute("SELECT player, runs FROM scores ORDER BY runs DESC LIMIT 3").fetchall())
Output
[('Gill', 90), ('Virat', 82), ('Rahul', 61)]

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs