first working template
This commit is contained in:
1 parent
62a3714562
commit
ca6bea351a
21 files changed
+684
-31
No files matched your search
@@ -108,9 +108,24 @@ which stay optional on the inbound topic. Enum properties list the values verbat
|
|||||||
**Credentials.** `flink/job.sql` connects to `ods:5432/ods` as `postgres` with password
|
**Credentials.** `flink/job.sql` connects to `ods:5432/ods` as `postgres` with password
|
||||||
`${ODS_PASSWORD}`, exactly as the template shows. Never write a real credential into a product.
|
`${ODS_PASSWORD}`, exactly as the template shows. Never write a real credential into a product.
|
||||||
|
|
||||||
**Seed.** Write `ods/040_seed.sql` unless told not to: two or three rows per table with fixed
|
**Seed.** Always write `ods/040_seed.sql`: two or three rows per table with fixed uuids,
|
||||||
uuids, parents first, subtype rows matching their parent's discriminator, values that satisfy
|
parents first, subtype rows matching their parent's discriminator, values that satisfy every
|
||||||
every CHECK. The seed is what makes the GraphQL and Trino smoke tests show data.
|
CHECK. The unit tests are written against it.
|
||||||
|
|
||||||
|
**Unit tests.** Copy `tests/test_*.py` from the template unchanged, and write
|
||||||
|
`tests/expectations.yaml` from the seed and the DDL:
|
||||||
|
- **Rows and samples:** each table's seed row count, and one sample row with every column the
|
||||||
|
seed sets. Quote values YAML would retype, such as postcodes and registration numbers.
|
||||||
|
- **Rejects:** one update per enum column, `CHECK` constraint, foreign key, unique column and
|
||||||
|
`NOT NULL` column, naming the constraint as PostgreSQL reports it. That is
|
||||||
|
`<table>_<column>_check` for an inline enum, the constraint's own name for a named one,
|
||||||
|
`<table>_<column>_fkey` or the FK's declared name, `<table>_<column>_key` for `UNIQUE`, and
|
||||||
|
`not-null`. Target the first sample, and pick values that break only the constraint under
|
||||||
|
test (for a foreign key, a uuid no parent has).
|
||||||
|
- **GraphQL:** one query per relationship field in `schema.graphql`, with an `orderBy` on nested
|
||||||
|
collections and the seed values it must return.
|
||||||
|
- **Round trip:** a valid record for a table without required foreign keys, with a key no seed
|
||||||
|
row uses, and a one-column text update.
|
||||||
|
|
||||||
**ODPS.** `class` maps to `type` (domain-aligned is `dataset`), `status` `Active` to
|
**ODPS.** `class` maps to `type` (domain-aligned is `dataset`), `status` `Active` to
|
||||||
`production`, `availability` `"99.95%"` to `99.95`, `refresh: real-time` to a freshness of
|
`production`, `availability` `"99.95%"` to `99.95`, `refresh: real-time` to a freshness of
|
||||||
@@ -128,23 +143,26 @@ product brings the domain near the limit.
|
|||||||
2. Derive the table list and order, then the column list per table. Write every file in
|
2. Derive the table list and order, then the column list per table. Write every file in
|
||||||
`products/<slug>/` in the domain repository in one pass. Every template file has a
|
`products/<slug>/` in the domain repository in one pass. Every template file has a
|
||||||
counterpart; nothing else is added.
|
counterpart; nothing else is added.
|
||||||
3. Self-check before touching the platform: no `{{` and no `>>>` anywhere in the product;
|
3. Self-check before touching the platform: no `{{` and no `>>>` anywhere in the product
|
||||||
|
(including `tests/expectations.yaml`);
|
||||||
each table in `product.yaml` has an inbound and an outbound topic and a schema file; the
|
each table in `product.yaml` has an inbound and an outbound topic and a schema file; the
|
||||||
column lists agree across DDL, JSON Schema and Flink; `smoke.graphql` and `smoke.sql`
|
column lists agree across DDL, JSON Schema and Flink; `smoke.graphql` and `smoke.sql`
|
||||||
cover every table; parents precede children everywhere.
|
cover every table; parents precede children everywhere.
|
||||||
4. From the domain repository, deploy with `uv run data-domain deploy products/<slug>`. Deploy
|
4. From the domain repository, deploy with `uv run data-domain deploy products/<slug>`. Deploy
|
||||||
expects a clean slate, so on any failure run `uv run data-domain undeploy products/<slug>
|
expects a clean slate, so on any failure run `uv run data-domain undeploy products/<slug>
|
||||||
--yes`, fix, and deploy again.
|
--yes`, fix, and deploy again.
|
||||||
5. Run `uv run data-domain test products/<slug>`.
|
5. Run `uv run data-domain test products/<slug>`, then `uv run data-domain unit
|
||||||
6. Verify what `test` does not: introspect the endpoint with curl for one subtype and one
|
products/<slug>`. A failing unit test is a defect in the product or its expectations; fix
|
||||||
association table and confirm the relationship field names match `schema.graphql`; confirm
|
whichever is wrong, and never weaken an expectation to match a product that disagrees with
|
||||||
the Trino counts equal the seed row counts.
|
the model.
|
||||||
|
6. If the domain is registered with the management zone, run `uv run data-domain register
|
||||||
|
products/<slug>` and confirm the data product appears under the domain.
|
||||||
7. Leave the product deployed and report.
|
7. Leave the product deployed and report.
|
||||||
|
|
||||||
## Report
|
## Report
|
||||||
|
|
||||||
Lead with the deploy and test outcome, including anything skipped or failed, with the CLI
|
Lead with the deploy, test, unit test and registration outcome, including anything skipped
|
||||||
output for failures. Then the versions generated from (model version and commit, template
|
or failed, with the CLI output for failures. Then the versions generated from (model version and commit, template
|
||||||
commit), and a short generation summary: entity to table mapping, the relationships left
|
commit), and a short generation summary: entity to table mapping, the relationships left
|
||||||
outside the boundary, the assumptions (the ODS is current state and declared bitemporal
|
outside the boundary, the assumptions (the ODS is current state and declared bitemporal
|
||||||
tracking is served by the outbound topics and the lake; discriminator values; typed
|
tracking is served by the outbound topics and the lake; discriminator values; typed
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ shared a repository with its platform, model and products.
|
|||||||
|
|
||||||
| Template | Product class | MD-DDL `class` | Status |
|
| Template | Product class | MD-DDL `class` | Status |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| [canonical_data_product/](canonical_data_product/README.md) | Canonical: a slice of the domain's canonical model, published as modelled through GraphQL, Kafka and Trino | `domain-aligned` | Available. Verified 2026-09-17 on the domain platform, 9 of 9 checks |
|
| [canonical_data_product/](canonical_data_product/README.md) | Canonical: a slice of the domain's canonical model, published as modelled through GraphQL, Kafka and Trino | `domain-aligned` | Available, with generic unit tests. Example verified 2026-09-18 on the domain platform (9 checks, 12 unit tests); Canonical Party generated from it passes 65 checks and 100 unit tests |
|
||||||
| `source_aligned_data_product/` | Source aligned: one source system's data in its own shape, for audit, replay and debugging | `source-aligned` | Planned |
|
| `source_aligned_data_product/` | Source aligned: one source system's data in its own shape, for audit, replay and debugging | `source-aligned` | Planned |
|
||||||
| `experience_<class>_data_product/` | Experience: shaped for an audience. Several classes, e.g. lake tables built by scheduled dbt models | `consumer-aligned` | Planned |
|
| `experience_<class>_data_product/` | Experience: shaped for an audience. Several classes, e.g. lake tables built by scheduled dbt models | `consumer-aligned` | Planned |
|
||||||
|
|
||||||
@@ -27,7 +27,8 @@ shared a repository with its platform, model and products.
|
|||||||
data_products/*.md ───────▶ <class>_data_product/ ◀── product contract ── data-domain CLI
|
data_products/*.md ───────▶ <class>_data_product/ ◀── product contract ── data-domain CLI
|
||||||
handoffs/<slug>.md .claude/agents/agent-<class>-product.md compose.domain.yml
|
handoffs/<slug>.md .claude/agents/agent-<class>-product.md compose.domain.yml
|
||||||
│ │
|
│ │
|
||||||
└──────── generate ──────┴──▶ semprini-domain-<d>/products/<slug>/ ── deploy ──▶ domain stack
|
└──────── generate ──────┴──▶ product repository (semprini-domain-cdp-<d>/<slug>/)
|
||||||
|
── deploy, test, unit, register ──▶ domain stack + management zone
|
||||||
```
|
```
|
||||||
|
|
||||||
- **From the modelling team:** a product declaration and the entities and enums it names,
|
- **From the modelling team:** a product declaration and the entities and enums it names,
|
||||||
@@ -38,8 +39,9 @@ shared a repository with its platform, model and products.
|
|||||||
manifest the `data-domain` CLI reads, and the SQL, schema, job and smoke-test files it
|
manifest the `data-domain` CLI reads, and the SQL, schema, job and smoke-test files it
|
||||||
applies. A template that needs something the contract does not offer asks the platform team
|
applies. A template that needs something the contract does not offer asks the platform team
|
||||||
first.
|
first.
|
||||||
- **Products** are generated into the domain repository that runs them, and deployed and
|
- **Products** are generated into the domain engineering team's product repository (or the
|
||||||
operated from there by the domain's engineering team.
|
domain repository), and deployed, tested and registered from the domain repository that runs
|
||||||
|
them.
|
||||||
|
|
||||||
All teams work on semprini-core, the enterprise landing zone: Keycloak for identity, and Gitea
|
All teams work on semprini-core, the enterprise landing zone: Keycloak for identity, and Gitea
|
||||||
(git.semprini.me) for these repositories.
|
(git.semprini.me) for these repositories.
|
||||||
@@ -53,9 +55,12 @@ hand:
|
|||||||
/agent-canonical-product Generate Canonical Party for the digital-core domain
|
/agent-canonical-product Generate Canonical Party for the digital-core domain
|
||||||
```
|
```
|
||||||
|
|
||||||
The agent reads the declaration and any pending handoff, writes `products/<slug>/` in the
|
The agent reads the declaration and any pending handoff, writes the product directory
|
||||||
domain repository, runs `uv run data-domain deploy` and `test` there, and reports the model and
|
(including `tests/expectations.yaml`), runs `uv run data-domain deploy`, `test`, `unit` and
|
||||||
template versions it generated from. Commit the product in the domain repository with both.
|
`register` from the domain repository, and reports the model and template versions it
|
||||||
|
generated from. Commit the product, in its product repository or the domain repository, with
|
||||||
|
both versions in the message. Digital Core's canonical products live in
|
||||||
|
semprini-domain-cdp-digital-core.
|
||||||
|
|
||||||
## Versioning
|
## Versioning
|
||||||
|
|
||||||
@@ -63,8 +68,8 @@ template versions it generated from. Commit the product in the domain repository
|
|||||||
record the tag they generated from and regenerate deliberately, not on every commit here.
|
record the tag they generated from and regenerate deliberately, not on every commit here.
|
||||||
- A template change that alters what a product directory contains may need a platform
|
- A template change that alters what a product directory contains may need a platform
|
||||||
change first. Check the product contract, and agree the change with the data platform team.
|
change first. Check the product contract, and agree the change with the data platform team.
|
||||||
- Every template keeps a worked `example/` that deploys and passes `data-domain test` on the
|
- Every template keeps a worked `example/` that deploys and passes `data-domain test` and
|
||||||
current domain platform. That example is the template's test, and the platform team's
|
`data-domain unit` on the current domain platform. That example is the template's test, and the platform team's
|
||||||
smoke test for the domain template.
|
smoke test for the domain template.
|
||||||
|
|
||||||
## Adding a template
|
## Adding a template
|
||||||
@@ -72,8 +77,9 @@ template versions it generated from. Commit the product in the domain repository
|
|||||||
1. Create `<class>_data_product/` with a `README.md` contract (what the product is, the
|
1. Create `<class>_data_product/` with a `README.md` contract (what the product is, the
|
||||||
mapping to platform interfaces, layout, naming, placeholders, type mapping, the generation
|
mapping to platform interfaces, layout, naming, placeholders, type mapping, the generation
|
||||||
input table, prerequisites and known gaps) and the template files.
|
input table, prerequisites and known gaps) and the template files.
|
||||||
2. Add a worked `example/` and verify it on a domain stack with `data-domain deploy` and
|
2. Add a worked `example/`, with a seed and `tests/` (generic test modules plus
|
||||||
`test`.
|
`expectations.yaml`), and verify it on a domain stack with `data-domain deploy`, `test` and
|
||||||
|
`unit`.
|
||||||
3. Add its generation agent as `.claude/agents/agent-<class>-product.md`, with a command
|
3. Add its generation agent as `.claude/agents/agent-<class>-product.md`, with a command
|
||||||
wrapper in `.claude/commands/`.
|
wrapper in `.claude/commands/`.
|
||||||
4. Add it to the catalogue above.
|
4. Add it to the catalogue above.
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ products/<slug>/
|
|||||||
010_schema.sql schema, pg_graphql directive, shared trigger function
|
010_schema.sql schema, pg_graphql directive, shared trigger function
|
||||||
020_tables.sql one CREATE TABLE per entity, foreign keys, association tables
|
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
|
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/
|
graphql/
|
||||||
schema.graphql documents the reflected GraphQL surface (not loaded anywhere)
|
schema.graphql documents the reflected GraphQL surface (not loaded anywhere)
|
||||||
smoke.graphql query run by `test`; must return no errors
|
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
|
010_replication.sql registers each ODS table with pg_duckpipe
|
||||||
trino/
|
trino/
|
||||||
smoke.sql one count per table through 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
|
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
|
role. `undeploy` also removed the registry group, which the management zone's Apicurio
|
||||||
allows.
|
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:
|
The earlier verification, from semprini-blog-dataproducts:
|
||||||
|
|
||||||
On 2026-09-08 that round trip verified, on the live stack: the product's GraphQL endpoint
|
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
|
`flink/job.sql` | same columns as the table, Flink types
|
||||||
`lakehouse/010_replication.sql`, `trino/smoke.sql` | table names only
|
`lakehouse/010_replication.sql`, `trino/smoke.sql` | table names only
|
||||||
`odps.yaml` | product description, `sla`, `refresh`, governance posture, owner
|
`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:
|
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
|
CLI substitutes it from `.env` when submitting the job, then deletes the rendered copy
|
||||||
from the jobmanager. Only `DOMAIN` and `ODS_PASSWORD` are substituted.
|
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
|
## Experience products read canonical ones
|
||||||
|
|
||||||
An experience product (MD-DDL `consumer-aligned`) is shaped for an audience rather than
|
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;
|
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 USAGE ON SCHEMA example_address TO anon;
|
||||||
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN 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
|
INSERT INTO example_address.address
|
||||||
(address_id, address_type, address_line_1, address_line_2, suburb, city, state_or_region, postcode, country)
|
(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
|
-- 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
|
-- 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
|
-- 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
|
-- 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
|
-- The unit tests (tests/expectations.yaml) are written against these rows, so every product has
|
||||||
-- reference their parents and so the same rows can be published to the inbound topics or
|
-- a seed. Use fixed uuids so child rows can reference their parents and the tests can find
|
||||||
-- queried through GraphQL in examples. Keep it to a handful of rows per table.
|
-- them. Keep it to a handful of rows per table, satisfying every constraint.
|
||||||
|
|
||||||
-- >>> repeat per entity table, parents before children
|
-- >>> repeat per entity table, parents before children
|
||||||
INSERT INTO {{product.schema}}.{{table}} ({{table}}_id, {{column}}, {{parent_table}}_id) VALUES
|
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