Testing PySpark Transformations Locally
Unit-test the DataFrame functions of the trips pipeline with pytest: one local SparkSession shared through a session-scoped fixture, small hand-built inputs with explicit schemas, order-insensitive comparisons with assertDataFrameEqual, schema checks with assertSchemaEqual, and two tests that fail for real before you fix them.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Share one SparkSession through a fixture
- Step 2: See what assertDataFrameEqual compares
- Step 3: Test the cleaning and deduplication functions
- Step 4: A test that depends on row order
- Step 5: Compare without order, and check the schema
- Step 6: Write a test first, and watch it fail
- Step 7: Run the suite and see where the time goes
- Check your understanding
- Apply it
- Review prompt
Lessons of Batch Processing with Spark
- From Clusters to Stages: How Spark Runs Your Code Concept · 25 min
- Lab: Read, Transform and Write with DataFrames Lab · 30 min
- Joins and Aggregations at Scale, Shuffle by Shuffle Worked example · 25 min
- Lab: Using the Spark UI to Fix a Slow Job Lab · 30 min
- Testing PySpark Transformations Locally Lab · 20 min
- Check: Plans, Shuffles and Tuning Knowledge check · 8 questions
What you will learn
- Unit-test PySpark transformation functions on small local DataFrames.
Prerequisites: Python Foundations
01. Goal and setup
A Spark job that runs for an hour on a cluster is a poor place to find out that a filter drops the wrong rows. The transformation functions in pipeline.py from the lab in lesson 2 take DataFrames and return a DataFrame, with no reads or writes inside. That shape makes them easy to test: you build three or four rows by hand, call the function, and compare the result with the rows you expect. Local mode runs the same Spark engine as a cluster, so a test on four rows checks the same plan logic, including joins and shuffles.
In this lab you add a pytest suite to spark-lab/. You share one SparkSession across all tests, compare results in ways that do not depend on row order, check a schema, and write two tests that fail for real reasons before you fix them. It was tested with PySpark 4.3.0, pytest 9.2.0, Python 3.12 and Temurin JRE 21.0.12.1. You need pipeline.py from lesson 2 and the venv with pytest. If pytest itself is new to you, read Type Hints and Testing with pytest first.
spark-lab/
├── pytest.ini step 1: test settings
├── try_asserts.py step 2: what assertDataFrameEqual compares
├── metrics.py step 6: a new function, written test-first
└── tests/
├── conftest.py step 1: the SparkSession fixture and shared inputs
├── test_pipeline.py step 3: clean_trips and latest_zones
├── test_daily.py steps 4 and 5: daily_zone_metrics
└── test_fare.py step 6: add_fare_per_km02. Step 1: Share one SparkSession through a fixture
Starting a SparkSession starts a Java process, which takes several seconds. A pytest fixture is a function that prepares something a test needs; a test receives it by naming it as a parameter. With scope="session", pytest calls the fixture once for the whole run and gives every test the same object, and the code after yield stops Spark at the end.
The session uses local[2]: two task slots are enough to run real shuffles, and they catch code that only works with one partition. spark.sql.shuffle.partitions drops from 200 to 2, because 200 tasks for four rows would spend most of the test on scheduling. The UI is off, because no one looks at it during a test run. The second fixture, daily_inputs, builds the input of step 4; it has the default function scope, so every test gets fresh DataFrames, but it reuses the shared session.
pytest.ini puts spark-lab/ on the import path, so tests can import pipeline, and asks for short tracebacks without the captured Spark logs.
[pytest]
pythonpath = .
testpaths = tests
addopts = --tb=short --show-capture=noimport datetime as dt
from decimal import Decimal
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark():
"""One local SparkSession for the whole test run: starting the JVM is slow."""
session = (
SparkSession.builder.master("local[2]")
.appName("pipeline-tests")
.config("spark.sql.shuffle.partitions", "2") # tiny data, few partitions
.config("spark.sql.session.timeZone", "UTC")
.config("spark.ui.enabled", "false")
.config("spark.ui.showConsoleProgress", "false")
.config("spark.driver.host", "127.0.0.1")
.config("spark.driver.bindAddress", "127.0.0.1")
.getOrCreate()
)
yield session
session.stop()
@pytest.fixture
def daily_inputs(spark):
"""Four clean trips on one day, and two zones; zone 13 has no zone row."""
day = dt.date(2026, 3, 1)
trips = spark.createDataFrame(
[
(1, 1, 2.0, Decimal("7.50"), day),
(2, 1, 4.0, Decimal("10.50"), day),
(3, 3, 3.0, Decimal("9.00"), day),
(4, 13, 1.0, Decimal("4.80"), day),
],
"trip_id long, pickup_zone_id int, distance_km double,"
" fare decimal(8,2), pickup_date date",
)
zones = spark.createDataFrame(
[(1, "Airport", "East"), (3, "Harbour", None)], # Harbour: no borough yet
"zone_id int, zone_name string, borough string",
)
return trips, zones03. Step 2: See what assertDataFrameEqual compares
assertDataFrameEqual from pyspark.testing compares two DataFrames, or a DataFrame and a list of Row objects. Before you rely on it, check its defaults on two rows that hold the same values in a different order, with a float that differs in the seventh decimal and a None on both sides.
from pyspark.sql import Row
from pyspark.testing import assertDataFrameEqual
from session import local_session
spark = local_session("try-asserts", cores=2)
actual = spark.createDataFrame(
[(2, 3.0000001, None), (1, 1.5, "late")], "trip_id int, km double, note string"
)
expected = [Row(trip_id=1, km=1.5, note="late"), Row(trip_id=2, km=3.0, note=None)]
print("collect() == expected:", actual.collect() == expected)
assertDataFrameEqual(actual, expected)
print("assertDataFrameEqual: no error")
try:
assertDataFrameEqual(actual, expected, checkRowOrder=True)
except AssertionError as error:
print("with checkRowOrder=True:", str(error).splitlines()[0])
spark.stop()python try_asserts.pycollect() == expected: False
assertDataFrameEqual: no error
with checkRowOrder=True: [DIFFERENT_ROWS] Results do not match: ( 100.00000 % )A plain == on collected rows fails on the order alone. assertDataFrameEqual ignores row order, compares floats with a relative tolerance of 1e-5 (rtol), and treats two None values as equal, which SQL's = does not. checkRowOrder=True turns the order check on; the error code [DIFFERENT_ROWS] and the share of rows that differ come first, followed by both row lists with the differing rows marked by !.
04. Step 3: Test the cleaning and deduplication functions
Each test builds its input with createDataFrame and an explicit schema string. Do not let Spark infer types from Python values: an inferred 7.5 becomes a double, while the trips table stores fares as decimal(8,2), and sums and divisions behave differently for the two. Choose rows that each test one rule: a trip at 23:59 checks the date conversion, one row has no distance and one has no fare. The expected zones list zone 8 before zone 7, and the test still passes.
import datetime as dt
from decimal import Decimal
from pyspark.testing import assertDataFrameEqual
from pipeline import clean_trips, latest_zones
TRIPS = (
"trip_id long, pickup_ts timestamp, pickup_zone_id int,"
" distance_km double, fare decimal(8,2)"
)
def ts(text):
return dt.datetime.fromisoformat(text)
def test_clean_trips_drops_bad_rows_and_adds_the_date(spark):
trips = spark.createDataFrame(
[
(1, ts("2026-03-01 23:59:00"), 1, 2.0, Decimal("7.50")),
(2, ts("2026-03-02 00:01:00"), 1, 0.0, Decimal("3.00")), # no distance
(3, ts("2026-03-02 08:00:00"), 2, 5.0, None), # no fare
],
TRIPS,
)
expected = spark.createDataFrame(
[(1, ts("2026-03-01 23:59:00"), 1, 2.0, Decimal("7.50"), dt.date(2026, 3, 1))],
TRIPS + ", pickup_date date",
)
assertDataFrameEqual(clean_trips(trips), expected)
def test_latest_zones_keeps_the_newest_row_per_zone(spark):
zones = spark.createDataFrame(
[
(7, "Riverside", "South", dt.date(2025, 1, 1)),
(7, "Riverside Park", "South", dt.date(2026, 2, 15)),
(8, "Hillside", "North", dt.date(2025, 1, 1)),
],
"zone_id int, zone_name string, borough string, updated_on date",
)
expected = spark.createDataFrame(
[(8, "Hillside", "North"), (7, "Riverside Park", "South")],
"zone_id int, zone_name string, borough string",
)
assertDataFrameEqual(latest_zones(zones), expected)python -m pytest -q tests/test_pipeline.pyUse python -m pytest, so that the venv's Python runs the tests. The result will match; the time includes the start of Java and will differ on your machine.
.. [100%]
2 passed in 21.01s05. Step 4: A test that depends on row order
Now test daily_zone_metrics. The daily_inputs fixture has four trips: two in zone 1, one in zone 3, whose borough is missing, and one in zone 13, which has no zone row. Start with the most natural test: collect the rows and compare the trip counts with a list in zone order.
from pipeline import daily_zone_metrics
def test_trips_per_zone(daily_inputs):
rows = daily_zone_metrics(*daily_inputs).collect()
# expected order: Airport, Harbour, Unknown
assert [row.trips for row in rows] == [2, 1, 1]python -m pytest -q tests/test_daily.pyF [100%]
=================================== FAILURES ===================================
_____________________________ test_trips_per_zone ______________________________
tests/test_daily.py:7: in test_trips_per_zone
assert [row.trips for row in rows] == [2, 1, 1]
E assert [1, 1, 2] == [2, 1, 1]
E
E At index 0 diff: 1 != 2
E Use -v to get more diff
=========================== short test summary info ============================
FAILED tests/test_daily.py::test_trips_per_zone - assert [1, 1, 2] == [2, 1, 1]
1 failed in 29.02sThe counts are right, but not in the order of the list. A DataFrame has no row order unless the last step of its plan is a sort. These rows come out of a shuffle in the order of their hash partitions, so Airport, with 2 trips, came last. That order can change with the number of partitions, the Spark version or the data, which is why such tests pass on one laptop and fail in CI. Do not add orderBy to the function under test: that adds a sort that production does not need.
06. Step 5: Compare without order, and check the schema
Replace the file with the version below. The first test puts the counts in a dictionary keyed by zone name, which has no order. The second compares full Row objects with assertDataFrameEqual. The third checks the schema with assertSchemaEqual: trips must be a long and revenue a decimal(18,2), the type Spark's sum gives a decimal(8,2) column (10 more digits of precision). A downstream table that expects those types breaks if they change, and this test tells you first. By default assertSchemaEqual ignores nullability.
import datetime as dt
from decimal import Decimal
from pyspark.sql import Row
from pyspark.testing import assertDataFrameEqual, assertSchemaEqual
from pipeline import daily_zone_metrics
DAY = dt.date(2026, 3, 1)
def test_trips_per_zone(daily_inputs):
rows = daily_zone_metrics(*daily_inputs).collect()
trips = {row.zone_name: row.trips for row in rows}
assert trips == {"Airport": 2, "Harbour": 1, "Unknown": 1}
def test_daily_metrics_rows(daily_inputs):
expected = [
Row(pickup_date=DAY, borough="East", zone_name="Airport",
trips=2, revenue=Decimal("18.00"), avg_km=3.0),
Row(pickup_date=DAY, borough="Unknown", zone_name="Harbour",
trips=1, revenue=Decimal("9.00"), avg_km=3.0),
Row(pickup_date=DAY, borough="Unknown", zone_name="Unknown",
trips=1, revenue=Decimal("4.80"), avg_km=1.0),
]
assertDataFrameEqual(daily_zone_metrics(*daily_inputs), expected)
def test_daily_metrics_schema(spark, daily_inputs):
expected = spark.createDataFrame(
[],
"pickup_date date, borough string, zone_name string,"
" trips long, revenue decimal(18,2), avg_km double",
).schema
assertSchemaEqual(daily_zone_metrics(*daily_inputs).schema, expected)python -m pytest -q tests/test_daily.py... [100%]
3 passed in 22.02sAll three pass. The Harbour row checks the null handling: its borough was None, and daily_zone_metrics replaced it with Unknown.
07. Step 6: Write a test first, and watch it fail
The analysts want the fare per kilometre. Trips with a distance of 0 should get NULL, not a crash, because the cleaning step is not always run first. Write the function the obvious way and the test that states the rule.
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
def add_fare_per_km(trips: DataFrame) -> DataFrame:
"""Fare divided by distance, rounded to cents."""
fare_per_km = F.col("fare") / F.col("distance_km")
return trips.withColumn("fare_per_km", F.round(fare_per_km, 2))from decimal import Decimal
from pyspark.testing import assertDataFrameEqual
from metrics import add_fare_per_km
def test_fare_per_km_is_null_when_distance_is_zero(spark):
trips = spark.createDataFrame(
[(1, 2.0, Decimal("7.50")), (2, 0.0, Decimal("3.00")), (3, 3.0, None)],
"trip_id long, distance_km double, fare decimal(8,2)",
)
expected = spark.createDataFrame(
[(1, 3.75), (2, None), (3, None)], "trip_id long, fare_per_km double"
)
result = add_fare_per_km(trips).select("trip_id", "fare_per_km")
assertDataFrameEqual(result, expected)python -m pytest -q tests/test_fare.pyYour paths will differ, and the long error line is wrapped here.
F [100%]
=================================== FAILURES ===================================
________________ test_fare_per_km_is_null_when_distance_is_zero ________________
tests/test_fare.py:17: in test_fare_per_km_is_null_when_distance_is_zero
assertDataFrameEqual(result, expected)
.venv/lib/python3.12/site-packages/pyspark/sql/classic/dataframe.py:504: in collect
sock_info = self._jdf.collectToPython()
^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.12/site-packages/py4j/java_gateway.py:1362: in __call__
return_value = get_return_value(
.venv/lib/python3.12/site-packages/pyspark/errors/exceptions/captured.py:262: in deco
raise converted from None
E pyspark.errors.exceptions.captured.ArithmeticException: [DIVIDE_BY_ZERO] Division by
E zero. Use `try_divide` to tolerate divisor being 0 and return NULL instead. If
E necessary set "spark.sql.ansi.enabled" to "false" to bypass this error. SQLSTATE:
E 22012
E == DataFrame ==
E "__truediv__" was called from
E /home/you/spark-lab/metrics.py:7
=========================== short test summary info ============================
FAILED tests/test_fare.py::test_fare_per_km_is_null_when_distance_is_zero - p...
1 failed in 19.07sThe test did not fail on the comparison; the query failed. Spark 4 turns on ANSI SQL mode by default (spark.sql.ansi.enabled), so dividing by zero raises [DIVIDE_BY_ZERO] instead of returning NULL, as Spark 3 did. The error only appears when an action runs, here inside the assertion, which is another reason to test with rows that hit the edge cases. Do not turn ANSI mode off to make the test pass: it also catches overflow and invalid casts. Use try_divide, which returns NULL when the divisor is 0. A null fare already gives a null result.
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
def add_fare_per_km(trips: DataFrame) -> DataFrame:
"""Fare divided by distance, rounded to cents; NULL when the distance is 0."""
fare_per_km = F.try_divide(F.col("fare"), F.col("distance_km"))
return trips.withColumn("fare_per_km", F.round(fare_per_km, 2))python -m pytest -q tests/test_fare.py. [100%]
1 passed in 15.28s08. Step 7: Run the suite and see where the time goes
Run all six tests and ask pytest for the three slowest steps.
python -m pytest -q --durations=3...... [100%]
============================= slowest 3 durations ==============================
12.98s setup tests/test_daily.py::test_trips_per_zone
5.70s call tests/test_daily.py::test_trips_per_zone
1.15s call tests/test_daily.py::test_daily_metrics_rows
6 passed in 24.36sThe largest item is the setup of the first test: the session fixture starting Spark. The first test's call is slower too, because Spark warms up on first use; later tests take about a second each. With a function-scoped fixture, every test would pay the start-up cost again. Keep the suite fast as it grows: tiny inputs, few shuffle partitions, one session, and no reads from shared storage; a test that needs a real file can write one into pytest's tmp_path.
Unit tests check the logic of each function. They do not replace checks on the real data, such as row counts after a join or a unique key, which data quality checks cover.
09. Check your understanding
10. Apply it
The practice project asks for pytest tests for each transformation function. Extend this suite towards it:
- Add a test for
clean_tripswith a negative distance, decide whether it should be dropped, and change the function if the test says so. - Add a test for
latest_zoneswhere two rows of one zone have the sameupdated_on, and decide how the function should break the tie. - Write a test for your project's daily metrics function that checks the schema with
assertSchemaEqualand the rows withassertDataFrameEqual. - Run the suite in CI with the same
pytest.ini, and note how long the fixture takes to start there.
11. Review prompt
Without looking back, explain in your own words:
- why the
sparkfixture has session scope, and why the session useslocal[2]and two shuffle partitions; - why
collect() == [...]failed although every value was right; - three things
assertDataFrameEqualdoes by default that a plain==does not; - why the fare test failed with an error rather than an assertion, and how
try_dividefixed it.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.