Sub topic 8
Data quality checks and expectations
This chapter assumes you can write pytest tests with a spark fixture, know PySpark DataFrames, and have read the earlier chapters on unit and integration tests.
Why unit tests are not enough
A unit test proves that your code handles the small inputs you wrote. It says nothing about the data that arrives tomorrow. A source system can send null keys, negative quantities, or duplicate orders, and a correct transformation will pass them along. Data quality checks test the data itself, so they run where the real data is: in integration tests, and inside the pipeline.
| Kind of check | Tests | Runs |
|---|---|---|
| Unit test | Your code, on tiny hand-built data | Locally and in CI |
| Integration test | Code and tables together, in a workspace | Staging, before promotion |
| Data quality check | The data, on every run | Inside the job or pipeline |
Reusable checks in plain PySpark
The simplest approach is a function that takes a DataFrame and a set of named rules, and returns how many rows break each rule. It stays portable, so you can call it from a job, a notebook, or a test.
from pyspark.sql import DataFrame, functions as F
def count_violations(df: DataFrame, rules: dict[str, str]) -> dict[str, int]:
"""Return the number of rows that break each SQL-expression rule."""
results = {}
for name, condition in rules.items():
# coalesce makes a NULL result count as a violation
failing = df.filter(F.expr(f"NOT coalesce({condition}, false)"))
results[name] = failing.count()
return resultsThe coalesce call matters. In SQL, quantity > 0 evaluates to NULL when quantity is NULL, and NOT NULL is also NULL, so a plain filter would silently skip those rows.
Use the function in an integration test against real output:
def test_orders_pass_quality_rules(spark):
orders = spark.createDataFrame(
[(1, 2, 5.0), (2, 3, 1.5)],
["order_id", "quantity", "unit_price"],
)
rules = {
"order_id_present": "order_id IS NOT NULL",
"quantity_positive": "quantity > 0",
"price_non_negative": "unit_price >= 0",
}
assert count_violations(orders, rules) == {
"order_id_present": 0,
"quantity_positive": 0,
"price_non_negative": 0,
}In a real integration test, replace createDataFrame with spark.table("staging_catalog.sales.orders").
Expectations inside a pipeline
Lakeflow Spark Declarative Pipelines (formerly Delta Live Tables) lets you attach expectations to a dataset. An expectation is a named SQL condition plus a policy for rows that fail it.
import dlt
@dlt.table
@dlt.expect("has_customer", "customer_id IS NOT NULL")
@dlt.expect_or_drop("positive_quantity", "quantity > 0")
@dlt.expect_or_fail("valid_price", "unit_price >= 0")
def clean_orders():
return spark.read.table("raw_orders")The three decorators differ only in what happens to a failing row:
| Decorator | Failing rows | Pipeline update |
|---|---|---|
| `expect` | Kept, and counted in metrics | Continues |
| `expect_or_drop` | Removed from the target | Continues |
| `expect_or_fail` | Not written | Fails |
Pick the policy by cost of the error. Use expect for conditions you want to monitor, expect_or_drop when bad rows are safe to discard, and expect_or_fail when wrong data is worse than late data. Pipeline metrics record how many rows passed or failed each expectation.
Constraints on the table
Delta tables also enforce rules directly:
ALTER TABLE main.sales.orders
ADD CONSTRAINT positive_quantity CHECK (quantity > 0);A write that violates a CHECK constraint fails. Adding the constraint also fails if existing rows already break it, so clean the data first. Constraints guard every writer to the table, not just your pipeline.
Using checks in the release flow
Run count_violations tests in the staging stage of your CD workflow, after the deploy and before promotion. A failed rule then blocks the release, in the same way a failed unit test blocks a merge.
Exercise
A rule quantity > 0 is run through df.filter("NOT (quantity > 0)").count(). A row has a NULL quantity. Is it counted as a violation, and how do you fix the check?
Show answer
No. NULL > 0 is NULL, and NOT NULL is NULL, so the filter drops the row. Wrap the condition as NOT coalesce(quantity > 0, false) so NULL counts as a failure.