Sub topic 5
Writing unit tests for PySpark transformations
This chapter assumes you know basic pytest, PySpark DataFrames, and the project layout and spark fixture from the earlier chapters. You will write unit tests for a pure transformation and learn the errors that most often break them.
The shape of a unit test
A unit test for a transformation has three steps:
- Build a small input DataFrame by hand.
- Build the DataFrame you expect.
- Call the function and compare the result with the expected DataFrame.
The function under test takes a DataFrame and returns a DataFrame. It does no reads or writes, so the test needs no tables or files.
from pyspark.sql import DataFrame, functions as F
def add_order_total(df: DataFrame) -> DataFrame:
"""Add a total column computed from quantity and unit price."""
return df.withColumn("total", F.col("quantity") * F.col("unit_price"))The test uses the shared spark fixture. It uses assertDataFrameEqual from pyspark.testing, which is available in PySpark 3.5 and later.
from pyspark.testing import assertDataFrameEqual
from my_project.transforms import add_order_total
def test_add_order_total(spark):
source = spark.createDataFrame(
[(1, 2, 5.0), (2, 3, 1.5)],
["order_id", "quantity", "unit_price"],
)
expected = spark.createDataFrame(
[(1, 2, 5.0, 10.0), (2, 3, 1.5, 4.5)],
["order_id", "quantity", "unit_price", "total"],
)
assertDataFrameEqual(add_order_total(source), expected)Run it with pytest tests/unit. The first run is slow because the fixture starts a local Spark session. Later tests in the same run reuse that session.
What the comparison checks
assertDataFrameEqual compares the schema and the rows. By default it ignores row order, because Spark does not guarantee order. It fails if a column name or a column type differs. Pass checkRowOrder=True only when the transformation sorts its output and the order is part of the behavior.
For floating-point columns, the helper accepts tolerances through rtol and atol. Use them when a result comes from division or aggregation.
assertDataFrameEqual(actual, expected, rtol=1e-5)flowchart TDChoosing test cases
Small inputs are enough. Two or three rows cover the normal path. Add rows for the cases where bugs hide:
- Null values in each column the function reads.
- Empty input, to confirm the function returns an empty DataFrame with the right schema.
- Duplicate keys, if the function joins or aggregates.
- Boundary values, such as zero quantity or a date at the edge of a window.
Give each case its own test function with a descriptive name. A failing test named test_add_order_total_keeps_null_price_as_null tells you what broke before you open the file.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Schema mismatch on an int column | Python ints become `long` in Spark, while the expected side used another type | Pass an explicit schema to `createDataFrame` |
| `Can not infer schema for type: NoneType` | A column holds only `None` values | Pass an explicit schema |
| Test passes locally, fails in CI | Different PySpark or Java versions | Pin versions in `requirements-dev.txt` and install Java in CI |
| Each test takes seconds | The fixture is function-scoped | Use `scope="session"` |
An explicit schema removes most type surprises. Use a DDL string, which is short to write.
def test_empty_input_keeps_schema(spark):
schema = "order_id long, quantity long, unit_price double"
source = spark.createDataFrame([], schema)
result = add_order_total(source)
assert result.columns == ["order_id", "quantity", "unit_price", "total"]
assert result.count() == 0Keeping tests fast
Unit tests run on every pull request, so speed matters. Set local[2] in the fixture, as the previous chapter showed. You can also lower spark.sql.shuffle.partitions to 2 in the session builder. The default of 200 makes small joins and aggregations slow on a laptop or CI runner.
Exercise
A test compares a transformation result with an expected DataFrame, but the test fails with a type difference on a column of whole numbers, even though the values look identical. What is the most likely cause and the fix?
Show answer
The inferred types differ, for example long on one side and int or double on the other. Pass an explicit schema, such as a DDL string, to createDataFrame for both the input and the expected DataFrame.
Exercise
Why does assertDataFrameEqual pass when the rows are in a different order, and when would you turn that off?
Show answer
Spark does not guarantee row order, so the helper ignores it by default. Pass checkRowOrder=True only when the transformation explicitly sorts its output and the order is part of the behavior you want to protect.