first working template

This commit is contained in:
paul committed 2026-09-18 08:56:37 +12:00
1 parent 62a3714562
commit ca6bea351a
21 files changed
+684 -31

No files matched your search

@@ -0,0 +1,47 @@
# {{product.name}}: unit test expectations, generated with ods/040_seed.sql and kept in step with it.
# Read by the generic tests beside this file (test_*.py, copied unchanged from the template).
# Run from the domain repository: uv run data-domain unit <product dir>
tables:
# rows: how many rows the seed inserts
# samples: seed rows checked by value in the ODS, through GraphQL and in the lake (the key
# column is required; the first sample is also the row the reject updates target)
# rejects: updates to the first sample that the ODS must refuse, with the constraint named in
# PostgreSQL's error: <table>_<column>_check for an enum, the constraint's own name for
# a model constraint, <table>_<column>_fkey for a foreign key, <table>_<column>_key for
# a unique column, "not-null" for NOT NULL
# >>> repeat per entity table, in product.yaml order
{{table}}:
rows: {{seed_row_count}}
samples:
- {{table}}_id: {{seed_uuid}}
{{column}}: {{seed_value}} # every column the seed row sets, quoted when YAML would retype it
rejects:
# >>> repeat per enum column, CHECK constraint, foreign key, unique and NOT NULL column
- set: {{{column}}: {{invalid_value}}}
violates: {{constraint_name}}
# <<< end repeat
# <<< end repeat
# Relationship traversals documented in graphql/schema.graphql, checked against the seed: one per
# relationship field the product exposes. `expect` must be contained in the response; lists
# compare item by item, in order, so give nested collections an orderBy.
graphql:
# >>> repeat per relationship field
- name: {{relationship_slug}}
query: '{ {{entity}}Collection(filter: {{{entity}}Id: {eq: "{{seed_uuid}}"}}) { edges { node { {{relationship_field}} { {{camelColumn}} } } } } }'
expect:
{{entity}}Collection: {edges: [{node: {{{relationship_field}}: {{{camelColumn}}: {{seed_value}}}}}]}
# <<< end repeat
# One record published to an inbound topic and followed through every interface, then updated
# and deleted through GraphQL. Pick a table without required foreign keys, and a key no seed row
# uses. The test refuses to publish a record the ODS would reject, because a refused record stops
# the product's Flink job.
round_trip:
table: {{table}}
record:
{{table}}_id: {{unused_uuid}}
{{column}}: {{valid_value}}
update:
{{text_column}}: {{new_value}}
@@ -0,0 +1,48 @@
"""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}]
@@ -0,0 +1,47 @@
"""CRUD API: pg_graphql reflects every column of every table, serves the seed rows, and
resolves the relationships the product documents in graphql/schema.graphql.
"""
import pytest
from semprini_data_domain.platform import camel, pascal
from semprini_data_domain.testing import contains, expectations_for, same_value
EXPECT = expectations_for(__file__)
TABLES = list(EXPECT["tables"].items())
SAMPLES = [(table, sample) for table, spec in TABLES for sample in spec.get("samples", [])]
QUERIES = EXPECT.get("graphql", [])
def key_of(dp, table):
return next(t.key for t in dp.product.tables if t.name == table)
@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES])
def test_type_reflects_every_column(dp, table, spec):
data = dp.graphql(f'{{ __type(name: "{pascal(table)}") {{ fields {{ name }} }} }}')
assert data["__type"], f"type {pascal(table)} not reflected"
fields = {f["name"] for f in data["__type"]["fields"]}
missing = [camel(c) for c in dp.columns(table) if camel(c) not in fields]
assert not missing, f"{pascal(table)} lacks {missing}"
@pytest.mark.parametrize("table,sample", SAMPLES, ids=[t for t, _ in SAMPLES])
def test_seed_row_through_graphql(dp, table, sample):
key = key_of(dp, table)
fields = " ".join(camel(column) for column in sample)
data = dp.graphql(
f'{{ {camel(table)}Collection(filter: {{{camel(key)}: {{eq: "{sample[key]}"}}}}) '
f"{{ edges {{ node {{ {fields} }} }} }} }}"
)
edges = data[f"{camel(table)}Collection"]["edges"]
assert len(edges) == 1, f"{table} {sample[key]}: {edges}"
node = edges[0]["node"]
for column, expected in sample.items():
assert same_value(expected, node[camel(column)]), f"{camel(column)}: {node[camel(column)]!r} != {expected!r}"
@pytest.mark.parametrize("case", QUERIES, ids=[q["name"] for q in QUERIES])
def test_relationship(dp, case):
data = dp.graphql(case["query"])
assert contains(case["expect"], data), f"{data} does not contain {case['expect']}"
+33
View File
@@ -0,0 +1,33 @@
"""Analytic SQL: pg_duckpipe has replicated every seed row into the lake, and Trino serves it."""
import pytest
from semprini_data_domain.testing import expectations_for, same_value
TABLES = list(expectations_for(__file__)["tables"].items())
SAMPLES = [(table, sample) for table, spec in TABLES for sample in spec.get("samples", [])]
def key_of(dp, table):
return next(t.key for t in dp.product.tables if t.name == table)
@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES])
def test_lake_matches_ods(dp, table, spec):
lake = f"{dp.product.trino_catalog}.{dp.product.lake_schema}.{table}"
ods = dp.sql(f"SELECT count(*) AS n FROM {dp.product.schema}.{table}")[0]["n"]
assert ods == spec["rows"]
dp.eventually(lambda: dp.trino(f"SELECT count(*) AS n FROM {lake}") == [{"n": ods}])
@pytest.mark.parametrize("table,sample", SAMPLES, ids=[t for t, _ in SAMPLES])
def test_seed_row_in_lake(dp, table, sample):
key = key_of(dp, table)
lake = f"{dp.product.trino_catalog}.{dp.product.lake_schema}.{table}"
# Every column is cast to varchar so dates and uuids compare as text, the way the seed writes them.
columns = ", ".join(f"CAST({column} AS varchar) AS {column}" for column in sample)
rows = dp.trino(f"SELECT {columns} FROM {lake} WHERE CAST({key} AS varchar) = '{sample[key]}'")
assert len(rows) == 1, f"{sample[key]} not in {lake}"
for column, expected in sample.items():
want = None if expected is None else (str(expected).lower() if isinstance(expected, bool) else expected)
assert same_value(want, rows[0][column]), f"{column}: {rows[0][column]!r} != {expected!r}"
+31
View File
@@ -0,0 +1,31 @@
"""Seed data: every ODS table holds the rows ods/040_seed.sql inserts, with the values it inserts.
Generic canonical-product test, copied unchanged into every product. What to expect comes
from expectations.yaml beside it. Run from the domain repository: data-domain unit <product>.
"""
import pytest
from semprini_data_domain.testing import expectations_for, same_value
TABLES = list(expectations_for(__file__)["tables"].items())
SAMPLES = [(table, sample) for table, spec in TABLES for sample in spec.get("samples", [])]
def key_of(dp, table):
return next(t.key for t in dp.product.tables if t.name == table)
@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES])
def test_seed_row_count(dp, table, spec):
rows = dp.sql(f"SELECT count(*) AS n FROM {dp.product.schema}.{table}")
assert rows[0]["n"] == spec["rows"]
@pytest.mark.parametrize("table,sample", SAMPLES, ids=[t for t, _ in SAMPLES])
def test_seed_row_values(dp, table, sample):
key = key_of(dp, table)
rows = dp.sql(f"SELECT * FROM {dp.product.schema}.{table} WHERE {key} = '{sample[key]}'")
assert len(rows) == 1, f"seed row {sample[key]} not in {table}"
for column, expected in sample.items():
assert same_value(expected, rows[0][column]), f"{table}.{column}: {rows[0][column]!r} != {expected!r}"
@@ -0,0 +1,75 @@
"""Publish input and subscribe output.
Every row is on the table's compacted outbound topic, and one record published to an inbound
topic travels through every interface: ODS, outbound topic, lake, then a GraphQL update and a
GraphQL delete that follow it back out. The record is checked against the ODS constraints
before it is published, because a record the ODS refuses stops the product's Flink job.
"""
import pytest
from semprini_data_domain.platform import camel, pascal
from semprini_data_domain.testing import contains, expectations_for
EXPECT = expectations_for(__file__)
TABLES = list(EXPECT["tables"].items())
ROUND_TRIP = EXPECT.get("round_trip")
def key_of(dp, table):
return next(t.key for t in dp.product.tables if t.name == table)
@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES])
def test_outbound_topic_carries_every_row(dp, table, spec):
key = key_of(dp, table)
ods_keys = {r[key] for r in dp.sql(f"SELECT {key} FROM {dp.product.schema}.{table}")}
topic = dp.topic(table, "subscribe-output")
dp.eventually(lambda: ods_keys <= {k for k, v in dp.latest(topic).items() if v is not None}, timeout=60)
@pytest.mark.skipif(not ROUND_TRIP, reason="no round_trip in expectations.yaml")
def test_record_round_trip(dp):
table, record, update = ROUND_TRIP["table"], ROUND_TRIP["record"], ROUND_TRIP["update"]
schema, key = dp.product.schema, key_of(dp, table)
record_key = record[key]
lake = f"{dp.product.trino_catalog}.{dp.product.lake_schema}.{table}"
outbound = dp.topic(table, "subscribe-output")
columns = ", ".join(record)
values = ", ".join(dp.sql_literal(v) for v in record.values())
where = f"{key} = '{record_key}'"
assert not dp.sql(f"SELECT 1 FROM {schema}.{table} WHERE {where}"), f"{record_key} already exists; clean up first"
refused = dp.sql_error(f"INSERT INTO {schema}.{table} ({columns}) VALUES ({values})")
assert refused is None, f"the ODS would refuse the round-trip record, so it is not published: {refused}"
try:
# Publish input -> Flink -> ODS
dp.publish(dp.topic(table, "publish-input"), [record])
dp.eventually(lambda: contains(record, (dp.sql(f"SELECT * FROM {schema}.{table} WHERE {where}") or [None])[0]))
# ODS -> Flink CDC -> subscribe output, and ODS -> pg_duckpipe -> lake
dp.eventually(lambda: contains(record, dp.latest(outbound).get(record_key)))
dp.eventually(lambda: dp.trino(f"SELECT count(*) AS n FROM {lake} WHERE CAST({key} AS varchar) = '{record_key}'") == [{"n": 1}])
# CRUD API update -> subscribe output and lake
assignments = ", ".join(f'{camel(c)}: "{v}"' for c, v in update.items())
data = dp.graphql(
f"mutation {{ update{pascal(table)}Collection(set: {{{assignments}}}, "
f'filter: {{{camel(key)}: {{eq: "{record_key}"}}}}) {{ affectedCount }} }}'
)
assert data[f"update{pascal(table)}Collection"]["affectedCount"] == 1
dp.eventually(lambda: contains(update, dp.latest(outbound).get(record_key)))
column, value = next(iter(update.items()))
dp.eventually(lambda: dp.trino(f"SELECT CAST({column} AS varchar) AS v FROM {lake} WHERE CAST({key} AS varchar) = '{record_key}'") == [{"v": str(value)}])
# CRUD API delete -> tombstone on subscribe output, row gone from the lake
data = dp.graphql(
f"mutation {{ deleteFrom{pascal(table)}Collection("
f'filter: {{{camel(key)}: {{eq: "{record_key}"}}}}, atMost: 1) {{ affectedCount }} }}'
)
assert data[f"deleteFrom{pascal(table)}Collection"]["affectedCount"] == 1
dp.eventually(lambda: (lambda state: record_key in state and state[record_key] is None)(dp.latest(outbound)))
dp.eventually(lambda: dp.trino(f"SELECT count(*) AS n FROM {lake} WHERE CAST({key} AS varchar) = '{record_key}'") == [{"n": 0}])
finally:
dp.execute(f"DELETE FROM {schema}.{table} WHERE {where}")