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(fromfunctools) 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'androw["id"]raisesKeyError.- A
runcolumn 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 11.45s ==============================
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 12.06s ========================
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
discountcolumn holds numbers (500), not text, because openpyxl reads real cell types. - Empty cells come back as
None. In this workbookNonemeans “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 10.76s ==============================
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.60s
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
- One loader module for the whole framework, so encoding, paths and skipping work the same everywhere.
- An
idcolumn in every file. Readable ids are the difference between “row 37 failed” and “save10-capped failed”. - Keep expected results in the data, next to the inputs.
- Never put real passwords or personal data in data files. Use test accounts, and read secrets from environment variables (next lesson).
- 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.
- 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 truthyEvery 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.
- Why build data paths with
Path(__file__).resolve().parent?Answer: The path then works no matter which folder pytest is started from. Relative paths depend on the current working directory; a path built from the loader’s own location does not. - What type does
csv.DictReaderreturn for a cell containing42?Answer:str. CSV has no types. Every value is a string until you convert it. - What does
encoding="utf-8-sig"fix when reading CSV files?Answer: The byte-order mark Excel adds at the start of “CSV UTF-8” files. The BOM would otherwise become part of the first header name, such as'id'. - In openpyxl, what does an empty cell return with
iter_rows(values_only=True)?Answer:None. openpyxl represents empty cells asNone. - What does
load_workbook(..., data_only=True)do?Answer: Returns stored calculated values of formula cells instead of formulas. Without it a formula cell returns its formula text, such as"=A2*2". - What is the benefit of decorating a loader with
functools.cache?Answer: The file is read once per session, however many tests use it. The cached result is reused for the same arguments, avoiding repeated disk reads and parsing. - A CSV column
runcontainsno. Why isif row["run"]:wrong?Answer: Any non-empty string, including"no", is truthy. Compare text explicitly, for examplerow["run"].strip().lower() == "yes". - Which format keeps nested data and real types such as booleans and null?Answer: JSON. JSON supports objects, arrays, numbers, booleans and null; CSV is flat text.
- Why validate data rows at collection time with a dataclass?Answer: Broken rows fail immediately with a clear message, before any browser starts. A typo in a key is reported in milliseconds with the row name instead of as a confusing browser failure.
- Which is the best place for a real production password used by tests?Answer: An environment variable or a secret store, never a data file. Data files are committed and shared; secrets belong in environment variables or CI secrets (next lesson).
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 useutf-8-sigfor CSV from Excel. - CSV values are strings; openpyxl returns real types and
Nonefor empty cells. - Turn rows into
pytest.paramwith ids from anidcolumn, and let aruncolumn 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