Sub topic 3
Separating transformation logic from I/O
This chapter assumes you know PySpark DataFrames, basic pytest, and how a Databricks notebook reads and writes tables. By the end you will be able to split a job into a pure transformation and a thin I/O layer, so tests can call the transformation directly.
Why the split matters
A common notebook reads a table, transforms it, and writes the result in one cell sequence. To test that code you need the source table, write access to the target, and a cluster. A failing test then tells you little about which step broke.
If the transformation takes a DataFrame and returns a DataFrame, a test can build a small input in memory and check the output. No tables, no cluster, no side effects.
A pure transformation
This function has no reads or writes. Its output depends only on its input.
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"))Three habits keep functions testable:
- Take DataFrames and plain parameters as arguments. Do not call
spark.table()orspark.readinside the function. - Return a new DataFrame. Do not write to a table, call
display(), or mutate global state. - Pass configuration, such as a threshold or a column name, as an argument instead of reading it from a widget or an environment variable inside the function.
Keeping I/O at the edge
The I/O code sits in a small entry-point function that reads, calls the transformations, and writes. It holds no business logic, so there is little in it that can break.
A job entry point for the function above might look like this:
from pyspark.sql import SparkSession
from my_project.transforms import add_order_total
def run(spark: SparkSession, source: str, target: str) -> None:
df = spark.read.table(source)
result = add_order_total(df)
result.write.mode("overwrite").saveAsTable(target)
if __name__ == "__main__":
spark = SparkSession.builder.getOrCreate()
run(spark, "dev.sales.orders", "dev.sales.orders_enriched")The table names are parameters of run, so a staging or production job can pass different names without changing the code. The bundle configuration in later chapters supplies those values per environment.
Chaining transformations
Small functions compose well. DataFrame has a transform method that takes a function and applies it, which keeps a pipeline readable:
result = (
df.transform(add_order_total)
.transform(drop_cancelled)
)Each step can then be tested alone, and a failing test points at one function.
Common errors
- Hidden reads. A helper that calls
spark.table("prod.sales.customers")for a join cannot run in a unit test. Pass the lookup DataFrame in as an argument. - Hidden writes. A transformation that saves an intermediate result makes every test touch storage. Move the write to the entry point.
- Logic in the notebook. Code defined only in a notebook cell cannot be imported by pytest. Put it in a module under
src/and import it from the notebook or job. - Using
collect()for results. Returning Python lists from a transformation breaks chaining. Return a DataFrame and let the test compare it.
Exercise
A function flag_late_orders(df) calls spark.table("main.sales.holidays") to exclude holidays when it computes lateness. Why is it hard to unit test, and how do you fix it?
Show answer
It reads a real table, so a test needs that table and a workspace. Change the signature to flag_late_orders(df, holidays_df) and have the entry point read the holidays table and pass it in. A test can then build a small holidays DataFrame in memory.