first working template
This commit is contained in:
1 parent
62a3714562
commit
ca6bea351a
21 files changed
+684
-31
No files matched your search
@@ -64,7 +64,7 @@ products/<slug>/
|
||||
010_schema.sql schema, pg_graphql directive, shared trigger function
|
||||
020_tables.sql one CREATE TABLE per entity, foreign keys, association tables
|
||||
030_api.sql grants for the API role and the product's GraphQL RPC endpoint
|
||||
040_seed.sql optional sample rows
|
||||
040_seed.sql sample rows with fixed uuids; the unit tests are written against them
|
||||
graphql/
|
||||
schema.graphql documents the reflected GraphQL surface (not loaded anywhere)
|
||||
smoke.graphql query run by `test`; must return no errors
|
||||
@@ -76,6 +76,13 @@ products/<slug>/
|
||||
010_replication.sql registers each ODS table with pg_duckpipe
|
||||
trino/
|
||||
smoke.sql one count per table through Trino
|
||||
tests/
|
||||
expectations.yaml what the seed holds and how it must behave: the only generated test file
|
||||
test_seed.py generic tests, copied unchanged from this template:
|
||||
test_constraints.py seed rows and values; constraints refuse bad updates; updated_at
|
||||
test_graphql.py every column reflected; seed rows and relationships through GraphQL
|
||||
test_lake.py lake row counts and seed values through Trino
|
||||
test_streams.py every row on its outbound topic; one record through every interface
|
||||
```
|
||||
|
||||
The CLI applies `ods/*.sql` and `lakehouse/*.sql` in filename order, so extra files can be
|
||||
@@ -103,6 +110,10 @@ the ODS. A GraphQL update came out on the compacted outbound topic and reached
|
||||
role. `undeploy` also removed the registry group, which the management zone's Apicurio
|
||||
allows.
|
||||
|
||||
Its unit tests passed the same day: 12 passed, and the relationship test was skipped because a
|
||||
single-entity product has none. `canonical-party` in semprini-domain-cdp-digital-core, generated
|
||||
from this template, passes 65 of 65 checks and 100 unit tests in about a minute.
|
||||
|
||||
The earlier verification, from semprini-blog-dataproducts:
|
||||
|
||||
On 2026-09-08 that round trip verified, on the live stack: the product's GraphQL endpoint
|
||||
@@ -205,6 +216,8 @@ File | Source in the model
|
||||
`flink/job.sql` | same columns as the table, Flink types
|
||||
`lakehouse/010_replication.sql`, `trino/smoke.sql` | table names only
|
||||
`odps.yaml` | product description, `sla`, `refresh`, governance posture, owner
|
||||
`ods/040_seed.sql` | two or three rows per table with fixed uuids that satisfy every constraint
|
||||
`tests/expectations.yaml` | the seed (row counts, one sample row per table), each constraint in `020_tables.sql` (an update that breaks it and the name PostgreSQL reports), every relationship field in `schema.graphql`, and one valid record for a table without required foreign keys
|
||||
|
||||
Rules that are easy to miss:
|
||||
|
||||
@@ -236,6 +249,69 @@ at `http://localhost:8081/apis/registry/v3` unless `APICURIO_URL` says otherwise
|
||||
CLI substitutes it from `.env` when submitting the job, then deletes the rendered copy
|
||||
from the jobmanager. Only `DOMAIN` and `ODS_PASSWORD` are substituted.
|
||||
|
||||
## Unit tests
|
||||
|
||||
`data-domain test` asks whether each interface is up. The unit tests ask whether the product
|
||||
behaves as the model says, against the seed data in `ods/040_seed.sql`. Run them from the domain
|
||||
repository after `deploy`:
|
||||
|
||||
```bash
|
||||
uv run data-domain unit products/<slug> # all of them
|
||||
uv run data-domain unit products/<slug> -k graphql # any pytest arguments after the path
|
||||
```
|
||||
|
||||
The test modules are generic and copied unchanged into every product; only
|
||||
`tests/expectations.yaml` is generated. The fixtures they use (`dp`, `product`, `expectations`)
|
||||
come from the domain platform's pytest plugin, `semprini_data_domain.testing`, which reaches the
|
||||
ODS and lakehouse with psql in their containers, GraphQL through PostgREST, the lake through
|
||||
Trino's HTTP protocol and Kafka with a client on the domain's published port.
|
||||
|
||||
| Module | Checks, per table unless noted |
|
||||
|---|---|
|
||||
| `test_seed.py` | the seed row count; every sample row's values in the ODS |
|
||||
| `test_constraints.py` | each `rejects` update to the first sample fails with the named constraint; an update moves `updated_at` past `created_at` |
|
||||
| `test_graphql.py` | the GraphQL type has a field for every ODS column; sample rows through GraphQL; each relationship query's `expect` (whole product) |
|
||||
| `test_lake.py` | the lake has as many rows as the ODS; sample rows through Trino |
|
||||
| `test_streams.py` | every ODS key has a live value on the outbound topic; one `round_trip` record: inbound topic → ODS → outbound topic and lake → GraphQL update → both → GraphQL delete → tombstone and lake removal (whole product) |
|
||||
|
||||
The tests leave the seed as they found it: constraint checks run in a transaction that is rolled
|
||||
back, and the round-trip record is deleted in a `finally` block. Before publishing that record,
|
||||
`test_streams.py` inserts it into the ODS inside a rolled-back transaction. If the ODS refuses
|
||||
it, the test fails there, and the record is never published, because a refused record stops the
|
||||
Flink job (see *Platform prerequisites and known gaps*).
|
||||
|
||||
## Registering in the management zone
|
||||
|
||||
Once deployed and tested, publish the product in the management zone's catalogue:
|
||||
|
||||
```bash
|
||||
uv run data-domain register products/<slug>
|
||||
uv run data-domain unregister products/<slug>
|
||||
```
|
||||
|
||||
The domain must be registered first (`platform/domain-integration.sh register mgmt`). That puts
|
||||
the domain in OpenMetadata and the ingestion-bot token in the domain's `.env`. Then `register`
|
||||
publishes:
|
||||
- the lake tables under the domain's Trino service, with columns, descriptions and keys from the
|
||||
ODS;
|
||||
- the topics under the domain's Kafka service, with their JSON Schemas;
|
||||
- the data product, imported from `odps.yaml`, with tables and topics as assets. Tables and
|
||||
outbound topics are output ports, and inbound topics are input ports;
|
||||
- lineage from each inbound topic to its table, and from the table to its outbound topic.
|
||||
|
||||
Apicurio needs no separate step: `deploy` registers the schemas there.
|
||||
|
||||
What this means for `odps.yaml`:
|
||||
- **Keep it standard ODPS.** The platform translates it to the flattened shape OpenMetadata 2.0
|
||||
imports.
|
||||
- **Tags are dropped on import.** OpenMetadata would need every `details.tags` value to exist
|
||||
as a classification tag, and the entity names used here are already the product's assets.
|
||||
- **The name must be unique across domains.** OpenMetadata names the product from
|
||||
`details.en.name` with spaces as underscores. `register` refuses to merge into a same-named
|
||||
product in another domain.
|
||||
- **Lifecycle isn't imported.** It starts at `DEVELOPMENT`, whatever `status` says, because
|
||||
OpenMetadata's governance workflow owns it.
|
||||
|
||||
## Experience products read canonical ones
|
||||
|
||||
An experience product (MD-DDL `consumer-aligned`) is shaped for an audience rather than
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
-- Example Address: operational data store schema (runs on the postgres service).
|
||||
-- Example Address: operational data store schema (runs on the ods service).
|
||||
|
||||
CREATE SCHEMA example_address;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
-- Example Address: API surface (runs on the postgres service).
|
||||
-- Example Address: API surface (runs on the ods service).
|
||||
|
||||
GRANT USAGE ON SCHEMA example_address TO anon;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA example_address TO anon;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
-- Example Address: sample rows (runs on the postgres service).
|
||||
-- Example Address: sample rows (runs on the ods service).
|
||||
|
||||
INSERT INTO example_address.address
|
||||
(address_id, address_type, address_line_1, address_line_2, suburb, city, state_or_region, postcode, country)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Example Address: 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 <path to canonical_data_product/example>
|
||||
|
||||
tables:
|
||||
address:
|
||||
rows: 3
|
||||
samples:
|
||||
- address_id: 2f4c1a3e-0001-4a7b-9c11-000000000001
|
||||
address_type: Street Address
|
||||
address_line_1: 1 Queen Street
|
||||
suburb: Auckland Central
|
||||
city: Auckland
|
||||
state_or_region: Auckland
|
||||
postcode: "1010"
|
||||
country: NZ
|
||||
rejects:
|
||||
- set: {address_type: Castle}
|
||||
violates: address_address_type_check
|
||||
- set: {address_line_1: null}
|
||||
violates: street_address_requires_address_line_1
|
||||
- set: {country: null}
|
||||
violates: not-null
|
||||
|
||||
# A single-entity product has no relationship fields to traverse.
|
||||
graphql: []
|
||||
|
||||
round_trip:
|
||||
table: address
|
||||
record:
|
||||
address_id: 2f4c1a3e-0001-4a7b-9c11-00000000e2e0
|
||||
address_type: PO Box
|
||||
address_line_1: PO Box 999
|
||||
city: Nelson
|
||||
postcode: "7040"
|
||||
country: NZ
|
||||
update:
|
||||
city: Richmond
|
||||
@@ -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']}"
|
||||
@@ -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}"
|
||||
@@ -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}")
|
||||
@@ -1,4 +1,4 @@
|
||||
-- {{product.name}}: operational data store schema (runs on the postgres service).
|
||||
-- {{product.name}}: operational data store schema (runs on the ods service).
|
||||
--
|
||||
-- The product owns one PostgreSQL schema. pg_graphql reflects only the schemas on the
|
||||
-- search_path, and the product's RPC endpoint (030_api.sql) sets the search_path to this
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
-- {{product.name}}: API surface (runs on the postgres service).
|
||||
-- {{product.name}}: API surface (runs on the ods service).
|
||||
--
|
||||
-- PostgREST connects as `authenticator` and switches to the platform's `anon` role, so the
|
||||
-- GraphQL API sees exactly what `anon` is granted here. The lab has no authentication; a real
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
-- {{product.name}}: optional sample rows (runs on the postgres service).
|
||||
-- {{product.name}}: optional sample rows (runs on the ods service).
|
||||
--
|
||||
-- Delete this file if the product should deploy empty. Use fixed uuids so child rows can
|
||||
-- reference their parents and so the same rows can be published to the inbound topics or
|
||||
-- queried through GraphQL in examples. Keep it to a handful of rows per table.
|
||||
-- The unit tests (tests/expectations.yaml) are written against these rows, so every product has
|
||||
-- a seed. Use fixed uuids so child rows can reference their parents and the tests can find
|
||||
-- them. Keep it to a handful of rows per table, satisfying every constraint.
|
||||
|
||||
-- >>> repeat per entity table, parents before children
|
||||
INSERT INTO {{product.schema}}.{{table}} ({{table}}_id, {{column}}, {{parent_table}}_id) VALUES
|
||||
|
||||
@@ -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']}"
|
||||
@@ -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}"
|
||||
@@ -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}")
|
||||
Reference in new issue
Block a user