Files
semprini-data-product-templ…/canonical_data_product/tests/test_constraints.py
T
2026-09-18 08:56:37 +12:00

49 lines
1.9 KiB
Python

"""Constraints and triggers: the ODS refuses what the model forbids, and keeps updated_at current.
Every statement runs in a transaction that is rolled back, so the seed is untouched. Each
rejected update in expectations.yaml is applied to the table's first sample row and must fail
with the named constraint (or "not-null") in PostgreSQL's error.
"""
import pytest
from semprini_data_domain.testing import expectations_for
TABLES = list(expectations_for(__file__)["tables"].items())
REJECTS = [(table, reject) for table, spec in TABLES for reject in spec.get("rejects", [])]
def key_of(dp, table):
return next(t.key for t in dp.product.tables if t.name == table)
def first_sample_key(dp, table, spec):
assert spec.get("samples"), f"{table} needs a sample in expectations.yaml"
return spec["samples"][0][key_of(dp, table)]
@pytest.mark.parametrize(
"table,reject", REJECTS, ids=[f"{t}-{r['violates']}" for t, r in REJECTS]
)
def test_update_is_refused(dp, table, reject):
spec = dict(TABLES)[table]
key = key_of(dp, table)
assignments = ", ".join(f"{column} = {dp.sql_literal(value)}" for column, value in reject["set"].items())
error = dp.sql_error(
f"UPDATE {dp.product.schema}.{table} SET {assignments} "
f"WHERE {key} = '{first_sample_key(dp, table, spec)}'"
)
assert error is not None, f"{table}: update {reject['set']} was accepted"
assert reject["violates"] in error, error
@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES])
def test_update_sets_updated_at(dp, table, spec):
key = key_of(dp, table)
sample_key = first_sample_key(dp, table, spec)
rows = dp.sql_rolled_back(
f"UPDATE {dp.product.schema}.{table} SET {key} = {key} WHERE {key} = '{sample_key}'",
f"SELECT updated_at > created_at AS moved FROM {dp.product.schema}.{table} WHERE {key} = '{sample_key}'",
)
assert rows == [{"moved": True}]