The one-line mental model
A good Spark test suite is a small, fast, deterministic local session plus assertions on data rather than on implementation, with the expensive end-to-end paths kept few and scheduled separately from the fast feedback loop.
You will be able to structure fixtures that are reused instead of rebuilt, compare DataFrames without ordering flakiness, test a full read-transform-write cycle in a temporary directory, encode data quality rules as executable checks, and decide what runs on every commit versus nightly.
Prerequisites
- !PySpark DataFrame transformations and actions
- !pytest fixtures, parametrisation and mocking basics
What You'll Learn
- 1Design session and test fixtures that minimise JVM spin-up cost
- 2Assert on schema, values and partitioning reliably
- 3Write isolated integration tests using temporary storage
- 4Split fast unit tests from slow nightly data quality suites
Why Spark tests are slow, and what that costs you
The first obstacle is not your assertions, it is the JVM. Every Spark session takes seconds to start, allocates shuffle files and opens sockets, and if each test function builds its own, a suite with two hundred cases will take long enough that engineers stop running it locally. The second obstacle is nondeterminism: unordered results, floating point drift, partition-dependent row order and generated data make tests that pass on one machine fail on another. The third is side effects, because a test that writes to a shared path or a real cluster can leave state that breaks the next run.
Each obstacle has a specific antidote. Share one session across the whole module and only stop it when the suite ends, so construction cost is paid once. Assert on sets, counts and aggregates rather than on list order, and use tolerance when comparing doubles. Write every file-backed test into a temporary directory created per test, and mock every network dependency. The reward is a suite that runs in tens of seconds, and speed is what makes coverage grow: teams with slow Spark tests tend to have a handful of smoke tests, while teams with fast ones assert on every transformation.
Session fixtures that get reused, not rebuilt
Fixtures are where Spark test suites are won or lost. Scope decides whether the JVM is created once per test, once per module, or once for the entire run, and the cheapest correct choice is almost always the largest scope your data isolation needs allow.
import pytest
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
@pytest.fixture(scope="session")
def spark():
session = SparkSession.builder \
.master("local[2]") \
.appName("unit-tests") \
.config("spark.ui.enabled", "false") \
.config("spark.sql.shuffle.partitions", "4") \
.config("spark.sql.adaptive.enabled", "false") \
.config("spark.driver.bindAddress", "127.0.0.1") \
.getOrCreate()
yield session
session.stop()
@pytest.fixture
def events(spark):
rows = [
("u1", "click", 100.0, "2026-03-01"),
("u2", "view", 0.0, "2026-03-01"),
("u1", "purchase", 250.0, "2026-03-02"),
("u3", "click", 100.0, "2026-03-02"),
(None, "click", 100.0, "2026-03-02"),
]
return spark.createDataFrame(
rows, ["user_id", "event_type", "amount", "event_date"]
)
def test_total_spend_excludes_null_users(events):
from my_module import total_spend
result = total_spend(events)
assert result == 350.0
A few configuration choices matter more than they look. Disabling the UI removes a background thread and a port binding. Setting shuffle partitions to a small number stops a four-row DataFrame from spawning two hundred tasks, which is the single biggest source of local test slowness. Disabling adaptive execution keeps plan behaviour predictable across Spark versions. And binding the driver to loopback avoids the mysterious hangs that appear when a test cluster tries to resolve a hostname in a container network.
Asserting on DataFrames without flaky comparisons
The naive assertion compares collect() output to a list, which breaks the moment partitioning changes row order. PySpark ships purpose-built helpers that compare content and schema together, and they should be your default.
from pyspark.testing import assertDataFrameEqual
from pyspark.sql import functions as F
def test_upper_case_transform(spark):
from my_module import add_upper
source = spark.createDataFrame([(1, "ada"), (2, "grace")], ["id", "name"])
actual = add_upper(source)
expected = spark.createDataFrame([(1, "ADA", "a"), (2, "GRACE", "g")],
["id", "name_upper", "initial"])
assertDataFrameEqual(actual, expected)
def test_schema_is_stable(spark):
from my_module import enrich
df = spark.createDataFrame([(1,)], ["id"])
out = enrich(df)
assert out.schema.fieldNames() == ["id", "enriched", "batch_date"]
assert out.schema["id"].dataType.simpleString() == "bigint"
def test_null_handling_is_explicit(spark):
from my_module import process
df = spark.createDataFrame([(1, None), (2, "ok")], ["id", "value"])
out = process(df)
assert out.filter(F.col("value").isNull()).count() == 0
assert out.count() == 2
def test_partitioning_after_repartition(spark):
from my_module import bucketed
df = spark.range(10_000)
out = bucketed(df, parts=8)
assert out.rdd.getNumPartitions() == 8
Use schema assertions deliberately rather than always: an exact schema check catches an accidental rename that silently breaks downstream consumers, but it also makes harmless refactors noisy. A good rule is to assert the schema on public entry points and the values everywhere. When a transformation is order-insensitive, compare sorted rows or aggregated totals; when it is order-sensitive, such as a ranking, sort explicitly inside the test instead of hoping the implementation preserves order.
Integration tests: temp paths, real files, no shared cluster
Integration tests exercise the whole read-transform-write cycle. The mistake is running them against a shared directory or an external service, which introduces ordering dependencies between tests and makes failures impossible to reproduce.
import os
import tempfile
from unittest.mock import Mock, patch
def test_pipeline_end_to_end(spark):
from my_module import run_pipeline
with tempfile.TemporaryDirectory() as tmp:
src = os.path.join(tmp, "in")
dst = os.path.join(tmp, "out")
spark.createDataFrame(
[(1, "a", 100.0), (2, "b", 200.0)],
["id", "category", "amount"],
).write.mode("overwrite").parquet(src)
run_pipeline(spark, src, dst)
result = spark.read.parquet(dst)
assert result.count() == 2
assert "processed_amount" in result.columns
assert result.filter(F.col("processed_amount") < 0).count() == 0
def test_external_api_is_mocked(spark):
from my_module import enrich_from_api
client = Mock()
client.lookup.return_value = {"tier": "gold"}
df = spark.createDataFrame([(1, "u1")], ["id", "user_id"])
with patch("my_module.api_client", client):
out = enrich_from_api(df)
assert client.lookup.call_count == out.count()
assert out.filter(F.col("tier") == "gold").count() == out.count()
Two details make these reliable. Writing with an explicit mode("overwrite") prevents leftover files from a previous run from inflating counts, and reading back from the same temporary directory proves the sink contract as well as the transformation. For external systems, mock at the module boundary rather than deep inside a client, so a refactor of the client library does not silently turn your test into a real network call against a production endpoint.
Encoding data quality rules as tests
Data quality assertions catch what unit tests miss, because they describe invariants over the data rather than behaviour of a function. Null checks on required columns, range checks on amounts, referential checks against dimension tables and enum membership checks on categorical fields all translate directly into pytest cases, and they fail the same pipeline that would otherwise load corrupt rows downstream.
def test_required_columns_have_no_nulls(spark, events):
for col in ["user_id", "event_type", "amount"]:
bad = events.filter(F.col(col).isNull()).count()
assert bad == 0, f"{col} contains {bad} nulls"
def test_amounts_are_within_expected_range(events):
assert events.filter((F.col("amount") < 0) | (F.col("amount") > 1_000_000)).count() == 0
def test_event_types_are_from_the_known_domain(events):
allowed = {"click", "view", "purchase"}
observed = {r[0] for r in events.select("event_type").distinct().collect()}
assert observed.issubset(allowed), f"unexpected types: {observed - allowed}"
def test_referential_integrity(spark, orders, customers):
orphans = orders.join(customers, "customer_id", "left_anti")
assert orphans.count() == 0, f"found {orphans.count()} orphan orders"
Notice that every assertion carries a message describing the violation. A bare assert x == 0 tells whoever is paged that something failed; it does not tell them which column, how many rows, or whether the fix is a bad pipeline or a bad upstream feed.
What runs on every commit, and what does not
Speed decides placement. Tests that finish in under a minute belong in the pre-commit and pull request path, because they are the ones developers will actually run. Anything requiring a cluster, a large fixture or an external system belongs in a scheduled job with alerting, because its value comes from consistency rather than from feedback speed.
| Suite | Scope | Runtime target | Trigger |
|---|---|---|---|
| Unit | Pure transformations on tiny DataFrames | Under 30 seconds | Every commit |
| Schema and contract | Public entry points, output schemas | Under 1 minute | Every pull request |
| Integration | Read and write against temp storage | 2 to 5 minutes | Pull request |
| Data quality | Invariants over a recent production sample | 10 to 30 minutes | Nightly |
| Performance | Runtime and shuffle volume thresholds | 30 minutes plus | Weekly or on demand |
Whichever tier you are in, treat a flaky test as a defect of equal priority to a product bug. Quarantining flaky tests quietly trains everyone to ignore red builds, and the suite loses its only real asset, which is trust.
The CI configuration itself is part of the test design. Pin the Spark and PySpark versions to exactly what production runs, so a test never passes against a version the cluster does not have. Cache the local Maven and Ivy directories between runs, otherwise every job re-downloads dependencies and dominates the pipeline duration. Cap parallelism inside the suite so two hundred tests do not open two hundred concurrent local sessions on a four-core runner. Finally, upload the Spark UI output and any collected diagnostics as build artefacts on failure, because the plan and stage information from a failing run is often enough to explain the assertion without reproducing it locally.
Common Mistakes
Creating a new SparkSession inside every test function
Fix: Use a session-scoped fixture so the JVM starts once and is reused by the whole module
Comparing collect() output to a literal list
Fix: Sort explicitly or use assertDataFrameEqual so partition order cannot break the test
Running integration tests against a shared output directory
Fix: Write to a temporary directory per test and set an explicit overwrite mode
Asserting without context
Fix: Attach a message naming the column, count and violated rule so failures are diagnosable
Best Practices
- Keep shuffle partitions and adaptive execution settings tuned for tiny local data
- Test the smallest useful dataset first, then add one larger fixture only where needed
- Mock every network dependency at the module boundary
- Promote data quality invariants into the same suite as transformation tests
- Fail the build on schema changes at public entry points rather than discovering them in production
Interview Questions
Q1: How would you test a Structured Streaming query?
Use a memory or file source with a fixed clock, run with a short trigger or availableNow, then assert on the sink contents, including late-arrival cases driven by manual clock advancement.
Q2: Why disable adaptive query execution in tests?
It makes planning dependent on runtime statistics, so plans vary between runs; tests benefit from deterministic plans and stable partition counts.
Q3: What makes a Spark test flaky and how do you remove it?
Order dependence, shared state, timing assumptions and unseeded randomness; fix by isolating data, sorting before comparison, seeding generators and asserting on properties instead of exact floats.
Q4: Where do you test UDFs differently from built-in functions?
Test UDFs on nulls, empty inputs and type boundaries separately, because they bypass Catalyst optimisations and can fail where an equivalent built-in expression would not.
Key Takeaways
- Reuse one local session and tune shuffle settings so suites stay fast
- Compare DataFrames by content and schema, never by incidental row order
- Isolate file-backed tests in temporary directories with explicit write modes
- Encode data quality invariants as tests with descriptive failure messages
- Split fast pull request tests from slow scheduled suites, and treat flakiness as a bug