Project layout
testproj/
βββ shopkart_jobs.py transformations (no reading/writing inside)
βββ tests/
βββ conftest.py the shared SparkSession fixture
βββ test_jobs.py the tests$pip install pyspark==4.0.1 pytest "pandas<3"$pytest -v
The code under test
Our first version of the jobs file. Can you spot the bug before the test does?
"""ShopKart transformations: plain functions that take and return DataFrames, so they're easy to test."""
from pyspark.sql import DataFrame, functions as F
def clean_orders(orders: DataFrame) -> DataFrame:
"""Drop broken rows, standardise status, add amount."""
return (orders
.dropna(subset=["order_id", "quantity"])
.withColumn("status", F.upper(F.trim("status")))
.withColumn("amount", F.col("quantity") * F.col("unit_price")))
def revenue_by_city(orders: DataFrame, customers: DataFrame) -> DataFrame:
"""Delivered revenue per city."""
return (orders
.join(customers, "customer_id")
.groupBy("city")
.agg(F.sum("amount").alias("revenue")))A SparkSession fixture
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark():
"""One small local Spark session shared by all tests (starting Spark is the slow part)."""
session = (SparkSession.builder.master("local[2]").appName("tests")
.config("spark.sql.shuffle.partitions", "2") # tiny data: no need for 200
.config("spark.ui.showConsoleProgress", "false")
.getOrCreate())
yield session
session.stop()The tests
from decimal import Decimal
from pyspark.testing import assertDataFrameEqual
from shopkart_jobs import clean_orders, revenue_by_city
ORDER_COLS = "order_id INT, customer_id INT, quantity INT, unit_price DECIMAL(10,2), status STRING"
def test_clean_orders_drops_broken_rows_and_fixes_status(spark):
raw = spark.createDataFrame(
[(1, 10, 2, Decimal("299.00"), " delivered "), (None, 11, None, Decimal("4999.00"), "DELIVERED")],
ORDER_COLS)
result = clean_orders(raw).select("order_id", "status", "amount")
expected = spark.createDataFrame([(1, "DELIVERED", Decimal("598.00"))], "order_id INT, status STRING, amount DECIMAL(21,2)")
assertDataFrameEqual(result, expected)
def test_revenue_by_city_counts_only_delivered(spark):
orders = clean_orders(spark.createDataFrame(
[(1, 10, 1, Decimal("1000.00"), "DELIVERED"),
(2, 10, 1, Decimal("5000.00"), "CANCELLED"), # must NOT count
(3, 20, 2, Decimal("500.00"), "DELIVERED")],
ORDER_COLS))
customers = spark.createDataFrame([(10, "Kolkata"), (20, "Pune")], "customer_id INT, city STRING")
expected = spark.createDataFrame(
[("Kolkata", Decimal("1000.00")), ("Pune", Decimal("1000.00"))], "city STRING, revenue DECIMAL(31,2)")
assertDataFrameEqual(revenue_by_city(orders, customers), expected) # row order doesn't matterpyspark.errors.exceptions.base.PySparkAssertionError: [DIFFERENT_ROWS] Results do not match: ( 50.00000 % )
*** actual ***
! Row(city='Kolkata', revenue=Decimal('6000.00'))
Row(city='Pune', revenue=Decimal('1000.00'))
*** expected ***
! Row(city='Kolkata', revenue=Decimal('1000.00'))
Row(city='Pune', revenue=Decimal('1000.00'))
1 failed, 1 passed, 1 warning in 17.92sThe first test passed. The second failed with a precise diff: Kolkata's revenue was βΉ6,000 instead of βΉ1,000. The function never filtered by status, so the cancelled βΉ5,000 order was counted: exactly the kind of bug that silently inflates a dashboard for months.
Fix and re-run
"""ShopKart transformations: plain functions that take and return DataFrames, so they're easy to test."""
from pyspark.sql import DataFrame, functions as F
def clean_orders(orders: DataFrame) -> DataFrame:
"""Drop broken rows, standardise status, add amount."""
return (orders
.dropna(subset=["order_id", "quantity"])
.withColumn("status", F.upper(F.trim("status")))
.withColumn("amount", F.col("quantity") * F.col("unit_price")))
def revenue_by_city(orders: DataFrame, customers: DataFrame) -> DataFrame:
"""Delivered revenue per city."""
return (orders
.filter(F.col("status") == "DELIVERED") # the fix: only delivered orders
.join(customers, "customer_id")
.groupBy("city")
.agg(F.sum("amount").alias("revenue")))tests/test_jobs.py::test_clean_orders_drops_broken_rows_and_fixes_status PASSED
tests/test_jobs.py::test_revenue_by_city_counts_only_delivered PASSED
========================= 2 passed, 1 warning in 7.15s =========================Testing tips
- Build tiny DataFrames with an explicit schema string, so types match what production produces (note the DECIMAL precisions Spark derives: 10,2 Γ INT β 21,2; SUM β 31,2).
- Test edge cases: nulls, duplicates, bad rows, empty input, ties in rankings.
- Keep I/O (read/write) out of the functions you test; test it separately or in an integration test.
- Run tests in CI on every pull request, with pinned versions.
π― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you unit test PySpark code?Fresher+
Q2How do you keep PySpark tests fast?1β3 yrs+
Q3What would you test in a production ETL job?3+ yrs+
Key takeaways
- βTestable PySpark starts with small, pure functions.
- βOne fixture, tiny DataFrames, assertDataFrameEqual.
- βOur test caught cancelled orders inflating revenue.
- βPin versions and run tests in CI.
Frequently asked questions
Do I need a cluster to test PySpark?
No. Tests run on a local SparkSession (local[2]) with tiny DataFrames you build in the test. They take seconds and run in CI like any Python tests.
What is assertDataFrameEqual?
A helper in pyspark.testing (Spark 3.5+) that compares two DataFrames: schema and rows, ignoring row order by default, and prints a clear diff of the rows that differ. Before it, people used chispa or collected rows manually.
Why share one SparkSession across tests?
Starting Spark takes several seconds. A session-scoped pytest fixture starts it once for the whole test run. Set spark.sql.shuffle.partitions low (2) so tiny tests don't create 200 partitions.
What should I test?
Your transformation logic: filters, joins, business rules, edge cases (nulls, duplicates, bad rows, empty input). Not Spark itself. Keep transformations as functions that take and return DataFrames, with reading and writing outside them.
π§ Quick check: testing PySpark
1. Best way to make PySpark code testable?
2. Our failing test showed Kolkata revenue 6000 instead of 1000 because...
3. assertDataFrameEqual by default...
4. Why scope='session' on the spark fixture?
Checking your accessβ¦