pytest for data pipelines: fixtures and parametrize
Data Quality Automation with Python · 7 questions
Short notes
Key idea
Fixtures give tests their data (loaded once with scope="session", shared via conftest.py); parametrize turns one test into many reported cases. Test the transformation code on tiny hand-made inputs full of edge cases, and keep known bugs visible with xfail(strict=True).
Syntax
# conftest.py
@pytest.fixture(scope="session")
def dw_orders():
return pd.read_csv("data/dw_orders.csv")
# test_quality.py
@pytest.mark.parametrize("column", ["order_id", "payment_method", "amount"])
def test_no_missing_values(dw_orders, column):
missing = dw_orders.loc[dw_orders[column].isna(), "order_id"].tolist()
assert not missing, f"{column} missing for {missing}"
@pytest.mark.xfail(reason="BUG-102: duplicates", strict=True)
def test_no_duplicates(dw_orders): ...
Example
The shop suite gives 2 failed, 16 passed, 1 xfailed: payment_method missing for order 56, orphans for customers 7, 23 and 38, and the known duplicate bug tracked as XFAIL.
Traps
- Calling fixtures instead of asking for them.
- Modifying a session-scoped DataFrame.
- Loops instead of parametrize hide failures.
round(100.005, 2)gives 100.0: decide the rounding rule.skipfor known bugs; use strict xfail.
Want the full lesson with step-by-step examples, a project and a certificate? Data Quality Automation with Python course, ₹120 →
- Question 1easy
A fixture is defined as
def dw_orders(): .... How does a test get its value? - Question 2medium
A session-scoped fixture returns dw_orders. One test drops rows from it in place. What happens?
- Question 3easy
Where do you put fixtures that several test files use?
- Question 4medium
@pytest.mark.parametrize("column", REQUIRED)decorates one test. How many tests does pytest report?REQUIRED = ["order_key", "order_id", "customer_id", "order_date", "status_group", "payment_method", "amount"] print(len(REQUIRED))
- Question 5hard
What does this print?
print(round(100.005, 2))
pytest for data pipelines: fixtures and parametrize
pytest for data pipelines: fixtures and parametrize
pytest for data pipelines: fixtures and parametrize
pytest for data pipelines: fixtures and parametrize
pytest for data pipelines: fixtures and parametrize
2 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.