22 Commits

Author SHA1 Message Date
AlbertoPMDM 80b513106f updated generator to use the unique rule 2026-09-08 18:36:56 -06:00
AlbertoPMDM a2104d6d48 updated tests 2026-09-08 18:36:40 -06:00
AlbertoPMDM d6519ee613 improved error naming 2026-09-08 18:23:22 -06:00
AlbertoPMDM 727159ee99 sample spec now includes unique rule 2026-09-08 18:23:03 -06:00
AlbertoPMDM b6c327a925 added unique rule to generator 2026-09-08 18:22:50 -06:00
AlbertoPMDM 810aa5c3dc new tests for unique rule 2026-09-08 18:22:27 -06:00
AlbertoPMDM 4db4204f5e added unique rule to documentation 2026-09-08 18:22:08 -06:00
AlbertoPMDM 610338f387 new tests for unique rule 2026-09-08 18:21:55 -06:00
AlbertoPMDM 1db1775bed updated for unique feature 2026-09-08 18:20:56 -06:00
AlbertoPMDM 8c8fc506ae edited a test table 2026-09-08 17:58:15 -06:00
AlbertoPMDM fb17d210f4 added a synthetica data generator 2026-09-08 17:58:06 -06:00
AlbertoPMDM 21eae6c70b versioning 2026-09-08 17:57:51 -06:00
AlbertoPMDM 76cac4e265 updated version 2026-09-07 18:42:10 -06:00
AlbertoPMDM a5d0ad175a updated way in which rules are defined and parsed in order to be able to apply multiple 2026-09-07 18:39:48 -06:00
AlbertoPMDM c62e790dfc tests / fixtures 2026-09-07 18:39:48 -06:00
AlbertoPMDM 052f2c3e5f updated rule templates 2026-09-07 18:39:48 -06:00
AlbertoPMDM 7cb1684e04 updated rule format 2026-09-07 18:39:48 -06:00
AlbertoPMDM 1d6ee59e9e updated 2026-09-07 18:39:48 -06:00
AlbertoPMDM b8ce06f11a updated version 2026-09-07 18:39:48 -06:00
AlbertoPMDM 86b1340f60 updated readme 2026-09-07 18:39:48 -06:00
AlbertoPMDM e40dfd78aa updated version 2026-09-07 18:39:48 -06:00
alberto 9b7ccebce8 Merge pull request 'Dev' (#1) from dev into master
Reviewed-on: #1
2026-09-07 20:32:49 +00:00
51 changed files with 3234 additions and 728 deletions
+1
View File
@@ -19,3 +19,4 @@ wheels/
# auto-generated testing files
generated
*.db
+233 -56
View File
@@ -2,17 +2,19 @@
Generates, from a folder of YAML spec files:
- **`schema.py`** — a permissive SQLAlchemy storage layer. Every field is
`Optional`. Foreign keys are not database constraints — a bad link
never blocks a row from being saved.
- **`validation.py`** — a Pydantic "check" class per table, one rule per
field, plus any cross-field rules you declare. Never touches the
- **`schema.py`** — a permissive SQLAlchemy storage layer. Every non-primary-key
column is nullable, regardless of what the Pydantic contract requires — a
row that fails a rule is still saved and flagged, never rejected by the
database.
- **`enums.py`** — one `str, Enum` class per enum, each paired with an
`...Field` Annotated type that normalizes (strip + uppercase) and
checks membership.
- **`validation.py`** — a Pydantic "check" class per table. Every field is
`Optional[T] = None`; "required" is just one rule among several, applied
by that field's own generated checker function. Every rule raises a
generic, parameterized message — see "Field rules" below.
- **`enums.py`** — one plain `str, Enum` class per enum. Normalizing input
and checking membership both happen in `validation.py`, not here.
- **`data_dictionary.md`** — a readable table-by-table reference of every
field's SQL type, requiredness, foreign key, and rule.
field's SQL type, rule set, foreign key, and required status, plus a
plain-English list of each table's cross-field rules.
A separate `ps_core.runtime` package (not code generation) provides the
functions used at data-load time: `load_row`, `validate_row`, `ingest`,
@@ -28,68 +30,161 @@ spec_dir/
*.yaml # required, one file per table
```
See `spec/` in this repo for a worked example.
See `spec/` in this repo for a small worked example.
### `tables/*.yaml`
## Field rules
A field is optional at every layer. It activates a rule by giving it a
truthy value (or, for `regex`/`max_length`, the parameter itself — the
value doubles as the flag):
```yaml
table:
name: test_table
fields:
id:
type: uuid
primary_key: true
field2:
type: integer
rule: range
min: 1
max: 10
required: false
field7:
type: enum
enum: test_enum
required: false
owner_id: # in a different file, e.g. foreign_table.yaml
type: uuid
pac_id_hospital:
type: text
required: true
foreign_key: test_table.id
strip: true
upper: true
pac_codigo_postal_vigente:
type: text
regex: "\\d{5}"
edad_meses:
type: float
range: true
min: 16.0
max: 36.0
```
Supported field types: `text`, `integer`, `float`, `date`, `datetime`,
`bool`, `enum`, `uuid`. Supported rules: `range` (integer/float only),
`not_future` (date only). `required` defaults to `false`.
Rules apply in a fixed order, regardless of the order written in YAML:
**strip → upper → required → max_length → regex → range → not_future.**
Which rules are legal depends on the field's `type`:
### `enums.yaml`
| type | legal rules (besides `required`) |
|---|---|
| `text` | `strip`, `upper`, `regex`, `max_length` |
| `integer`, `float` | `range` (needs `min`/`max`) |
| `date` | `not_future` |
| `datetime`, `bool`, `enum` | *(none — `required` only)* |
| `uuid` | `strip` |
`enum` fields always strip + uppercase + check membership.
**Messages are generic, not per-field.** There is no `<rule>_message` key
in the spec YAML. Each rule raises a message built from the field's own
name (its `label`), by the matching function in `constraints.py` —
matching this shape:
```python
def check_range(v, lo, hi, label="value"):
if v < lo or v > hi:
raise ValueError(f"{label} must be between {lo} and {hi}, got {v}")
return v
```
To change the wording for every field that uses a given rule — across
the whole project — edit that one function in `constraints.py`. This
keeps customization in one place, in code, rather than repeated in every
field's YAML.
Using a rule the field's type doesn't support raises `ValueError` at
parse time, naming the file, field, and rule — nothing is silently
ignored.
## Foreign keys
```yaml
test_enum:
- item1
- item2
owner_id:
type: uuid
required: true
foreign_key: users.id
```
### `cross_rules.yaml`
Checked at parse time (the target table and column must exist) but
**never** turned into a database constraint — a bad link is not allowed
to block an insert. Call `ps_core.runtime.check_foreign_keys` after your
insert batch to flag orphans the same way any other rule gets flagged
(`validated=False`, `errors` updated).
## Uniqueness
```yaml
test_table:
- kind: requires
if_field: field6
if_value: true
then_field: field3
message: "field3 is required when field6 is true"
email:
type: text
unique: true
```
Supported kinds:
Same philosophy as foreign keys, on purpose: **never** a database UNIQUE
constraint, since that could silently reject a row outright rather than
let it be saved and flagged. Call `ps_core.runtime.check_unique_fields`
after your insert batch — it flags every row sharing a duplicate value
on that column (a `NULL` is never treated as a duplicate of another
`NULL`), the same way `check_foreign_keys` flags orphans.
This checks single-column uniqueness only. There is no `unique_together`
for multi-column uniqueness.
## Cross-field rules (`cross_rules.yaml`)
Table name → list of rules, each a fixed, named **kind** — never a raw
condition string. Every field a rule mentions must exist on that table,
checked at parse time.
| kind | required keys | checks |
|---|---|---|
| `order` | `fields: [a, b]`, `op: le\|lt\|ge\|gt` | `a <op> b`, skipped if either is `None` |
| `order` | `fields: [a, b]`, `op: le\|lt\|ge\|gt` | `a <op> b` |
| `equals` | `fields: [a, b]` | `a == b` |
| `sum_equals` | `target`, `parts: [...]` | `target == sum(parts)`, optional `tolerance` |
| `requires` | `if_field`, `then_field` | `then_field` is not `None` when `if_field` is truthy (or equals optional `if_value`) |
| `equals` | `fields: [a, b]` | `a == b`, skipped if either is `None` |
| `ratio_equals` | `target`, `numerator`, `denominator` | `target == numerator / denominator**power`, optional `power` (default 1), `tolerance` |
| `date_offset_equals` | `base`, `offset_days_field`, `target` | `target == base + timedelta(days=offset_days_field)`, optional `tolerance_days` |
| `date_diff_equals` | `start`, `end`, `target` | `target == (end - start).days`, optional `tolerance_days` |
| `comparison_equals` | `target`, `left`, `op` | `target == (left <op> right)`; exactly one of `right` (a field) or `right_value` (a literal) |
| `piecewise_lookup` | `source`, `target`, `breakpoints`, `otherwise` | `target` matches the bucket `source` falls into — see below |
| `requires` | `if_field`, `then_field` | if the if-condition holds, `then_field` is set (and optionally equals `then_value`) |
| `forbidden_if` | `if_field`, `then_fields: [...]` | if the if-condition holds, every field in `then_fields` must be `None` (or in `then_allowed_values`) |
| `any_of_implies` | `target`, `conditions: [...]` | `target == True` if any condition holds, else `False` |
| `conditional_equals` | `if_field`, `target`, `value_if_true`, `value_if_false` | `target` equals one of two values depending on the if-condition |
Every field name used in a rule must exist on the named table, or
`parse_spec` raises `ValueError` before anything is generated.
All optional keys accept `message` to override the generated default.
**The if-condition language**, shared by `requires`, `forbidden_if`, and
`conditional_equals`:
- no `if_value` → `if_field` must be truthy
- scalar `if_value` → `if_field` must equal it
- list `if_value` → `if_field` must be a member
- `if_op` (`eq`/`lt`/`le`/`gt`/`ge`) + numeric `if_value` → that comparison
A string `if_value`/`then_value`/`then_allowed_values` compared against an
**enum field** is uppercased automatically, so `if_value: severa` in YAML
correctly matches the stored `SEVERA` — write YAML values in whatever
case reads naturally.
**`piecewise_lookup` breakpoints**, ascending and non-overlapping:
```yaml
- kind: piecewise_lookup
source: edad_meses
target: ventana_madurativa
breakpoints:
- {max: 23.9, value: v1_16_23}
- {max: 30.9, value: v2_24_30}
- {max: 36.0, value: v3_31_36}
otherwise: fuera_de_rango
```
If `target` is an enum field, every breakpoint `value` and `otherwise`
must be a real member of that enum — checked at parse time.
**`any_of_implies` conditions**, each `{field, op[, value]}` with
`op` one of `truthy`/`eq`/`lt`/`le`/`gt`/`ge` (`truthy` needs no `value`):
```yaml
- kind: any_of_implies
target: flag_riesgo_neonatal
conditions:
- {field: apgar_5min, op: lt, value: 7}
- {field: ingreso_ucin, op: truthy}
```
## Generating
@@ -104,14 +199,15 @@ in-process or load it from disk later.
## Loading data at runtime
```python
from generated.schema import Base, TestTable
from generated.validation import TestTableCheck
from ps_core.runtime import ingest, check_foreign_keys
from generated.schema import Base, TestTable, ForeignTable
from generated.validation import TestTableCheck, ForeignTableCheck
from ps_core.runtime import ingest, check_foreign_keys, check_unique_fields
from ps_core.parse_spec import parse_spec
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
parsed_tables, _, _ = parse_spec("spec")
class_lookup = {"test_table": TestTable, "foreign_table": ForeignTable}
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
@@ -121,11 +217,92 @@ with Session(engine) as session:
session.add(row)
session.commit()
check_foreign_keys(session, parsed_tables, {"test_table": TestTable, "foreign_table": ForeignTable})
check_foreign_keys(session, parsed_tables, class_lookup)
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
```
`validate_row` (used inside `ingest`) takes and returns plain data, so it
is safe to run in a separate worker process — only `check_cls` needs to
be importable by name on both sides. `load_row` and `check_foreign_keys`
must run in the process that owns the database session.
be importable by name on both sides. `load_row`, `check_foreign_keys`,
and `check_unique_fields` must run in the process that owns the database
session.
## The shape of a stored error
`errors` is a JSON object, one entry per failed field (or `_cross_field`
for a cross rule). Each entry is `{"rule": <name>, "message": <text>}`:
```json
{
"field2": {"rule": "range", "message": "field2 must be between 1 and 10, got 99"},
"_cross_field": {"rule": "requires", "message": "field3 is required when field6 is true"}
}
```
`rule` is never parsed back out of the message — every check in
`constraints.py` and every cross-rule kind raises
`pydantic_core.PydanticCustomError(rule_name, ...)`, which is still a
real `ValueError` (so `except ValueError` keeps working everywhere), but
also sets `e.errors()[i]["type"]` to that exact rule name.
`ps_core.runtime.validate_row` reads that field directly. `foreign_key`
and `unique` set the same `rule` key by hand, in
`check_foreign_keys`/`check_unique_fields`, since neither ever goes
through Pydantic at all.
## A note on cross-rule messages
Field-level rules (`required`, `range`, `regex`, and so on) never take a
custom message — see "Field rules" above. Cross-field rules are
different: each one describes a genuinely distinct relationship between
fields, so a single generic template can't cover them all. Their
optional `message` key is inserted into the generated file as a plain
string literal (safely `repr()`'d), regardless of what characters it
contains — no injection risk from quotes or braces in the text.
## Synthetic data for development (`ps_core.devdata`)
Not imported by anything else in `ps_core` — a separate subpackage for
generating good and deliberately-bad data against a spec, for local
development and testing. Its own dependency direction: it reads
`parse_spec`'s output and calls into `ps_core.runtime`, never the other
way around, so a plain `pip install ps_core` needs none of it.
```bash
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated
```
`--generated-dir` points at wherever `build.py` (or `generate_all`)
already wrote `schema.py`/`validation.py`/`enums.py` — this script
imports the real classes rather than reconstruct them, and does not
regenerate anything itself.
Runs in five phases, across every table together — not table by table —
so table order never matters, even with circular or self-referential
foreign keys: build every table's skeleton row (every field except
foreign keys) → backfill every foreign key, now that every table has
rows → run real validation → check foreign keys → check unique fields.
Four independent rate flags, each an independent coin flip per row (a
single row can be more than one of these at once):
| flag | default | what it does |
|---|---|---|
| `--count` | `20` | rows generated per table |
| `--orphan-rate` | `0.0` | fraction of rows whose foreign key(s) point at nothing on purpose |
| `--faulty-rate` | `0.0` | fraction of rows with one randomly chosen field deliberately breaking its own rule |
| `--repeated-rate` | `0.0` | fraction of rows whose `unique: true` field(s) are copied from an earlier row, on purpose |
```bash
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated \
--count 100 --orphan-rate 0.3 --faulty-rate 0.3 --repeated-rate 0.2
```
`devdata.good` builds values by reading `field["checks"]` directly — no
retries, no calls into Pydantic, every value correct by construction.
`devdata.faulty` breaks one field's own rule the same deterministic way.
Only cross-field-rule violations need Pydantic at all
(`faulty_row_for_cross_rule`): since a cross rule's condition lives in
generated code, not in any field's `checks`, there's nothing structured
to read, so that one function generates candidates and asks
`check_cls(**row)` to say when one actually violates the rule.
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "ps-core"
version = "0.1.0"
version = "0.2.1"
description = "YAML-driven generator for SQLAlchemy storage models, Pydantic validation contracts, and data dictionaries."
readme = "README.md"
requires-python = ">=3.10"
-1
View File
@@ -4,4 +4,3 @@ test_table:
if_value: true
then_field: field3
message: "field3 is required when field6 is true"
+4 -8
View File
@@ -8,29 +8,25 @@ fields:
field1:
type: text
required: true
unique: true
field2:
type: integer
rule: range
range: true
min: 1
max: 10
required: false
field3:
type: float
rule: range
range: true
min: 0.1
max: 1.0
required: false
field4:
type: date
rule: not_future
required: true
not_future: true
field5:
type: datetime
required: false
field6:
type: bool
required: false
field7:
type: enum
enum: test_enum
required: false
+84 -55
View File
@@ -1,60 +1,89 @@
# -*- coding: utf-8 -*-
"""
Reusable Pydantic field constraints.
Composable validation primitives.
These are written once, by hand, and imported by every generated
validation file. They are never regenerated.
Each raises pydantic_core.PydanticCustomError, not a plain ValueError.
PydanticCustomError IS a ValueError (so every existing `except ValueError`
/ `pytest.raises(ValueError)` still works), but it also carries the rule
name as a real field — e.errors()[i]["type"] — instead of forcing anyone
downstream to parse it back out of the message text. The first argument
to PydanticCustomError below is that rule name; keep it stable, since
ps_core.runtime.validate_row stores it alongside the message.
The message wording is still built here, from a `label` (normally the
field name, passed in automatically by the generated checker function).
To change the wording for every field that uses a given rule, edit the
template string here once.
"""
from __future__ import annotations
import re as _re
from datetime import date
from typing import Annotated, Optional
from pydantic import AfterValidator, BeforeValidator, StringConstraints
from pydantic_core import PydanticCustomError
def RangeInt(lo: int, hi: int, label: str = "value"):
"""Integer, checked to fall within [lo, hi] inclusive."""
def _check(v: int) -> int:
if v < lo or v > hi:
raise ValueError(f"{label} must be between {lo} and {hi}, got {v}")
return v
return Annotated[int, AfterValidator(_check)]
def RangeFloat(lo: float, hi: float, label: str = "value"):
"""Float, checked to fall within [lo, hi] inclusive."""
def _check(v: float) -> float:
if v < lo or v > hi:
raise ValueError(f"{label} must be between {lo} and {hi}, got {v}")
return v
return Annotated[float, AfterValidator(_check)]
def RegexStr(pattern: str):
"""String, checked against a regex pattern."""
return Annotated[str, StringConstraints(pattern=pattern)]
def MaxLenStr(n: int):
"""String, checked to not exceed n characters."""
return Annotated[str, StringConstraints(max_length=n)]
def check_not_future(v: date) -> date:
if v > date.today():
raise ValueError(f"{v} is a future date")
def apply_strip(v):
"""Transform. Never raises."""
if isinstance(v, str):
return v.strip()
return v
NotFutureDate = Annotated[date, AfterValidator(check_not_future)]
def apply_upper(v):
"""Transform. Never raises."""
if isinstance(v, str):
return v.upper()
return v
def coerce_bool(v):
def check_required(v, label: str = "value"):
if v is None:
raise PydanticCustomError("required", "{label} is required", {"label": label})
return v
def check_range(v, lo, hi, label: str = "value"):
if v < lo or v > hi:
raise PydanticCustomError(
"range", "{label} must be between {lo} and {hi}, got {v}", {"label": label, "lo": lo, "hi": hi, "v": v}
)
return v
def check_not_future(v: date, label: str = "value"):
if v > date.today():
raise PydanticCustomError("not_future", "{label} must not be a future date, got {v}", {"label": label, "v": v})
return v
def check_regex(v: str, pattern: str, label: str = "value"):
if not _re.fullmatch(pattern, v):
raise PydanticCustomError(
"regex", "{label} does not match the expected format, got {v}", {"label": label, "v": v}
)
return v
def check_max_length(v: str, max_length: int, label: str = "value"):
if len(v) > max_length:
raise PydanticCustomError(
"max_length",
"{label} exceeds {max_length} characters, got {length}",
{"label": label, "max_length": max_length, "length": len(v)},
)
return v
def coerce_bool(v, label: str = "value"):
"""
Accepts True/False, 0/1, '0'/'1' (leading/trailing space tolerated).
Returns None unchanged — pair this with check_required if the field
must not be empty.
"""
if v is None:
return None
if isinstance(v, bool):
@@ -63,26 +92,26 @@ def coerce_bool(v):
return bool(v)
if isinstance(v, str) and v.strip() in ("0", "1"):
return bool(int(v.strip()))
raise ValueError(f"unrecognized type for boolean field: {type(v)}")
FlexBool = Annotated[Optional[bool], BeforeValidator(coerce_bool)]
raise PydanticCustomError(
"bool_coercion",
"{label}: unrecognized type for boolean field: {type_name}",
{"label": label, "type_name": str(type(v))},
)
def normalize_enum(v):
"""Shared BeforeValidator for every generated enum field: strip + uppercase."""
"""Transform. Never raises. Shared first step for every generated enum field."""
if v is None:
return None
return str(v).strip().upper()
def check_enum(enum_cls):
"""Shared AfterValidator factory for every generated enum field."""
def _check(v):
if v not in enum_cls.__members__.values():
allowed = ", ".join(m.value for m in enum_cls)
raise ValueError(f"value must be one of: {allowed}, got {v!r}")
return v
return _check
def check_enum_membership(v, enum_cls, label: str = "value"):
allowed = {m.value for m in enum_cls}
if v not in allowed:
raise PydanticCustomError(
"enum_membership",
"{label} must be one of: {allowed}, got {v}",
{"label": label, "allowed": sorted(allowed), "v": v},
)
return enum_cls(v)
View File
+95
View File
@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
"""
Builds rows that fail exactly one named thing: a single field's own
rule (deterministic, no Pydantic involved), a foreign key (orphaned on
purpose), or a specific cross-field rule (needs Pydantic as an oracle,
since a cross rule's condition lives in generated code, not in any
field's checks).
"""
from __future__ import annotations
import random
import uuid
from datetime import date, timedelta
from typing import Any
from pydantic import ValidationError
from ps_core.devdata.good import good_skeleton_row, good_value
def break_field(field: dict[str, Any]) -> Any:
"""Deterministically violate ONE field's own rule set."""
checks = {c["kind"]: c for c in field["checks"]}
if "required" in checks:
return None
if "range" in checks:
return checks["range"]["max"] + 1
if "max_length" in checks:
return "x" * (checks["max_length"]["max_length"] + 1)
if "regex" in checks:
return "###invalid###"
if "not_future" in checks:
return date.today() + timedelta(days=1)
if field["pydantic_type"] == "EnumField":
return "NOT_A_REAL_MEMBER"
if field["py_type"] == "bool":
return "nonsense"
raise ValueError(f"break_field: '{field['field_name']}' has no rule to break")
def faulty_skeleton_row(
table_spec: dict[str, Any], enums_by_name: dict[str, dict], field_name: str
) -> dict[str, Any]:
"""A good skeleton row except `field_name`, which deliberately fails its own rule."""
row = good_skeleton_row(table_spec, enums_by_name)
target = next(f for f in table_spec["fields"] if f["field_name"] == field_name)
row[field_name] = break_field(target)
return row
def faulty_foreign_key() -> str:
"""A well-formed id that (almost certainly) points at nothing."""
return str(uuid.uuid4())
def faulty_row_for_cross_rule(
table_spec: dict[str, Any],
check_cls: type,
enums_by_name: dict[str, dict],
cross_rule: dict[str, Any] | None = None,
tries: int = 50,
) -> dict[str, Any]:
"""
No single field to break deterministically here — a cross rule
relates fields to each other. Keep nudging fields on an otherwise-good
row until Pydantic raises a cross-rule error (empty `loc`).
Pass `cross_rule` (one entry from cross_rules_spec[table_name]) to
only touch the fields that specific rule actually references, rather
than nudging at random and hoping to hit it.
"""
if cross_rule is not None:
from ps_core.parse_spec import _referenced_fields_for_kind
candidate_names = _referenced_fields_for_kind(cross_rule["kind"], cross_rule)
candidates = [f for f in table_spec["fields"] if f["field_name"] in candidate_names]
else:
candidates = [f for f in table_spec["fields"] if not f["primary_key"] and not f["foreign_key"]]
for _ in range(tries):
row = good_skeleton_row(table_spec, enums_by_name)
target = random.choice(candidates)
row[target["field_name"]] = good_value(target, enums_by_name) # re-roll: may drift out of the relationship
try:
check_cls(**row)
except ValidationError as e:
if any(not err["loc"] for err in e.errors()): # cross-rule errors carry no field location
return row
raise RuntimeError(
f"faulty_row_for_cross_rule: no violation found in {tries} tries — "
f"try more, or pass a narrower `cross_rule`"
)
+211
View File
@@ -0,0 +1,211 @@
# -*- coding: utf-8 -*-
"""
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated --count 100 --orphan-rate 0.3 --faulty-rate 0.5 --repeated-rate 0.2
Fills every table in the spec with synthetic data — good rows, with
optional fractions of deliberately orphaned foreign keys, deliberately
broken field values, and deliberately repeated (duplicate) values on
any field marked `unique: true`. Everything needed to know *what* to
generate comes from --spec-dir; --generated-dir only points at where
build.py already wrote schema.py/validation.py/enums.py, so this script
can import the real classes rather than reconstruct them.
Runs in five phases, across ALL tables together — not table by table —
which is what lets table order stay irrelevant even with circular or
self-referential foreign keys:
1. Skeleton rows for every table (every field except FK), inserted
with FK fields absent. A --faulty-rate fraction of rows get one
randomly chosen field deliberately broken; a --repeated-rate
fraction of rows get their unique-marked field(s) copied from an
earlier row in the same table, on purpose.
2. Every foreign key backfilled — good (a real parent id) or
deliberately orphaned — now that every table already has rows.
3. Real validation against the now-complete row, same as
ps_core.runtime.ingest would do for real data.
4. Foreign keys checked, catching orphans phase 3 structurally cannot.
5. Unique fields checked, catching the repeats from phase 1 the same way.
"""
from __future__ import annotations
import argparse
import importlib
import random
import sys
from pathlib import Path
from typing import Any
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from ps_core.devdata.faulty import break_field, faulty_foreign_key
from ps_core.devdata.good import good_foreign_key, good_skeleton_row
from ps_core.parse_spec import parse_spec
from ps_core.runtime import check_foreign_keys, check_unique_fields, load_row, validate_row
def _import_generated(generated_dir: Path):
generated_dir = generated_dir.resolve()
pkg_name = generated_dir.name
sys.path.insert(0, str(generated_dir.parent))
try:
schema = importlib.import_module(f"{pkg_name}.schema")
validation = importlib.import_module(f"{pkg_name}.validation")
finally:
sys.path.remove(str(generated_dir.parent))
return schema, validation
def _build_lookups(parsed_tables, schema_mod, validation_mod):
class_lookup, check_lookup = {}, {}
for table_spec in parsed_tables:
class_name = table_spec["table"]["class_name"]
table_name = table_spec["table"]["table_name"]
class_lookup[table_name] = getattr(schema_mod, class_name)
check_lookup[table_name] = getattr(validation_mod, f"{class_name}Check")
return class_lookup, check_lookup
def _breakable_fields(table_spec: dict) -> list[dict]:
"""Fields break_field actually knows how to break — see faulty.py."""
return [
f for f in table_spec["fields"]
if f["checks"] or f["pydantic_type"] == "EnumField" or f["py_type"] == "bool"
]
def fill_all(
session: Any,
parsed_tables: list[dict],
enums_by_name: dict[str, dict],
class_lookup: dict[str, type],
check_lookup: dict[str, type],
count: int,
orphan_rate: float,
faulty_rate: float,
repeated_rate: float,
) -> None:
rows_by_table: dict[str, list] = {}
# phase 1: skeletons for every table, any order, FK fields absent.
# faulty_rate breaks one field's own rule; repeated_rate copies a
# unique-marked field's value from an earlier row, on purpose.
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
table_cls = class_lookup[table_name]
breakable = _breakable_fields(table_spec)
unique_fields = [f["field_name"] for f in table_spec["fields"] if f["unique"]]
raw_rows: list[dict] = []
rows = []
for _ in range(count):
raw = good_skeleton_row(table_spec, enums_by_name)
if unique_fields and raw_rows and random.random() < repeated_rate:
source = random.choice(raw_rows)
for uf in unique_fields:
if uf in raw: # a unique field could itself be a foreign key, absent here
raw[uf] = source[uf]
if breakable and random.random() < faulty_rate:
target = random.choice(breakable)
raw[target["field_name"]] = break_field(target)
raw_rows.append(raw)
row = load_row(raw, table_cls)
session.add(row)
rows.append(row)
rows_by_table[table_name] = rows
session.commit()
print(f" inserted {count} skeleton row(s) each, across {len(parsed_tables)} table(s)")
# phase 2: backfill every foreign key, now that every table has rows
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
fk_fields = [f for f in table_spec["fields"] if f["foreign_key"]]
if not fk_fields:
continue
for row in rows_by_table[table_name]:
make_orphan = random.random() < orphan_rate
for f in fk_fields:
target_table, target_col = f["foreign_key"].split(".", 1)
value = (
faulty_foreign_key()
if make_orphan
else good_foreign_key(session, class_lookup[target_table], target_col)
)
setattr(row, f["field_name"], value)
session.commit()
print(" backfilled foreign keys")
# phase 3: real validation, now that every row is actually complete
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
check_cls = check_lookup[table_name]
for row in rows_by_table[table_name]:
raw = {
f["field_name"]: getattr(row, f["field_name"])
for f in table_spec["fields"] if not f["primary_key"]
}
result = validate_row(raw, check_cls)
row.validated = result["validated"]
row.errors = result["errors"]
session.commit()
print(" validated every row")
# phase 4: catch what phase 3 structurally cannot — foreign keys
check_foreign_keys(session, parsed_tables, class_lookup)
session.commit()
print(" checked foreign keys")
# phase 5: catch what phase 3 structurally cannot — uniqueness
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
print(" checked unique fields")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec-dir", type=Path, required=True)
parser.add_argument(
"--generated-dir", type=Path, required=True,
help="where build.py wrote schema.py/validation.py/enums.py",
)
parser.add_argument("--db-url", default="sqlite:///dev.db")
parser.add_argument("--count", type=int, default=20, help="rows per table")
parser.add_argument("--orphan-rate", type=float, default=0.0, help="fraction of rows with a deliberately bad FK")
parser.add_argument("--faulty-rate", type=float, default=0.0, help="fraction of rows with one deliberately broken field")
parser.add_argument(
"--repeated-rate", type=float, default=0.0,
help="fraction of rows with unique-marked field(s) deliberately duplicated from an earlier row",
)
args = parser.parse_args()
print(f"Parsing spec from {args.spec_dir} ...")
try:
parsed_tables, enums_spec, _ = parse_spec(args.spec_dir)
except (ValueError, FileNotFoundError) as e:
print(f"\nSpec error: {e}", file=sys.stderr)
sys.exit(1)
enums_by_name = {e["name"]: e for e in enums_spec}
print(f"Importing generated code from {args.generated_dir} ...")
schema_mod, validation_mod = _import_generated(args.generated_dir)
class_lookup, check_lookup = _build_lookups(parsed_tables, schema_mod, validation_mod)
engine = create_engine(args.db_url, echo=False)
schema_mod.Base.metadata.create_all(engine)
print(f"Filling {len(parsed_tables)} table(s), {args.count} row(s) each, into {args.db_url} ...")
with Session(engine) as session:
fill_all(
session, parsed_tables, enums_by_name, class_lookup, check_lookup,
args.count, args.orphan_rate, args.faulty_rate, args.repeated_rate,
)
print("Done.")
if __name__ == "__main__":
main()
+77
View File
@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
"""
Builds plausible, rule-respecting values — read directly from
field["checks"], never by asking Pydantic to accept-or-reject. Fast and
deterministic: every value is correct by construction, no retries.
Foreign key fields are deliberately left out of every row built here —
see fill.py for why, and for how they get filled in afterward.
"""
from __future__ import annotations
import random
import string
from datetime import date, datetime, timedelta
from typing import Any
def _sample_text(field_name: str, checks: dict[str, dict]) -> str:
if "regex" in checks:
raise ValueError(
f"good_value: no generic sampler for a regex pattern on '{field_name}' "
f"({checks['regex']['pattern']!r}) — write a per-field generator for "
f"this field and call it instead of good_value for it"
)
max_length = checks.get("max_length", {}).get("max_length", 20)
length = random.randint(1, max(1, min(max_length, 20)))
return "".join(random.choices(string.ascii_letters, k=length))
def good_value(field: dict[str, Any], enums_by_name: dict[str, dict]) -> Any:
"""One plausible value for a single field, respecting every check it declares."""
checks = {c["kind"]: c for c in field["checks"]}
if field["pydantic_type"] == "EnumField":
elements = enums_by_name[field["enum_ref"]]["elements"]
return random.choice(elements)
if field["py_type"] == "bool":
return random.choice([True, False])
if field["py_type"] == "date":
return date.today() - timedelta(days=random.randint(0, 3650)) # not_future satisfied by construction
if field["py_type"] == "datetime":
return datetime.now() - timedelta(days=random.randint(0, 3650))
if field["py_type"] in ("int", "float"):
if "range" in checks:
lo, hi = checks["range"]["min"], checks["range"]["max"]
return random.randint(lo, hi) if field["py_type"] == "int" else round(random.uniform(lo, hi), 4)
return random.randint(0, 100) if field["py_type"] == "int" else round(random.uniform(0, 100), 2)
return _sample_text(field["field_name"], checks) # text, uuid
def good_skeleton_row(table_spec: dict[str, Any], enums_by_name: dict[str, dict]) -> dict[str, Any]:
"""
Every field except the primary key and any foreign key. Deliberately
incomplete — fill.py inserts this, then backfills foreign keys once
parent rows actually exist.
"""
return {
f["field_name"]: good_value(f, enums_by_name)
for f in table_spec["fields"]
if not f["primary_key"] and not f["foreign_key"]
}
def good_foreign_key(session: Any, target_table_cls: type, target_col: str) -> Any:
"""A real id already sitting in the parent table."""
existing = session.query(getattr(target_table_cls, target_col)).all()
if not existing:
raise RuntimeError(
f"good_foreign_key: no rows in {target_table_cls.__tablename__} yet — "
f"insert that table's rows before backfilling links to it"
)
return random.choice(existing)[0]
+351 -62
View File
@@ -2,88 +2,364 @@
"""
Renders the validation.py file — the Pydantic check layer.
Per-field rules come straight from each table's field list (see
parse_spec.parse_single_table). Cross-field rules come from a table's
entry in cross_rules_spec (see parse_spec.parse_cross_rules) and are
turned into `@model_validator(mode="after")` methods here, from a fixed
set of safe, named rule kinds — never from a raw eval'd string.
Every field is generated as `Optional[T] = None`, with a single
module-level checker function (a BeforeValidator) doing whatever the
spec configured for that field, in the fixed order set by
parse_spec.CHECK_ORDER. "Required" is just one of those checks, like
any other. Each check raises a generic message built from the field's
own name (constraints.py owns the wording — see that module).
Cross-field rules come from a table's entry in cross_rules_spec (see
parse_spec.parse_cross_rules) and are turned into
`@model_validator(mode="after")` methods here, from the fixed, named
kind vocabulary in parse_spec.CROSS_RULE_SPECS — never from a raw eval'd
string.
"""
from __future__ import annotations
from typing import Any
from ps_core.parse_spec import OP_SYMBOLS
from ps_core.templating import env
INDENT = " "
# ---------------------------------------------------------------------------
# Per-field checker functions
# ---------------------------------------------------------------------------
def render_field_checker(table_class_name: str, field: dict[str, Any]) -> tuple[str, str]:
"""Returns (checker_function_source, field_declaration_line)."""
fn_name = f"_check_{table_class_name.lower()}_{field['field_name']}"
label = field["field_name"]
body: list[str] = []
if field["pydantic_type"] == "EnumField":
body.append("if v is not None:")
body.append(" v = normalize_enum(v)")
elif field["py_type"] == "bool":
body.append(f"v = coerce_bool(v, label={label!r})")
for check in field["checks"]:
kind = check["kind"]
if kind == "strip":
body.append("v = apply_strip(v)")
elif kind == "upper":
body.append("v = apply_upper(v)")
elif kind == "required":
body.append(f"v = check_required(v, label={label!r})")
elif kind == "max_length":
body.append("if v is not None:")
body.append(f" v = check_max_length(v, {check['max_length']!r}, label={label!r})")
elif kind == "regex":
body.append("if v is not None:")
body.append(f" v = check_regex(v, {check['pattern']!r}, label={label!r})")
elif kind == "range":
body.append("if v is not None:")
body.append(f" v = check_range(v, {check['min']!r}, {check['max']!r}, label={label!r})")
elif kind == "not_future":
body.append("if v is not None:")
body.append(f" v = check_not_future(v, label={label!r})")
if field["pydantic_type"] == "EnumField":
enum_class = field["enum_class"]
body.append("if v is not None:")
body.append(f" v = check_enum_membership(v, {enum_class}, label={label!r})")
body.append("return v")
indented = "\n".join(f" {line}" for line in body)
checker_source = f"def {fn_name}(v):\n{indented}\n"
type_annotation = field["enum_class"] if field["pydantic_type"] == "EnumField" else field["pydantic_type"]
field_line = f" {field['field_name']}: Annotated[Optional[{type_annotation}], BeforeValidator({fn_name})] = None"
return checker_source, field_line
# ---------------------------------------------------------------------------
# Cross-field rule renderers
# ---------------------------------------------------------------------------
def _wrap_method(name: str, body_lines: list[str]) -> str:
header = f" @model_validator(mode=\"after\")\n def {name}(self):\n"
body = "\n".join(f" {line}" for line in body_lines)
return f"{header}{body}\n return self\n"
def _condition_expr(field_name: str, rule: dict[str, Any]) -> str:
if "if_op" in rule:
op_symbol = OP_SYMBOLS[rule["if_op"]]
return f"self.{field_name} is not None and self.{field_name} {op_symbol} {rule['if_value']!r}"
if "if_value" in rule:
val = rule["if_value"]
if isinstance(val, list):
return f"self.{field_name} in {val!r}"
return f"self.{field_name} == {val!r}"
return f"bool(self.{field_name})"
def _render_single_condition(c: dict[str, Any]) -> str:
field = c["field"]
if c["op"] == "truthy":
return f"bool(self.{field})"
op_symbol = OP_SYMBOLS[c["op"]]
return f"(self.{field} is not None and self.{field} {op_symbol} {c['value']!r})"
def _raise(error_type: str, template: str, context_src: str, indent: str = " ") -> str:
"""
One line: raise PydanticCustomError(error_type, template, context).
error_type becomes e.errors()[i]["type"] at runtime — the rule name,
kept as data, not parsed back out of the message text. context_src
is already-built dict-literal source (e.g. "{\'_msg\': _msg, \'left\': self.a}").
"""
return f"{indent}raise PydanticCustomError({error_type!r}, {template!r}, {context_src})"
def _render_order(rule: dict[str, Any], name: str) -> str:
left, right = rule["fields"]
op_symbol = {"le": "<=", "lt": "<", "ge": ">=", "gt": ">"}[rule["op"]]
op_symbol = OP_SYMBOLS[rule["op"]]
msg = rule.get("message") or rule["display"]
return (
f"{INDENT}@model_validator(mode=\"after\")\n"
f"{INDENT}def {name}(self):\n"
f"{INDENT*2}if self.{left} is not None and self.{right} is not None:\n"
f"{INDENT*3}if not (self.{left} {op_symbol} self.{right}):\n"
f"{INDENT*4}raise ValueError(f\"{msg}: {{self.{left}}} vs {{self.{right}}}\")\n"
f"{INDENT*2}return self\n"
)
def _render_sum_equals(rule: dict[str, Any], name: str) -> str:
target = rule["target"]
parts = rule["parts"]
tolerance = rule.get("tolerance", 0)
sum_expr = " + ".join(f"self.{p}" for p in parts)
none_checks = " and ".join(f"self.{p} is not None" for p in parts)
msg = rule.get("message") or rule["display"]
return (
f"{INDENT}@model_validator(mode=\"after\")\n"
f"{INDENT}def {name}(self):\n"
f"{INDENT*2}if self.{target} is not None and {none_checks}:\n"
f"{INDENT*3}_expected = {sum_expr}\n"
f"{INDENT*3}if abs(self.{target} - _expected) > {tolerance!r}:\n"
f"{INDENT*4}raise ValueError(f\"{msg}: got {{self.{target}}}, expected {{_expected}}\")\n"
f"{INDENT*2}return self\n"
)
def _render_requires(rule: dict[str, Any], name: str) -> str:
if_field = rule["if_field"]
then_field = rule["then_field"]
msg = rule.get("message") or rule["display"]
if "if_value" in rule:
cond = f"self.{if_field} == {rule['if_value']!r}"
else:
cond = f"self.{if_field}"
return (
f"{INDENT}@model_validator(mode=\"after\")\n"
f"{INDENT}def {name}(self):\n"
f"{INDENT*2}if {cond} and self.{then_field} is None:\n"
f"{INDENT*3}raise ValueError({msg!r})\n"
f"{INDENT*2}return self\n"
)
body = [
f"_msg = {msg!r}",
f"if self.{left} is not None and self.{right} is not None:",
f" if not (self.{left} {op_symbol} self.{right}):",
_raise("order", "{_msg}: {left} vs {right}", f"{{'_msg': _msg, 'left': self.{left}, 'right': self.{right}}}"),
]
return _wrap_method(name, body)
def _render_equals(rule: dict[str, Any], name: str) -> str:
a, b = rule["fields"]
msg = rule.get("message") or rule["display"]
return (
f"{INDENT}@model_validator(mode=\"after\")\n"
f"{INDENT}def {name}(self):\n"
f"{INDENT*2}if self.{a} is not None and self.{b} is not None:\n"
f"{INDENT*3}if self.{a} != self.{b}:\n"
f"{INDENT*4}raise ValueError(f\"{msg}: {{self.{a}}} vs {{self.{b}}}\")\n"
f"{INDENT*2}return self\n"
)
body = [
f"_msg = {msg!r}",
f"if self.{a} is not None and self.{b} is not None:",
f" if self.{a} != self.{b}:",
_raise("equals", "{_msg}: {a} vs {b}", f"{{'_msg': _msg, 'a': self.{a}, 'b': self.{b}}}"),
]
return _wrap_method(name, body)
def _render_sum_equals(rule: dict[str, Any], name: str) -> str:
target, parts, tol = rule["target"], rule["parts"], rule.get("tolerance", 0)
sum_expr = " + ".join(f"self.{p}" for p in parts)
none_checks = " and ".join(f"self.{p} is not None" for p in parts)
msg = rule.get("message") or rule["display"]
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and {none_checks}:",
f" _expected = {sum_expr}",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"sum_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
return _wrap_method(name, body)
def _render_ratio_equals(rule: dict[str, Any], name: str) -> str:
target, num, den = rule["target"], rule["numerator"], rule["denominator"]
power, tol = rule.get("power", 1), rule.get("tolerance", 0)
denom_expr = f"self.{den}" + (f" ** {power}" if power != 1 else "")
msg = rule.get("message") or rule["display"]
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{num} is not None and self.{den} not in (None, 0):",
f" _expected = self.{num} / ({denom_expr})",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"ratio_equals", "{_msg}: got {got}, expected {expected:.4f}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
return _wrap_method(name, body)
def _render_date_offset_equals(rule: dict[str, Any], name: str) -> str:
base, offset, target = rule["base"], rule["offset_days_field"], rule["target"]
tol = rule.get("tolerance_days", 0)
msg = rule.get("message") or rule["display"]
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{base} is not None and self.{offset} is not None:",
f" _expected = self.{base} + timedelta(days=self.{offset})",
f" if abs((self.{target} - _expected).days) > {tol!r}:",
_raise(
"date_offset_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
return _wrap_method(name, body)
def _render_date_diff_equals(rule: dict[str, Any], name: str) -> str:
start, end, target = rule["start"], rule["end"], rule["target"]
tol = rule.get("tolerance_days", 0)
msg = rule.get("message") or rule["display"]
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{start} is not None and self.{end} is not None:",
f" _expected = (self.{end} - self.{start}).days",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"date_diff_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
return _wrap_method(name, body)
def _render_comparison_equals(rule: dict[str, Any], name: str) -> str:
target, left, op = rule["target"], rule["left"], rule["op"]
op_symbol = OP_SYMBOLS[op]
tol = rule.get("tolerance", 0)
msg = rule.get("message") or rule["display"]
if "right" in rule:
right_field = rule["right"]
right_expr = f"self.{right_field}"
guard = f"self.{target} is not None and self.{left} is not None and self.{right_field} is not None"
else:
right_expr = repr(rule["right_value"])
guard = f"self.{target} is not None and self.{left} is not None"
if op == "eq" and tol:
cond_expr = f"abs(self.{left} - {right_expr}) <= {tol!r}"
else:
cond_expr = f"self.{left} {op_symbol} {right_expr}"
body = [
f"_msg = {msg!r}",
f"if {guard}:",
f" _expected = bool({cond_expr})",
f" if bool(self.{target}) != _expected:",
_raise(
"comparison_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
return _wrap_method(name, body)
def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
source, target = rule["source"], rule["target"]
breakpoints, otherwise = rule["breakpoints"], rule["otherwise"].upper()
msg = rule.get("message") or rule["display"]
branch: list[str] = []
for i, bp in enumerate(breakpoints):
kw = "if" if i == 0 else "elif"
branch.append(f" {kw} self.{source} <= {bp['max']!r}:")
branch.append(f" _expected = {bp['value'].upper()!r}")
branch.append(" else:")
branch.append(f" _expected = {otherwise!r}")
body = [f"_msg = {msg!r}", f"if self.{source} is not None and self.{target} is not None:"]
body += branch
body.append(f" _actual = getattr(self.{target}, 'value', self.{target})")
body.append(" if _actual != _expected:")
body.append(
_raise(
"piecewise_lookup", "{_msg}: got {got}, expected {expected} for " + source + "={source_value}",
f"{{'_msg': _msg, 'got': _actual, 'expected': _expected, 'source_value': self.{source}}}",
)
)
return _wrap_method(name, body)
def _render_requires(rule: dict[str, Any], name: str) -> str:
if_field, then_field = rule["if_field"], rule["then_field"]
msg = rule.get("message") or rule["display"]
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
if "then_value" in rule:
then_val = rule["then_value"]
body.append(f" if self.{then_field} is None or self.{then_field} != {then_val!r}:")
else:
body.append(f" if self.{then_field} is None:")
body.append(
_raise(
"requires", "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{then_field}}}",
)
)
return _wrap_method(name, body)
def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
if_field, then_fields = rule["if_field"], rule["then_fields"]
allowed_values = [v.upper() if isinstance(v, str) else v for v in rule.get("then_allowed_values", [])]
msg = rule.get("message") or rule["display"]
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
for tf in then_fields:
body.append(f" _val = getattr(self.{tf}, 'value', self.{tf})")
body.append(f" if _val is not None and _val not in {allowed_values!r}:")
body.append(
_raise(
"forbidden_if", "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{tf}, 'value': _val}}",
)
)
return _wrap_method(name, body)
def _render_any_of_implies(rule: dict[str, Any], name: str) -> str:
target = rule["target"]
msg = rule.get("message") or rule["display"]
cond_exprs = [_render_single_condition(c) for c in rule["conditions"]]
body = [f"_msg = {msg!r}", "_components = ("]
body += [f" {ce}," for ce in cond_exprs]
body.append(")")
body.append(f"if self.{target} is not None:")
body.append(" _expected = any(_components)")
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"any_of_implies", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
return _wrap_method(name, body)
def _render_conditional_equals(rule: dict[str, Any], name: str) -> str:
if_field, target = rule["if_field"], rule["target"]
value_if_true, value_if_false = rule["value_if_true"], rule["value_if_false"]
tol = rule.get("tolerance", 0)
msg = rule.get("message") or rule["display"]
cond = _condition_expr(if_field, rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None:",
f" _expected = ({value_if_true!r} if ({cond}) else {value_if_false!r})",
]
if tol:
body.append(f" if abs(self.{target} - _expected) > {tol!r}:")
else:
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"conditional_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
return _wrap_method(name, body)
_RENDERERS = {
"order": _render_order,
"sum_equals": _render_sum_equals,
"requires": _render_requires,
"equals": _render_equals,
"sum_equals": _render_sum_equals,
"ratio_equals": _render_ratio_equals,
"date_offset_equals": _render_date_offset_equals,
"date_diff_equals": _render_date_diff_equals,
"comparison_equals": _render_comparison_equals,
"piecewise_lookup": _render_piecewise_lookup,
"requires": _render_requires,
"forbidden_if": _render_forbidden_if,
"any_of_implies": _render_any_of_implies,
"conditional_equals": _render_conditional_equals,
}
@@ -101,13 +377,26 @@ def render_cross_rules_code(rules: list[dict[str, Any]]) -> str:
return "\n" + "\n".join(render_cross_rule(r, i) for i, r in enumerate(rules))
# ---------------------------------------------------------------------------
# Assembly
# ---------------------------------------------------------------------------
def generate_validation_class(
table_spec: dict[str, Any], cross_rules: list[dict[str, Any]] | None = None
) -> str:
table = table_spec["table"]
checker_sources = []
field_lines = []
for field in table_spec["fields"]:
checker_source, field_line = render_field_checker(table["class_name"], field)
checker_sources.append(checker_source)
field_lines.append(field_line)
template = env.get_template("validation_class.jinja")
return template.render(
table=table_spec["table"],
fields=table_spec["fields"],
table=table,
checker_functions="\n".join(checker_sources),
field_lines="\n".join(field_lines),
cross_rules_code=render_cross_rules_code(cross_rules or []),
)
+449 -79
View File
@@ -20,12 +20,70 @@ Loading order matters and is enforced here:
3. foreign keys — checked once every table is parsed, since a
foreign key may point at a table defined in a
different file
4. cross_rules.yaml — each rule may reference fields on a table; the
table and its fields must already be known
4. cross_rules.yaml — each rule may reference fields (and, for some
kinds, enum members) on a table; these must
already be known
Every failure raises ValueError (or FileNotFoundError for a missing path)
with a message naming the offending file and field, so a broken spec is
never silently accepted.
--------------------------------------------------------------------------
Field rules
--------------------------------------------------------------------------
Every field is optional at the storage layer and optional in the
generated Pydantic contract (Optional[T] = None). "Required" is not a
type-level distinction here — it is one rule among several.
A field activates a rule by giving it a truthy value (or, for `regex`
and `max_length`, the parameter itself, since the value doubles as the
flag):
field_name:
type: text
required: true
strip: true
upper: true
max_length: 100
regex: "[A-Z]{3}"
Rules are applied in a fixed order — strip, upper, required, max_length,
regex, range, not_future — regardless of the order written in YAML.
Which rules are legal depends on the field's `type` (see
RULE_KEYS_BY_TYPE below); an illegal combination raises ValueError at
parse time, before any code is generated.
Each rule raises a generic message, built from the field's own name, by
the constraint function in constraints.py (e.g. "age must be between 1
and 10, got 15"). To change the wording, edit that function once — there
is no per-field message override in the spec YAML.
--------------------------------------------------------------------------
Cross-field rule kinds
--------------------------------------------------------------------------
See generate_validation.py for how each kind becomes a
`@model_validator(mode="after")` method. Supported kinds:
order — a <op> b (op: le/lt/ge/gt)
equals — a == b
sum_equals — target == sum(parts), within tolerance
ratio_equals — target == numerator / denominator**power, within tolerance
date_offset_equals — target == base + timedelta(days=offset_days_field)
date_diff_equals — target == (end - start).days, within tolerance_days
comparison_equals — target == (left <op> right_or_right_value)
piecewise_lookup — target == the bucket `source` falls into
requires — if <condition on if_field> then then_field is set
(and optionally equals then_value)
forbidden_if — if <condition on if_field> then every field in
then_fields must be None (or in then_allowed_values)
any_of_implies — target == True if any of `conditions` holds, else False
`requires` and `forbidden_if` share one small condition language for the
"if" side: with no `if_value`, the if_field must be truthy; with a
scalar `if_value`, it must equal it; with a list `if_value`, it must be
a member; with `if_op` (one of eq/lt/le/gt/ge) plus a numeric `if_value`,
it must satisfy that comparison. `any_of_implies` reuses the same
language per condition, plus a `truthy` op needing no value.
"""
from __future__ import annotations
@@ -60,22 +118,26 @@ PY_TYPES = {
"uuid": "str",
}
# Which `rule:` values are legal for which field type.
RULES_BY_TYPE = {
# Which rule keys are legal for which field type. `required` is legal
# everywhere; the rest are listed per type below.
RULE_KEYS_BY_TYPE = {
"text": {"strip", "upper", "regex", "max_length"},
"integer": {"range"},
"float": {"range"},
"date": {"not_future"},
"datetime": set(),
"bool": set(),
"enum": set(),
"uuid": {"strip"},
}
# Fixed application order — independent of the order written in YAML.
CHECK_ORDER = ["strip", "upper", "required", "max_length", "regex", "range", "not_future"]
VALID_ORDER_OPS = {"le", "lt", "ge", "gt"}
OP_SYMBOLS = {"le": "<=", "lt": "<", "ge": ">=", "gt": ">"}
CROSS_RULE_SPECS = {
"order": {"required": {"fields", "op"}, "optional": {"message"}},
"sum_equals": {"required": {"target", "parts"}, "optional": {"message", "tolerance"}},
"requires": {"required": {"if_field", "then_field"}, "optional": {"message", "if_value"}},
"equals": {"required": {"fields"}, "optional": {"message"}},
}
OP_SYMBOLS = {"le": "<=", "lt": "<", "ge": ">=", "gt": ">", "eq": "=="}
VALID_COMPARISON_OPS = {"eq", "lt", "le", "gt", "ge"}
VALID_CONDITION_OPS = {"eq", "lt", "le", "gt", "ge"} # for if_op / condition op (excluding "truthy")
def under_to_camel(name: str) -> str:
@@ -134,17 +196,92 @@ def parse_enums(enums_path: Path) -> list[dict[str, Any]]:
# ---------------------------------------------------------------------------
# tables/*.yaml
# tables/*.yaml — field rules
# ---------------------------------------------------------------------------
def build_rule_display(rule, min_val, max_val, pydantic_type, enum_ref) -> str | None:
if rule == "range":
return f"range [{min_val}, {max_val}]"
if rule == "not_future":
return "not a future date"
def _parse_field_checks(
yaml_path: Path, field_name: str, field_type: str, field_spec: dict[str, Any]
) -> list[dict[str, Any]]:
allowed = RULE_KEYS_BY_TYPE.get(field_type, set()) | {"required"}
present = {
key for key in ("required", "strip", "upper", "range", "not_future", "regex", "max_length")
if key in field_spec
}
illegal = present - allowed
if illegal:
raise ValueError(
f"{yaml_path}: field '{field_name}' of type '{field_type}' cannot use rule(s) "
f"{sorted(illegal)}"
)
checks: list[dict[str, Any]] = []
if field_spec.get("required", False):
checks.append({"kind": "required"})
if field_spec.get("strip", False):
checks.append({"kind": "strip"})
if field_spec.get("upper", False):
checks.append({"kind": "upper"})
if field_spec.get("range", False):
if "min" not in field_spec or "max" not in field_spec:
raise ValueError(f"{yaml_path}: field '{field_name}' has rule 'range' but is missing 'min' or 'max'")
lo, hi = field_spec["min"], field_spec["max"]
if not isinstance(lo, (int, float)) or not isinstance(hi, (int, float)):
raise ValueError(f"{yaml_path}: field '{field_name}' range min/max must be numbers")
if lo > hi:
raise ValueError(f"{yaml_path}: field '{field_name}' has min ({lo}) greater than max ({hi})")
checks.append({"kind": "range", "min": lo, "max": hi})
if field_spec.get("not_future", False):
checks.append({"kind": "not_future"})
if "max_length" in field_spec:
max_length = field_spec["max_length"]
if not isinstance(max_length, int) or isinstance(max_length, bool) or max_length <= 0:
raise ValueError(f"{yaml_path}: field '{field_name}' max_length must be a positive integer")
checks.append({"kind": "max_length", "max_length": max_length})
if "regex" in field_spec:
pattern = field_spec["regex"]
if not isinstance(pattern, str) or not pattern:
raise ValueError(f"{yaml_path}: field '{field_name}' regex must be a non-empty string")
import re as _re
try:
_re.compile(pattern)
except _re.error as e:
raise ValueError(f"{yaml_path}: field '{field_name}' has an invalid regex pattern: {e}")
checks.append({"kind": "regex", "pattern": pattern})
order = {kind: i for i, kind in enumerate(CHECK_ORDER)}
checks.sort(key=lambda c: order[c["kind"]])
return checks
def build_rule_display(checks: list[dict[str, Any]], pydantic_type: str, enum_ref: str | None) -> str | None:
parts = []
for check in checks:
kind = check["kind"]
if kind == "required":
continue # shown in its own "Required" column
elif kind == "strip":
parts.append("strip")
elif kind == "upper":
parts.append("upper")
elif kind == "range":
parts.append(f"range [{check['min']}, {check['max']}]")
elif kind == "not_future":
parts.append("not a future date")
elif kind == "max_length":
parts.append(f"max length {check['max_length']}")
elif kind == "regex":
parts.append(f"regex {check['pattern']!r}")
if pydantic_type == "EnumField":
return f"one of {enum_ref}"
return None
parts.append(f"one of {enum_ref}")
return ", ".join(parts) if parts else None
def parse_single_table(yaml_path: Path, enum_names: set[str]) -> dict[str, Any]:
@@ -182,26 +319,6 @@ def parse_single_table(yaml_path: Path, enum_names: set[str]) -> dict[str, Any]:
if field_spec.get("primary_key", False):
primary_keys.append(field_name)
rule = field_spec.get("rule", None)
if rule is not None and rule not in RULES_BY_TYPE.get(field_type, set()):
raise ValueError(
f"{yaml_path}: field '{field_name}' of type '{field_type}' cannot use rule '{rule}'"
)
min_val = max_val = None
if rule == "range":
if "min" not in field_spec or "max" not in field_spec:
raise ValueError(
f"{yaml_path}: field '{field_name}' has rule 'range' but is missing 'min' or 'max'"
)
min_val, max_val = field_spec["min"], field_spec["max"]
if not isinstance(min_val, (int, float)) or not isinstance(max_val, (int, float)):
raise ValueError(f"{yaml_path}: field '{field_name}' range min/max must be numbers")
if min_val > max_val:
raise ValueError(
f"{yaml_path}: field '{field_name}' has min ({min_val}) greater than max ({max_val})"
)
enum_class = None
enum_ref = None
pydantic_type = PY_TYPES[field_type]
@@ -210,12 +327,12 @@ def parse_single_table(yaml_path: Path, enum_names: set[str]) -> dict[str, Any]:
if not enum_ref:
raise ValueError(f"{yaml_path}: field '{field_name}' is type enum but has no 'enum' key")
if enum_ref not in enum_names:
raise ValueError(
f"{yaml_path}: field '{field_name}' references unknown enum '{enum_ref}'"
)
enum_class = under_to_camel(enum_ref) + "Field"
raise ValueError(f"{yaml_path}: field '{field_name}' references unknown enum '{enum_ref}'")
enum_class = under_to_camel(enum_ref)
pydantic_type = "EnumField"
checks = _parse_field_checks(yaml_path, field_name, field_type, field_spec)
foreign_key = field_spec.get("foreign_key", None)
if foreign_key is not None:
if not isinstance(foreign_key, str) or "." not in foreign_key:
@@ -224,23 +341,23 @@ def parse_single_table(yaml_path: Path, enum_names: set[str]) -> dict[str, Any]:
f"{foreign_key!r}, expected 'table.column'"
)
required = field_spec.get("required", False)
if not isinstance(required, bool):
raise ValueError(f"{yaml_path}: field '{field_name}' 'required' must be true or false")
unique = field_spec.get("unique", False)
if not isinstance(unique, bool):
raise ValueError(f"{yaml_path}: field '{field_name}' 'unique' must be true or false")
fields.append({
"field_name": field_name,
"py_type": PY_TYPES[field_type],
"pydantic_type": pydantic_type,
"enum_class": enum_class,
"enum_ref": enum_ref,
"sql_type": SQL_TYPES[field_type],
"primary_key": field_spec.get("primary_key", False),
"foreign_key": foreign_key,
"required": required,
"rule": rule,
"min": min_val,
"max": max_val,
"rule_display": build_rule_display(rule, min_val, max_val, pydantic_type, enum_ref),
"unique": unique,
"checks": checks,
"required": any(c["kind"] == "required" for c in checks),
"rule_display": build_rule_display(checks, pydantic_type, enum_ref),
})
if not primary_keys:
@@ -309,6 +426,75 @@ def validate_foreign_keys(parsed_tables: list[dict[str, Any]]) -> None:
# cross_rules.yaml
# ---------------------------------------------------------------------------
CROSS_RULE_SPECS = {
"order": {"required": {"fields", "op"}, "optional": {"message"}},
"equals": {"required": {"fields"}, "optional": {"message"}},
"sum_equals": {"required": {"target", "parts"}, "optional": {"message", "tolerance"}},
"ratio_equals": {
"required": {"target", "numerator", "denominator"},
"optional": {"message", "power", "tolerance"},
},
"date_offset_equals": {
"required": {"base", "offset_days_field", "target"},
"optional": {"message", "tolerance_days"},
},
"date_diff_equals": {
"required": {"start", "end", "target"},
"optional": {"message", "tolerance_days"},
},
"comparison_equals": {
"required": {"target", "left", "op"},
"optional": {"message", "right", "right_value", "tolerance"},
},
"piecewise_lookup": {
"required": {"source", "target", "breakpoints", "otherwise"},
"optional": {"message"},
},
"requires": {
"required": {"if_field", "then_field"},
"optional": {"message", "if_value", "if_op", "then_value"},
},
"forbidden_if": {
"required": {"if_field", "then_fields"},
"optional": {"message", "if_value", "if_op", "then_allowed_values"},
},
"any_of_implies": {"required": {"target", "conditions"}, "optional": {"message"}},
"conditional_equals": {
"required": {"if_field", "target", "value_if_true", "value_if_false"},
"optional": {"message", "if_value", "if_op", "tolerance"},
},
}
def _normalize_condition_value(value: Any, field: dict[str, Any]) -> Any:
"""
A field storing an enum keeps its value uppercased (see
constraints.normalize_enum). Condition values compared against that
field must be uppercased the same way, or a perfectly valid YAML
value like `severa` would silently never match the stored `SEVERA`.
Non-enum fields pass through unchanged.
"""
if field["pydantic_type"] != "EnumField":
return value
if isinstance(value, str):
return value.upper()
if isinstance(value, list):
return [v.upper() if isinstance(v, str) else v for v in value]
return value
def _validate_condition(path: Path, table_name: str, index: int, rule: dict[str, Any], field_names: set[str]) -> None:
"""Shared validation for the if_field/if_value/if_op condition language."""
if_field = rule["if_field"]
if if_field not in field_names:
raise ValueError(f"{path}: {table_name}[{index}] references unknown field '{if_field}'")
if "if_op" in rule:
if rule["if_op"] not in VALID_CONDITION_OPS:
raise ValueError(f"{path}: {table_name}[{index}] 'if_op' must be one of {sorted(VALID_CONDITION_OPS)}")
if "if_value" not in rule or not isinstance(rule["if_value"], (int, float)):
raise ValueError(f"{path}: {table_name}[{index}] 'if_op' requires a numeric 'if_value'")
def _referenced_fields_for_kind(kind: str, rule: dict[str, Any]) -> list[str]:
if kind in ("order", "equals"):
fields = rule.get("fields")
@@ -317,13 +503,33 @@ def _referenced_fields_for_kind(kind: str, rule: dict[str, Any]) -> list[str]:
target = [rule["target"]] if isinstance(rule.get("target"), str) else []
parts = rule.get("parts") if isinstance(rule.get("parts"), list) else []
return target + list(parts or [])
if kind == "requires":
out = []
if isinstance(rule.get("if_field"), str):
out.append(rule["if_field"])
if isinstance(rule.get("then_field"), str):
out.append(rule["then_field"])
if kind == "ratio_equals":
return [f for f in (rule.get("target"), rule.get("numerator"), rule.get("denominator")) if isinstance(f, str)]
if kind == "date_offset_equals":
return [f for f in (rule.get("base"), rule.get("offset_days_field"), rule.get("target")) if isinstance(f, str)]
if kind == "date_diff_equals":
return [f for f in (rule.get("start"), rule.get("end"), rule.get("target")) if isinstance(f, str)]
if kind == "comparison_equals":
out = [f for f in (rule.get("target"), rule.get("left")) if isinstance(f, str)]
if isinstance(rule.get("right"), str):
out.append(rule["right"])
return out
if kind == "piecewise_lookup":
return [f for f in (rule.get("source"), rule.get("target")) if isinstance(f, str)]
if kind == "requires":
return [f for f in (rule.get("if_field"), rule.get("then_field")) if isinstance(f, str)]
if kind == "forbidden_if":
out = [rule["if_field"]] if isinstance(rule.get("if_field"), str) else []
then_fields = rule.get("then_fields")
return out + list(then_fields) if isinstance(then_fields, list) else out
if kind == "any_of_implies":
out = [rule["target"]] if isinstance(rule.get("target"), str) else []
conditions = rule.get("conditions")
if isinstance(conditions, list):
out += [c.get("field") for c in conditions if isinstance(c, dict) and isinstance(c.get("field"), str)]
return out
if kind == "conditional_equals":
return [f for f in (rule.get("if_field"), rule.get("target")) if isinstance(f, str)]
return []
@@ -331,21 +537,117 @@ def _display_for_kind(kind: str, rule: dict[str, Any]) -> str:
if kind == "order":
left, right = rule["fields"]
return f"{left} must be {OP_SYMBOLS[rule['op']]} {right}"
if kind == "sum_equals":
return f"{rule['target']} must equal the sum of {', '.join(rule['parts'])}"
if kind == "requires":
if "if_value" in rule:
return f"{rule['then_field']} is required when {rule['if_field']} == {rule['if_value']!r}"
return f"{rule['then_field']} is required when {rule['if_field']} is set"
if kind == "equals":
a, b = rule["fields"]
return f"{a} must equal {b}"
if kind == "sum_equals":
return f"{rule['target']} must equal the sum of {', '.join(rule['parts'])}"
if kind == "ratio_equals":
power = rule.get("power", 1)
denom = f"{rule['denominator']}" + (f"**{power}" if power != 1 else "")
return f"{rule['target']} must equal {rule['numerator']} / {denom}"
if kind == "date_offset_equals":
return f"{rule['target']} must equal {rule['base']} + {rule['offset_days_field']} days"
if kind == "date_diff_equals":
return f"{rule['target']} must equal ({rule['end']} - {rule['start']}).days"
if kind == "comparison_equals":
right = rule.get("right", rule.get("right_value"))
return f"{rule['target']} must equal ({rule['left']} {OP_SYMBOLS[rule['op']]} {right})"
if kind == "piecewise_lookup":
return f"{rule['target']} must match the bucket {rule['source']} falls into"
if kind == "requires":
cond = _condition_display(rule["if_field"], rule)
if "then_value" in rule:
return f"{rule['then_field']} must equal {rule['then_value']!r} when {cond}"
return f"{rule['then_field']} is required when {cond}"
if kind == "forbidden_if":
cond = _condition_display(rule["if_field"], rule)
return f"{', '.join(rule['then_fields'])} must be empty when {cond}"
if kind == "any_of_implies":
return f"{rule['target']} must equal true if any of its conditions hold"
if kind == "conditional_equals":
cond = _condition_display(rule["if_field"], rule)
return f"{rule['target']} must equal {rule['value_if_true']!r} when {cond}, else {rule['value_if_false']!r}"
return kind
def _condition_display(field_name: str, rule: dict[str, Any]) -> str:
if "if_op" in rule:
return f"{field_name} {OP_SYMBOLS[rule['if_op']]} {rule['if_value']}"
if "if_value" in rule:
if isinstance(rule["if_value"], list):
return f"{field_name} in {rule['if_value']}"
return f"{field_name} == {rule['if_value']!r}"
return f"{field_name} is set"
def _validate_breakpoints(path: Path, table_name: str, index: int, rule: dict[str, Any]) -> None:
breakpoints = rule["breakpoints"]
if not isinstance(breakpoints, list) or not breakpoints:
raise ValueError(f"{path}: {table_name}[{index}] 'breakpoints' must be a non-empty list")
last_max = None
for bp in breakpoints:
if not isinstance(bp, dict) or "max" not in bp or "value" not in bp:
raise ValueError(f"{path}: {table_name}[{index}] each breakpoint needs 'max' and 'value'")
if not isinstance(bp["max"], (int, float)):
raise ValueError(f"{path}: {table_name}[{index}] breakpoint 'max' must be a number")
if not isinstance(bp["value"], str):
raise ValueError(f"{path}: {table_name}[{index}] breakpoint 'value' must be a string")
if last_max is not None and bp["max"] <= last_max:
raise ValueError(f"{path}: {table_name}[{index}] breakpoints must have strictly increasing 'max'")
last_max = bp["max"]
if not isinstance(rule["otherwise"], str):
raise ValueError(f"{path}: {table_name}[{index}] 'otherwise' must be a string")
def _validate_piecewise_targets_against_enum(
path: Path, table_name: str, index: int, rule: dict[str, Any], fields_by_name: dict[str, Any],
enums_by_name: dict[str, Any],
) -> None:
target_field = fields_by_name[rule["target"]]
if target_field["pydantic_type"] != "EnumField":
return
enum = enums_by_name.get(target_field["enum_ref"])
if enum is None:
return
allowed = set(enum["elements"])
values = [bp["value"].upper() for bp in rule["breakpoints"]] + [rule["otherwise"].upper()]
bad = [v for v in values if v not in allowed]
if bad:
raise ValueError(
f"{path}: {table_name}[{index}] breakpoint value(s) {bad} are not members of enum "
f"'{target_field['enum_ref']}'"
)
def _validate_conditions_list(path: Path, table_name: str, index: int, rule: dict[str, Any], field_names: set[str]) -> None:
conditions = rule["conditions"]
if not isinstance(conditions, list) or not conditions:
raise ValueError(f"{path}: {table_name}[{index}] 'conditions' must be a non-empty list")
for c in conditions:
if not isinstance(c, dict) or "field" not in c or "op" not in c:
raise ValueError(f"{path}: {table_name}[{index}] each condition needs 'field' and 'op'")
if c["field"] not in field_names:
raise ValueError(f"{path}: {table_name}[{index}] condition references unknown field '{c['field']}'")
if c["op"] not in ({"truthy"} | VALID_COMPARISON_OPS):
raise ValueError(
f"{path}: {table_name}[{index}] condition 'op' must be one of "
f"{sorted({'truthy'} | VALID_COMPARISON_OPS)}"
)
if c["op"] != "truthy" and "value" not in c:
raise ValueError(f"{path}: {table_name}[{index}] condition with op '{c['op']}' needs a 'value'")
def parse_single_cross_rule(
cross_rules_path: Path, table_name: str, index: int, rule: Any, field_names: set[str]
cross_rules_path: Path,
table_name: str,
index: int,
rule: Any,
fields_by_name: dict[str, Any],
enums_by_name: dict[str, Any],
) -> dict[str, Any]:
field_names = set(fields_by_name)
if not isinstance(rule, dict):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] must be a mapping")
@@ -362,7 +664,6 @@ def parse_single_cross_rule(
raise ValueError(
f"{cross_rules_path}: {table_name}[{index}] (kind '{kind}') missing key(s): {sorted(missing)}"
)
allowed = spec["required"] | spec["optional"] | {"kind"}
unknown = rule.keys() - allowed
if unknown:
@@ -385,13 +686,9 @@ def parse_single_cross_rule(
f"{cross_rules_path}: {table_name}[{index}] 'fields' must be a list of exactly two field names"
)
if kind == "order" and rule["op"] not in VALID_ORDER_OPS:
raise ValueError(
f"{cross_rules_path}: {table_name}[{index}] 'op' must be one of {sorted(VALID_ORDER_OPS)}"
)
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'op' must be one of {sorted(VALID_ORDER_OPS)}")
if kind == "sum_equals":
if not isinstance(rule["target"], str):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'target' must be a field name")
parts = rule["parts"]
if not (isinstance(parts, list) and len(parts) >= 1 and all(isinstance(x, str) for x in parts)):
raise ValueError(
@@ -401,22 +698,94 @@ def parse_single_cross_rule(
if not isinstance(tolerance, (int, float)):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'tolerance' must be a number")
if kind == "requires":
if not isinstance(rule["if_field"], str) or not isinstance(rule["then_field"], str):
if kind == "ratio_equals":
power = rule.get("power", 1)
if not isinstance(power, int) or isinstance(power, bool):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'power' must be an integer")
tolerance = rule.get("tolerance", 0)
if not isinstance(tolerance, (int, float)):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'tolerance' must be a number")
if kind in ("date_offset_equals", "date_diff_equals"):
tolerance_days = rule.get("tolerance_days", 0)
if not isinstance(tolerance_days, int) or isinstance(tolerance_days, bool):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'tolerance_days' must be an integer")
if kind == "comparison_equals":
if rule["op"] not in VALID_COMPARISON_OPS:
raise ValueError(
f"{cross_rules_path}: {table_name}[{index}] 'if_field' and 'then_field' must be field names"
f"{cross_rules_path}: {table_name}[{index}] 'op' must be one of {sorted(VALID_COMPARISON_OPS)}"
)
has_right = "right" in rule
has_right_value = "right_value" in rule
if has_right == has_right_value:
raise ValueError(
f"{cross_rules_path}: {table_name}[{index}] needs exactly one of 'right' or 'right_value'"
)
tolerance = rule.get("tolerance", 0)
if not isinstance(tolerance, (int, float)):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'tolerance' must be a number")
if kind == "piecewise_lookup":
_validate_breakpoints(cross_rules_path, table_name, index, rule)
_validate_piecewise_targets_against_enum(cross_rules_path, table_name, index, rule, fields_by_name, enums_by_name)
if kind in ("requires", "forbidden_if", "conditional_equals"):
_validate_condition(cross_rules_path, table_name, index, rule, field_names)
if kind == "conditional_equals":
tolerance = rule.get("tolerance", 0)
if not isinstance(tolerance, (int, float)):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'tolerance' must be a number")
if kind == "forbidden_if":
then_fields = rule["then_fields"]
if not (isinstance(then_fields, list) and then_fields and all(isinstance(x, str) for x in then_fields)):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'then_fields' must be a non-empty list")
allowed_values = rule.get("then_allowed_values", [])
if not isinstance(allowed_values, list):
raise ValueError(f"{cross_rules_path}: {table_name}[{index}] 'then_allowed_values' must be a list")
if kind == "any_of_implies":
_validate_conditions_list(cross_rules_path, table_name, index, rule, field_names)
parsed_rule = {k: v for k, v in rule.items() if k not in ("kind", "message")}
# Enum fields store their value uppercased (constraints.normalize_enum).
# Any condition value compared against such a field must match that
# casing, or a natural-looking lowercase YAML value would silently
# never match.
if kind in ("requires", "conditional_equals") and "if_value" in parsed_rule:
parsed_rule["if_value"] = _normalize_condition_value(parsed_rule["if_value"], fields_by_name[rule["if_field"]])
if kind == "requires" and "then_value" in parsed_rule:
parsed_rule["then_value"] = _normalize_condition_value(
parsed_rule["then_value"], fields_by_name[rule["then_field"]]
)
if kind == "forbidden_if":
if "if_value" in parsed_rule:
parsed_rule["if_value"] = _normalize_condition_value(
parsed_rule["if_value"], fields_by_name[rule["if_field"]]
)
if "then_allowed_values" in parsed_rule:
first_then_field = fields_by_name[rule["then_fields"][0]]
parsed_rule["then_allowed_values"] = _normalize_condition_value(
parsed_rule["then_allowed_values"], first_then_field
)
if kind == "any_of_implies":
parsed_rule["conditions"] = [
{**c, "value": _normalize_condition_value(c["value"], fields_by_name[c["field"]])}
if "value" in c else c
for c in parsed_rule["conditions"]
]
parsed_rule["kind"] = kind
parsed_rule["message"] = rule.get("message")
parsed_rule["display"] = _display_for_kind(kind, rule)
parsed_rule.setdefault("tolerance", 0)
return parsed_rule
def parse_cross_rules(
cross_rules_path: Path, parsed_tables: list[dict[str, Any]]
cross_rules_path: Path, parsed_tables: list[dict[str, Any]], enums_spec: list[dict[str, Any]] | None = None
) -> dict[str, list[dict[str, Any]]]:
with open(cross_rules_path, "r", encoding="utf-8") as f:
try:
@@ -430,6 +799,7 @@ def parse_cross_rules(
raise ValueError(f"{cross_rules_path}: top level must map table name -> list of rules")
tables_by_name = {t["table"]["table_name"]: t for t in parsed_tables}
enums_by_name = {e["name"]: e for e in (enums_spec or [])}
cross_rules_spec: dict[str, list[dict[str, Any]]] = {}
for table_name, rules in raw.items():
@@ -438,9 +808,9 @@ def parse_cross_rules(
if not isinstance(rules, list) or not rules:
raise ValueError(f"{cross_rules_path}: '{table_name}' must map to a non-empty list of rules")
field_names = {f["field_name"] for f in tables_by_name[table_name]["fields"]}
fields_by_name = {f["field_name"]: f for f in tables_by_name[table_name]["fields"]}
cross_rules_spec[table_name] = [
parse_single_cross_rule(cross_rules_path, table_name, i, rule, field_names)
parse_single_cross_rule(cross_rules_path, table_name, i, rule, fields_by_name, enums_by_name)
for i, rule in enumerate(rules)
]
@@ -478,7 +848,7 @@ def parse_spec(
cross_rules_path = spec_dir / "cross_rules.yaml"
cross_rules_spec = (
parse_cross_rules(cross_rules_path, parsed_tables) if cross_rules_path.exists() else {}
parse_cross_rules(cross_rules_path, parsed_tables, enums_spec) if cross_rules_path.exists() else {}
)
return parsed_tables, enums_spec, cross_rules_spec
+2 -1
View File
@@ -8,6 +8,7 @@ one holding the database session (see validator.validate_row).
from ps_core.runtime.foreign_keys import check_foreign_keys
from ps_core.runtime.ingest import ingest
from ps_core.runtime.loader import load_row
from ps_core.runtime.unique import check_unique_fields
from ps_core.runtime.validator import validate_row
__all__ = ["load_row", "validate_row", "ingest", "check_foreign_keys"]
__all__ = ["load_row", "validate_row", "ingest", "check_foreign_keys", "check_unique_fields"]
+4 -1
View File
@@ -53,5 +53,8 @@ def check_foreign_keys(
for row in bad_rows:
row.validated = False
errs = json.loads(row.errors) if row.errors else {}
errs[f["field_name"]] = f"no matching row in {target_table_name}.{target_col_name}"
errs[f["field_name"]] = {
"rule": "foreign_key",
"message": f"no matching row in {target_table_name}.{target_col_name}",
}
row.errors = json.dumps(errs)
+69
View File
@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*-
"""
Uniqueness is never enforced as a database constraint (no UNIQUE column,
for the same reason foreign keys carry no FK constraint — see
foreign_keys.py): a duplicate should not block a row from being saved.
Instead, this runs as a second pass, after every row is already in the
database: it flags every row sharing a duplicate value by setting
`validated = False` and recording the reason in `errors`, the same
columns every other rule already writes to.
Call this once per batch, after your inserts are committed, and commit
again afterward.
This checks single-column uniqueness only (`unique: true` on one field).
It does not implement multi-column ("unique together") uniqueness.
"""
from __future__ import annotations
import json
from typing import Any
import sqlalchemy as sa
def check_unique_fields(
session: Any,
parsed_tables: list[dict[str, Any]],
class_lookup: dict[str, type],
) -> None:
"""
parsed_tables — the list returned by parse_spec.parse_spec (or its
`parsed_tables` element).
class_lookup — {table_name: orm_class}, built by the caller from
whatever module holds the generated schema classes.
Kept explicit, rather than read from globals(), so
this function has no dependency on how those classes
were loaded.
"""
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
table_cls = class_lookup[table_name]
for f in table_spec["fields"]:
if not f["unique"]:
continue
column = getattr(table_cls, f["field_name"])
duplicate_values = (
session.query(column)
.filter(column.isnot(None))
.group_by(column)
.having(sa.func.count() > 1)
.all()
)
if not duplicate_values:
continue
values = [row[0] for row in duplicate_values]
bad_rows = session.query(table_cls).filter(column.in_(values)).all()
for row in bad_rows:
row.validated = False
errs = json.loads(row.errors) if row.errors else {}
errs[f["field_name"]] = {
"rule": "unique",
"message": f"duplicate value for {f['field_name']}: {getattr(row, f['field_name'])!r}",
}
row.errors = json.dumps(errs)
+7 -2
View File
@@ -19,14 +19,19 @@ from pydantic import BaseModel, ValidationError
def validate_row(raw_data: dict[str, Any], check_cls: type[BaseModel]) -> dict[str, Any]:
"""
Returns {"validated": True, "errors": None} on success, or
{"validated": False, "errors": <json string of field -> message>} on failure.
{"validated": False, "errors": <json string>} on failure.
Each entry in the JSON is {"rule": <name>, "message": <text>} — the
rule name is `err["type"]`, which every check in constraints.py and
every cross-rule kind sets explicitly via PydanticCustomError, rather
than something parsed back out of the message text.
"""
try:
check_cls.model_validate(raw_data)
return {"validated": True, "errors": None}
except ValidationError as e:
field_errors = {
".".join(str(p) for p in err["loc"]) or "_cross_field": err["msg"]
(".".join(str(p) for p in err["loc"]) or "_cross_field"): {"rule": err["type"], "message": err["msg"]}
for err in e.errors()
}
return {"validated": False, "errors": json.dumps(field_errors)}
-6
View File
@@ -2,9 +2,3 @@ class {{ class_name }}(str, Enum):
{% for e in elements %}
{{ e }} = "{{ e }}"
{% endfor %}
{{ class_name }}Field = Annotated[
{{ class_name }},
BeforeValidator(normalize_enum),
AfterValidator(check_enum({{ class_name }})),
]
-5
View File
@@ -1,8 +1,3 @@
# -*- coding: utf-8 -*-
"""AUTO-GENERATED. DO NOT EDIT BY HAND."""
from enum import Enum
from typing import Annotated
from pydantic import AfterValidator, BeforeValidator
from ps_core.constraints import check_enum, normalize_enum
+5 -5
View File
@@ -2,13 +2,13 @@
**Class name:** `{{ table.class_name }}`
| Field | SQL Type | Required | Primary Key | Foreign Key | Rule |
|---|---|---|---|---|---|
| Field | SQL Type | Required | Unique | Primary Key | Foreign Key | Rule |
|---|---|---|---|---|---|---|
{% for f in fields %}
| {{ f.field_name }} | {{ f.sql_type }} | {{ "Yes" if f.required else "No" }} | {{ "Yes" if f.primary_key else "No" }} | {{ f.foreign_key if f.foreign_key else "—" }} | {{ f.rule_display if f.rule_display else "—" }} |
| {{ f.field_name }} | {{ f.sql_type }} | {{ "Yes" if f.required else "No" }} | {{ "Yes" if f.unique else "No" }} | {{ "Yes" if f.primary_key else "No" }} | {{ f.foreign_key if f.foreign_key else "—" }} | {{ f.rule_display if f.rule_display else "—" }} |
{% endfor %}
| validated | sa.Boolean | Yes | No | — | — |
| errors | sa.Text | No | No | — | — |
| validated | sa.Boolean | Yes | No | No | — | — |
| errors | sa.Text | No | No | No | — | — |
{% if cross_rules %}
**Cross-field rules:**
+7 -6
View File
@@ -1,10 +1,13 @@
class {{ table.class_name }}(Base):
"""
Storage model for table `{{ table.table_name }}`.
Permissive — no domain validation at this layer. Every rule lives in
the matching `{{ table.class_name }}Check` Pydantic class instead.
Foreign keys are not enforced as database constraints; they are
checked separately, after insert, by ps_core.runtime.foreign_keys.
Permissive — no domain validation at this layer, and no NOT NULL
constraints beyond the primary key. Every rule ("required" included)
lives in the matching `{{ table.class_name }}Check` Pydantic class
instead, so a row that fails a rule can still be saved and flagged,
never rejected by the database.
Foreign keys are not enforced as database constraints either; they
are checked separately, after insert, by ps_core.runtime.foreign_keys.
"""
__tablename__ = "{{ table.table_name }}"
@@ -12,8 +15,6 @@ class {{ table.class_name }}(Base):
{% for f in fields %}
{% if f.primary_key %}
{{ f.field_name }}: Mapped[{{ f.py_type }}] = mapped_column({{ f.sql_type }}, primary_key=True, default=lambda: str(uuid.uuid4()))
{% elif f.required %}
{{ f.field_name }}: Mapped[{{ f.py_type }}] = mapped_column({{ f.sql_type }}, nullable=False)
{% else %}
{{ f.field_name }}: Mapped[Optional[{{ f.py_type }}]] = mapped_column({{ f.sql_type }}, nullable=True, default=None)
{% endif %}
+8 -38
View File
@@ -1,44 +1,14 @@
{{ checker_functions }}
class {{ table.class_name }}Check(BaseModel):
"""
Validation contract for table `{{ table.table_name }}`.
Not a database table. No SQLAlchemy dependency.
Not a database table. No SQLAlchemy dependency. Every field is
optional here; "required" is one configurable rule among several,
enforced by that field's own checker function above.
"""
{% for f in fields %}
{% if f.pydantic_type == "EnumField" %}
{% if f.required %}
{{ f.field_name }}: {{ f.enum_class }}
{% else %}
{{ f.field_name }}: Optional[{{ f.enum_class }}] = None
{% endif %}
{% elif f.rule == "range" %}
{% if f.py_type == "int" %}
{% if f.required %}
{{ f.field_name }}: RangeInt({{ f.min }}, {{ f.max }}, label="{{ f.field_name }}")
{% else %}
{{ f.field_name }}: Optional[RangeInt({{ f.min }}, {{ f.max }}, label="{{ f.field_name }}")] = None
{% endif %}
{% elif f.py_type == "float" %}
{% if f.required %}
{{ f.field_name }}: RangeFloat({{ f.min }}, {{ f.max }}, label="{{ f.field_name }}")
{% else %}
{{ f.field_name }}: Optional[RangeFloat({{ f.min }}, {{ f.max }}, label="{{ f.field_name }}")] = None
{% endif %}
{% endif %}
{% elif f.rule == "not_future" %}
{% if f.required %}
{{ f.field_name }}: NotFutureDate
{% else %}
{{ f.field_name }}: Optional[NotFutureDate] = None
{% endif %}
{% elif f.py_type == "bool" %}
{{ f.field_name }}: FlexBool
{% else %}
{% if f.required %}
{{ f.field_name }}: {{ f.pydantic_type }}
{% else %}
{{ f.field_name }}: Optional[{{ f.pydantic_type }}] = None
{% endif %}
{% endif %}
{% endfor %}
model_config = ConfigDict(validate_default=True)
{{ field_lines }}
{{ cross_rules_code }}
+17 -5
View File
@@ -1,9 +1,21 @@
# -*- coding: utf-8 -*-
"""AUTO-GENERATED. DO NOT EDIT BY HAND."""
from datetime import date, datetime
from typing import Optional
from datetime import date, datetime, timedelta
from typing import Annotated, Optional
from pydantic import BaseModel, model_validator
from pydantic import BaseModel, BeforeValidator, ConfigDict, model_validator
from pydantic_core import PydanticCustomError
from ps_core.constraints import FlexBool, NotFutureDate, RangeFloat, RangeInt
from .enums import * # noqa: F401,F403 — provides every generated *Field enum type
from ps_core.constraints import (
apply_strip,
apply_upper,
check_enum_membership,
check_max_length,
check_not_future,
check_range,
check_regex,
check_required,
coerce_bool,
normalize_enum,
)
from .enums import * # noqa: F401,F403 — provides every generated enum class
+62 -70
View File
@@ -40,81 +40,73 @@ def spec_bad_fk_dir() -> Path:
return FIXTURES_DIR / "spec_bad_fk"
@pytest.fixture
def spec_devdata_dir() -> Path:
return FIXTURES_DIR / "spec_devdata"
def _plain_field(field_name: str, py_type: str, sql_type: str, **overrides) -> dict:
field = {
"field_name": field_name,
"py_type": py_type,
"pydantic_type": py_type,
"enum_class": None,
"enum_ref": None,
"sql_type": sql_type,
"primary_key": False,
"foreign_key": None,
"unique": False,
"checks": [],
"required": False,
"rule_display": None,
}
field.update(overrides)
return field
@pytest.fixture
def sample_table_spec() -> dict:
"""A small, hand-built table_spec — table `t` with fields a, b, c, flag."""
return {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
{
"field_name": "id",
"py_type": "str",
"pydantic_type": "str",
"enum_class": None,
"sql_type": "sa.String(36)",
"primary_key": True,
"foreign_key": None,
"required": True,
"rule": None,
"min": None,
"max": None,
"rule_display": None,
},
{
"field_name": "a",
"py_type": "int",
"pydantic_type": "int",
"enum_class": None,
"sql_type": "sa.Integer",
"primary_key": False,
"foreign_key": None,
"required": False,
"rule": None,
"min": None,
"max": None,
"rule_display": None,
},
{
"field_name": "b",
"py_type": "float",
"pydantic_type": "float",
"enum_class": None,
"sql_type": "sa.Float",
"primary_key": False,
"foreign_key": None,
"required": False,
"rule": None,
"min": None,
"max": None,
"rule_display": None,
},
{
"field_name": "c",
"py_type": "float",
"pydantic_type": "float",
"enum_class": None,
"sql_type": "sa.Float",
"primary_key": False,
"foreign_key": None,
"required": False,
"rule": None,
"min": None,
"max": None,
"rule_display": None,
},
{
"field_name": "flag",
"py_type": "bool",
"pydantic_type": "bool",
"enum_class": None,
"sql_type": "sa.Integer",
"primary_key": False,
"foreign_key": None,
"required": False,
"rule": None,
"min": None,
"max": None,
"rule_display": None,
},
_plain_field("id", "str", "sa.String(36)", primary_key=True),
_plain_field("a", "int", "sa.Integer"),
_plain_field("b", "float", "sa.Float"),
_plain_field("c", "float", "sa.Float"),
_plain_field("flag", "bool", "sa.Integer"),
],
}
@pytest.fixture
def make_field():
"""Factory for building field dicts in tests that need custom shapes."""
return _plain_field
@pytest.fixture
def rich_table_spec() -> dict:
"""A table with numeric, date, bool, and enum fields, for cross-rule tests."""
return {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
_plain_field("id", "str", "sa.String(36)", primary_key=True),
_plain_field("a", "int", "sa.Integer"),
_plain_field("b", "float", "sa.Float"),
_plain_field("c", "float", "sa.Float"),
_plain_field("n", "int", "sa.Integer"),
_plain_field("flag", "bool", "sa.Integer"),
_plain_field("d1", "date", "sa.Date"),
_plain_field("d2", "date", "sa.Date"),
_plain_field(
"status", "str", "sa.Text",
pydantic_type="EnumField", enum_class="Color", enum_ref="color",
),
],
}
@pytest.fixture
def rich_enums_spec() -> list[dict]:
return [{"name": "color", "class_name": "Color", "elements": ["RED", "GREEN", "BLUE"]}]
+3
View File
@@ -0,0 +1,3 @@
color:
- red
- green
+10
View File
@@ -0,0 +1,10 @@
table:
name: order
fields:
id:
type: uuid
primary_key: true
widget_id:
type: uuid
required: true
foreign_key: widget.id
+18
View File
@@ -0,0 +1,18 @@
table:
name: widget
fields:
id:
type: uuid
primary_key: true
code:
type: text
required: true
unique: true
quantity:
type: integer
range: true
min: 1
max: 10
color:
type: enum
enum: color
+3 -7
View File
@@ -9,24 +9,20 @@ fields:
required: true
field2:
type: integer
rule: range
range: true
min: 1
max: 10
required: false
field3:
type: float
rule: range
range: true
min: 0.1
max: 1.0
required: false
field4:
type: date
rule: not_future
required: true
not_future: true
field6:
type: bool
required: false
field7:
type: enum
enum: test_enum
required: false
+9
View File
@@ -0,0 +1,9 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
name:
type: text
max_length: -5
+9
View File
@@ -0,0 +1,9 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
code:
type: text
regex: "[a-z"
+12
View File
@@ -0,0 +1,12 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
age:
type: integer
required: true
range: true
min: 0
max: 120
+10
View File
@@ -0,0 +1,10 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
status:
type: enum
enum: test_enum
enum_message: "status must be a known value: {v}"
+9
View File
@@ -0,0 +1,9 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
name:
type: text
enum_message: "should not be allowed here"
+13
View File
@@ -0,0 +1,13 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
code:
type: text
required: true
strip: true
upper: true
max_length: 10
regex: "[A-Z]{3}"
+1 -1
View File
@@ -6,6 +6,6 @@ fields:
primary_key: true
age:
type: integer
rule: range
range: true
min: 10
max: 1
+1 -1
View File
@@ -6,5 +6,5 @@ fields:
primary_key: true
age:
type: integer
rule: range
range: true
min: 1
+1 -1
View File
@@ -6,6 +6,6 @@ fields:
primary_key: true
name:
type: text
rule: range
range: true
min: 1
max: 10
+9
View File
@@ -0,0 +1,9 @@
table:
name: t
fields:
id:
type: uuid
primary_key: true
age:
type: integer
strip: true
+1 -1
View File
@@ -6,4 +6,4 @@ fields:
primary_key: true
age:
type: integer
rule: not_a_real_rule
not_future: true
+154 -101
View File
@@ -1,94 +1,129 @@
from datetime import date, timedelta
from enum import Enum
import pytest
from pydantic import BaseModel, ValidationError
from pydantic_core import PydanticCustomError
from ps_core.constraints import (
FlexBool,
MaxLenStr,
NotFutureDate,
RangeFloat,
RangeInt,
RegexStr,
check_enum,
apply_strip,
apply_upper,
check_enum_membership,
check_max_length,
check_not_future,
check_range,
check_regex,
check_required,
coerce_bool,
normalize_enum,
)
# --- RangeInt / RangeFloat --------------------------------------------------
# --- apply_strip / apply_upper (transforms, never raise) ---------------------
class _RangeModel(BaseModel):
n: RangeInt(1, 10)
f: RangeFloat(0.1, 1.0)
def test_apply_strip_trims_whitespace():
assert apply_strip(" hello ") == "hello"
@pytest.mark.parametrize("n,f", [(1, 0.1), (10, 1.0), (5, 0.5)])
def test_range_accepts_boundaries_and_middle(n, f):
m = _RangeModel(n=n, f=f)
assert m.n == n
assert m.f == f
def test_apply_strip_passes_through_none():
assert apply_strip(None) is None
@pytest.mark.parametrize("n", [0, 11, -5])
def test_range_int_rejects_out_of_bounds(n):
with pytest.raises(ValidationError):
_RangeModel(n=n, f=0.5)
def test_apply_strip_passes_through_non_string():
assert apply_strip(5) == 5
@pytest.mark.parametrize("f", [0.0, 1.01, -1.0])
def test_range_float_rejects_out_of_bounds(f):
with pytest.raises(ValidationError):
_RangeModel(n=5, f=f)
def test_apply_upper_uppercases():
assert apply_upper("abc") == "ABC"
def test_range_int_label_appears_in_message():
Labeled = RangeInt(1, 10, label="age")
class M(BaseModel):
age: Labeled
with pytest.raises(ValidationError, match="age must be between 1 and 10"):
M(age=99)
def test_apply_upper_passes_through_none():
assert apply_upper(None) is None
# --- NotFutureDate -----------------------------------------------------------
class _DateModel(BaseModel):
d: NotFutureDate
def test_apply_upper_passes_through_non_string():
assert apply_upper(5) == 5
def test_not_future_accepts_today():
m = _DateModel(d=date.today())
assert m.d == date.today()
# --- check_required ------------------------------------------------------------
def test_check_required_passes_non_none():
assert check_required("x", "field is required") == "x"
def test_not_future_accepts_past():
def test_check_required_passes_falsy_non_none():
assert check_required("", "field is required") == ""
assert check_required(0, "field is required") == 0
def test_check_required_raises_on_none():
with pytest.raises(ValueError, match="field is required"):
check_required(None, "field is required")
# --- check_range ------------------------------------------------------------------
@pytest.mark.parametrize("v", [1, 5, 10])
def test_check_range_accepts_boundaries_and_middle(v):
assert check_range(v, 1, 10, "out of range") == v
@pytest.mark.parametrize("v", [0, 11, -5])
def test_check_range_rejects_out_of_bounds(v):
with pytest.raises(ValueError, match="out of range"):
check_range(v, 1, 10, "out of range")
def test_check_range_message_includes_value():
with pytest.raises(ValueError, match="got 99"):
check_range(99, 1, 10, "bad")
# --- check_not_future --------------------------------------------------------------
def test_check_not_future_accepts_today():
assert check_not_future(date.today(), "future") == date.today()
def test_check_not_future_accepts_past():
past = date.today() - timedelta(days=1)
m = _DateModel(d=past)
assert m.d == past
assert check_not_future(past, "future") == past
def test_not_future_rejects_future():
def test_check_not_future_rejects_future():
future = date.today() + timedelta(days=1)
with pytest.raises(ValidationError, match="future date"):
_DateModel(d=future)
with pytest.raises(ValueError, match="future"):
check_not_future(future, "future")
def test_check_not_future_plain_function():
assert check_not_future(date.today()) == date.today()
# --- check_regex --------------------------------------------------------------------
def test_check_regex_accepts_match():
assert check_regex("ABC", "[A-Z]{3}", "bad format") == "ABC"
def test_check_regex_rejects_non_match():
with pytest.raises(ValueError, match="bad format"):
check_regex("abc", "[A-Z]{3}", "bad format")
def test_check_regex_requires_full_match_not_partial():
with pytest.raises(ValueError):
check_not_future(date.today() + timedelta(days=1))
check_regex("ABCD", "[A-Z]{3}", "bad format") # fullmatch, not search
# --- FlexBool / coerce_bool ----------------------------------------------------
# --- check_max_length ---------------------------------------------------------------
class _BoolModel(BaseModel):
flag: FlexBool
def test_check_max_length_accepts_within_bound():
assert check_max_length("abcde", 5, "too long") == "abcde"
def test_check_max_length_rejects_over_bound():
with pytest.raises(ValueError, match="too long"):
check_max_length("abcdef", 5, "too long")
# --- coerce_bool -----------------------------------------------------------------------
@pytest.mark.parametrize("raw,expected", [
(True, True), (False, False),
(1, True), (0, False),
@@ -96,56 +131,22 @@ class _BoolModel(BaseModel):
(" 1 ", True),
(None, None),
])
def test_flex_bool_accepts_known_forms(raw, expected):
m = _BoolModel(flag=raw)
assert m.flag is expected
def test_coerce_bool_accepts_known_forms(raw, expected):
assert coerce_bool(raw) is expected
@pytest.mark.parametrize("raw", [2, -1, "yes", "no", 3.5, []])
def test_flex_bool_rejects_unknown_forms(raw):
with pytest.raises(ValidationError):
_BoolModel(flag=raw)
def test_coerce_bool_rejects_unknown_forms(raw):
with pytest.raises(ValueError):
coerce_bool(raw)
def test_coerce_bool_plain_function_raises_on_bad_type():
with pytest.raises(ValueError, match="unrecognized type"):
coerce_bool([1, 2])
def test_coerce_bool_label_appears_in_error():
with pytest.raises(ValueError, match="my_field"):
coerce_bool("nonsense", label="my_field")
# --- RegexStr / MaxLenStr ------------------------------------------------------
class _RegexModel(BaseModel):
code: RegexStr(r"[A-Z]{3}")
def test_regex_str_accepts_match():
assert _RegexModel(code="ABC").code == "ABC"
def test_regex_str_rejects_non_match():
with pytest.raises(ValidationError):
_RegexModel(code="abc")
class _MaxLenModel(BaseModel):
name: MaxLenStr(5)
def test_max_len_str_accepts_within_bound():
assert _MaxLenModel(name="abcde").name == "abcde"
def test_max_len_str_rejects_over_bound():
with pytest.raises(ValidationError):
_MaxLenModel(name="abcdef")
# --- enum helpers --------------------------------------------------------------
class _Color(str, Enum):
RED = "RED"
GREEN = "GREEN"
# --- normalize_enum --------------------------------------------------------------------
def test_normalize_enum_strips_and_uppercases():
assert normalize_enum(" red ") == "RED"
@@ -155,12 +156,64 @@ def test_normalize_enum_passes_through_none():
assert normalize_enum(None) is None
def test_check_enum_accepts_member_value():
checker = check_enum(_Color)
assert checker(_Color.RED) == _Color.RED
# --- check_enum_membership ----------------------------------------------------------------
class _Color(str, __import__("enum").Enum):
RED = "RED"
GREEN = "GREEN"
def test_check_enum_rejects_non_member():
checker = check_enum(_Color)
def test_check_enum_membership_accepts_member():
assert check_enum_membership("RED", _Color) == _Color.RED
def test_check_enum_membership_rejects_non_member():
with pytest.raises(ValueError, match="must be one of"):
checker("BLUE")
check_enum_membership("BLUE", _Color)
# --- every check carries its rule name as a structured type, not just message text -----
#
# Each function raises PydanticCustomError, not a plain ValueError. It IS a
# ValueError (existing `except ValueError` / `pytest.raises(ValueError)`
# still works everywhere), but Pydantic also exposes the rule name at
# e.errors()[i]["type"] — this is what ps_core.runtime.validate_row reads
# to store {"rule": ..., "message": ...} instead of a bare string.
@pytest.mark.parametrize("fn,args,expected_type", [
(check_required, (None,), "required"),
(check_range, (99, 1, 10), "range"),
(check_not_future, (date.today() + timedelta(days=1),), "not_future"),
(check_regex, ("abc", "[A-Z]{3}"), "regex"),
(check_max_length, ("abcdef", 5), "max_length"),
(coerce_bool, ("nonsense",), "bool_coercion"),
])
def test_check_functions_raise_pydantic_custom_error_with_matching_type(fn, args, expected_type):
with pytest.raises(PydanticCustomError) as exc_info:
fn(*args)
assert exc_info.value.type == expected_type
def test_check_enum_membership_raises_pydantic_custom_error_with_matching_type():
with pytest.raises(PydanticCustomError) as exc_info:
check_enum_membership("BLUE", _Color)
assert exc_info.value.type == "enum_membership"
def test_rule_name_survives_through_a_real_pydantic_model():
from typing import Annotated, Optional
from pydantic import BeforeValidator
def _check(v):
return check_range(v, 1, 10, label="age")
class M(BaseModel):
age: Annotated[Optional[int], BeforeValidator(_check)] = None
with pytest.raises(ValidationError) as exc_info:
M(age=99)
err = exc_info.value.errors()[0]
assert err["type"] == "range"
assert err["msg"] == "age must be between 1 and 10, got 99"
+153
View File
@@ -0,0 +1,153 @@
from datetime import date
import pytest
from pydantic import BaseModel, ValidationError, model_validator
from ps_core.devdata.faulty import break_field, faulty_foreign_key, faulty_row_for_cross_rule, faulty_skeleton_row
@pytest.fixture
def enums_by_name():
return {"color": {"name": "color", "class_name": "Color", "elements": ["RED", "GREEN"]}}
def test_break_field_required(make_field):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "required"}])
assert break_field(field) is None
def test_break_field_range(make_field):
field = make_field("n", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 10}])
assert break_field(field) == 11
def test_break_field_max_length(make_field):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "max_length", "max_length": 5}])
assert len(break_field(field)) == 6
def test_break_field_regex(make_field):
field = make_field("code", "str", "sa.Text", checks=[{"kind": "regex", "pattern": "[A-Z]{3}"}])
import re
assert not re.fullmatch("[A-Z]{3}", break_field(field))
def test_break_field_not_future(make_field):
field = make_field("d", "date", "sa.Date", checks=[{"kind": "not_future"}])
assert break_field(field) > date.today()
def test_break_field_enum(make_field):
field = make_field("status", "str", "sa.Text", pydantic_type="EnumField", enum_ref="color")
assert break_field(field) == "NOT_A_REAL_MEMBER"
def test_break_field_bool(make_field):
field = make_field("flag", "bool", "sa.Integer")
assert break_field(field) == "nonsense"
def test_break_field_prioritizes_required_over_other_checks(make_field):
# required check goes first, matching the fixed CHECK_ORDER in parse_spec
field = make_field("n", "int", "sa.Integer", checks=[
{"kind": "required"}, {"kind": "range", "min": 1, "max": 10},
])
assert break_field(field) is None
def test_break_field_raises_when_nothing_to_break(make_field):
field = make_field("name", "str", "sa.Text") # no checks, not enum, not bool
with pytest.raises(ValueError, match="has no rule to break"):
break_field(field)
def test_faulty_skeleton_row_breaks_only_the_named_field(make_field, enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("age", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 10}]),
make_field("name", "str", "sa.Text"),
],
}
row = faulty_skeleton_row(table_spec, enums_by_name, "age")
assert row["age"] == 11
assert isinstance(row["name"], str) # untouched, still a plain generated value
def test_faulty_foreign_key_is_a_uuid_shaped_string():
import uuid
value = faulty_foreign_key()
assert uuid.UUID(value) # parses without raising
# --- faulty_row_for_cross_rule: the oracle path -----------------------------------------
def _make_order_check_cls():
from typing import Optional
class M(BaseModel):
a: Optional[int] = None
b: Optional[int] = None
@model_validator(mode="after")
def _order(self):
if self.a is not None and self.b is not None and self.a > self.b:
raise ValueError("a must not exceed b")
return self
return M
def test_faulty_row_for_cross_rule_finds_a_violation(make_field, enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("a", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
make_field("b", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
],
}
check_cls = _make_order_check_cls()
row = faulty_row_for_cross_rule(table_spec, check_cls, enums_by_name, tries=200)
with pytest.raises(ValidationError):
check_cls(**row)
def test_faulty_row_for_cross_rule_respects_narrowed_candidates(make_field, enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("a", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
make_field("b", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
],
}
check_cls = _make_order_check_cls()
cross_rule = {"kind": "order", "fields": ["a", "b"], "op": "le"}
row = faulty_row_for_cross_rule(table_spec, check_cls, enums_by_name, cross_rule=cross_rule, tries=200)
with pytest.raises(ValidationError):
check_cls(**row)
def test_faulty_row_for_cross_rule_raises_when_no_violation_found(make_field, enums_by_name):
# a check_cls with no cross rule at all — the oracle can never find a
# cross-rule error (empty loc), so it must give up loudly, not hang
from typing import Optional
class AlwaysFine(BaseModel):
a: Optional[int] = None
b: Optional[int] = None
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("a", "int", "sa.Integer"),
make_field("b", "int", "sa.Integer"),
],
}
with pytest.raises(RuntimeError, match="no violation found"):
faulty_row_for_cross_rule(table_spec, AlwaysFine, enums_by_name, tries=5)
+134
View File
@@ -0,0 +1,134 @@
import json
import sys
import uuid
import sqlalchemy as sa
from sqlalchemy.orm import Session
from ps_core.devdata.fill import _build_lookups, fill_all
from ps_core.generate_all import generate_all
from ps_core.parse_spec import parse_spec
def _build_and_import(spec_dir, out_dir):
generate_all(spec_dir, out_dir)
pkg_name = out_dir.name
sys.path.insert(0, str(out_dir.parent))
try:
import importlib
schema = importlib.import_module(f"{pkg_name}.schema")
validation = importlib.import_module(f"{pkg_name}.validation")
finally:
sys.path.remove(str(out_dir.parent))
return schema, validation
def _setup(spec_devdata_dir, tmp_path):
parsed_tables, enums_spec, _ = parse_spec(spec_devdata_dir)
enums_by_name = {e["name"]: e for e in enums_spec}
out_dir = tmp_path / f"gen_{uuid.uuid4().hex}"
schema_mod, validation_mod = _build_and_import(spec_devdata_dir, out_dir)
class_lookup, check_lookup = _build_lookups(parsed_tables, schema_mod, validation_mod)
engine = sa.create_engine("sqlite://")
schema_mod.Base.metadata.create_all(engine)
return parsed_tables, enums_by_name, class_lookup, check_lookup, engine
def test_fill_all_basic_run_produces_valid_rows(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
widgets = session.query(class_lookup["widget"]).all()
orders = session.query(class_lookup["order"]).all()
assert len(widgets) == 10
assert len(orders) == 10
assert all(w.validated for w in widgets)
assert all(o.validated for o in orders)
def test_fill_all_orphan_rate_one_flags_every_link(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=1.0, faulty_rate=0.0, repeated_rate=0.0)
orders = session.query(class_lookup["order"]).all()
assert all(not o.validated for o in orders)
assert all(json.loads(o.errors)["widget_id"]["rule"] == "foreign_key" for o in orders)
def test_fill_all_orphan_rate_zero_flags_nothing(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
orders = session.query(class_lookup["order"]).all()
assert all(o.validated for o in orders)
assert all(o.errors is None for o in orders)
def test_fill_all_faulty_rate_one_flags_every_widget(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=1.0, repeated_rate=0.0)
widgets = session.query(class_lookup["widget"]).all()
assert all(not w.validated for w in widgets)
assert all(w.errors is not None for w in widgets)
def test_fill_all_repeated_rate_one_flags_unique_field(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=1.0)
widgets = session.query(class_lookup["widget"]).all()
codes = [w.code for w in widgets]
assert len(set(codes)) < len(codes) # genuine duplicates exist
flagged_unique = [
w for w in widgets
if w.errors and json.loads(w.errors).get("code", {}).get("rule") == "unique"
]
assert flagged_unique # at least the duplicates got caught
def test_fill_all_zero_rates_never_produce_duplicates_by_accident(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
widgets = session.query(class_lookup["widget"]).all()
assert all(w.validated for w in widgets)
assert all(w.errors is None for w in widgets)
def test_fill_all_table_order_does_not_matter(spec_devdata_dir, tmp_path):
# parsed_tables happens to list "order" before "widget" alphabetically —
# order (the FK child) still ends up correctly linked after phase 2
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
assert parsed_tables[0]["table"]["table_name"] == "order" # confirms the ordering this test is about
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=5,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
widget_ids = {w.id for w in session.query(class_lookup["widget"]).all()}
orders = session.query(class_lookup["order"]).all()
assert all(o.widget_id in widget_ids for o in orders)
+122
View File
@@ -0,0 +1,122 @@
from datetime import date, datetime
import pytest
from ps_core.devdata.good import good_foreign_key, good_skeleton_row, good_value
@pytest.fixture
def enums_by_name():
return {"color": {"name": "color", "class_name": "Color", "elements": ["RED", "GREEN", "BLUE"]}}
def test_good_value_enum_picks_a_real_member(make_field, enums_by_name):
field = make_field("status", "str", "sa.Text", pydantic_type="EnumField", enum_ref="color")
for _ in range(20):
assert good_value(field, enums_by_name) in enums_by_name["color"]["elements"]
def test_good_value_bool_is_a_real_bool(make_field, enums_by_name):
field = make_field("flag", "bool", "sa.Integer")
assert good_value(field, enums_by_name) in (True, False)
def test_good_value_date_is_never_in_the_future(make_field, enums_by_name):
field = make_field("d", "date", "sa.Date")
for _ in range(20):
assert good_value(field, enums_by_name) <= date.today()
def test_good_value_datetime_is_never_in_the_future(make_field, enums_by_name):
field = make_field("d", "datetime", "sa.DateTime")
for _ in range(20):
assert good_value(field, enums_by_name) <= datetime.now()
def test_good_value_int_respects_range(make_field, enums_by_name):
field = make_field("n", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 10}])
for _ in range(50):
v = good_value(field, enums_by_name)
assert isinstance(v, int)
assert 1 <= v <= 10
def test_good_value_float_respects_range(make_field, enums_by_name):
field = make_field("n", "float", "sa.Float", checks=[{"kind": "range", "min": 0.1, "max": 1.0}])
for _ in range(50):
v = good_value(field, enums_by_name)
assert 0.1 <= v <= 1.0
def test_good_value_int_with_no_range_still_returns_an_int(make_field, enums_by_name):
field = make_field("n", "int", "sa.Integer")
assert isinstance(good_value(field, enums_by_name), int)
def test_good_value_text_respects_max_length(make_field, enums_by_name):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "max_length", "max_length": 5}])
for _ in range(20):
assert len(good_value(field, enums_by_name)) <= 5
def test_good_value_text_with_regex_raises_with_a_clear_message(make_field, enums_by_name):
field = make_field("code", "str", "sa.Text", checks=[{"kind": "regex", "pattern": "[A-Z]{3}"}])
with pytest.raises(ValueError, match="no generic sampler for a regex pattern"):
good_value(field, enums_by_name)
def test_good_skeleton_row_excludes_primary_key_and_foreign_key(enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
{"field_name": "id", "primary_key": True, "foreign_key": None, "py_type": "str",
"pydantic_type": "str", "checks": []},
{"field_name": "owner_id", "primary_key": False, "foreign_key": "other.id", "py_type": "str",
"pydantic_type": "str", "checks": []},
{"field_name": "name", "primary_key": False, "foreign_key": None, "py_type": "str",
"pydantic_type": "str", "checks": []},
],
}
row = good_skeleton_row(table_spec, enums_by_name)
assert set(row) == {"name"}
def test_good_foreign_key_picks_a_real_existing_id():
import sqlalchemy as sa
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Parent(Base):
__tablename__ = "parent"
id: Mapped[str] = mapped_column(sa.String(36), primary_key=True)
engine = sa.create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([Parent(id="a"), Parent(id="b")])
session.commit()
for _ in range(10):
assert good_foreign_key(session, Parent, "id") in ("a", "b")
def test_good_foreign_key_raises_when_parent_table_is_empty():
import sqlalchemy as sa
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Parent(Base):
__tablename__ = "parent2"
id: Mapped[str] = mapped_column(sa.String(36), primary_key=True)
engine = sa.create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
with pytest.raises(RuntimeError, match="no rows in parent2"):
good_foreign_key(session, Parent, "id")
+6 -12
View File
@@ -14,7 +14,6 @@ def test_generate_enum_class_contains_expected_names(enums_dir):
assert "class TestEnum(str, Enum):" in result
assert 'ITEM1 = "ITEM1"' in result
assert 'ITEM2 = "ITEM2"' in result
assert "TestEnumField = Annotated[" in result
def test_generate_enums_file_is_valid_python_and_runs(enums_dir):
@@ -26,22 +25,17 @@ def test_generate_enums_file_is_valid_python_and_runs(enums_dir):
exec(compile(content, "<generated>", "exec"), namespace)
TestEnum = namespace["TestEnum"]
TestEnumField = namespace["TestEnumField"]
assert TestEnum.ITEM1.value == "ITEM1"
assert TestEnum.ITEM2.value == "ITEM2"
# the Field type actually normalizes + checks, end to end
from pydantic import BaseModel
class M(BaseModel):
e: TestEnumField
assert M(e=" item1 ").e == TestEnum.ITEM1
# plain (str, Enum) — no normalization or membership checking lives
# here anymore; that is generated per-field in validation.py instead
assert TestEnum("ITEM1") is TestEnum.ITEM1
import pytest
from pydantic import ValidationError
with pytest.raises(ValidationError):
M(e="not_a_member")
with pytest.raises(ValueError):
TestEnum("not_a_member")
def test_generate_enums_file_with_no_enums_still_compiles():
+16 -4
View File
@@ -9,16 +9,16 @@ def test_generate_markdown_table_contains_expected_rows(spec_ok_dir):
assert "## test_table" in result
assert "**Class name:** `TestTable`" in result
assert "| field2 | sa.Integer | No | No | — | range [1, 10] |" in result
assert "| field7 | sa.Text | No | No | — | one of test_enum |" in result
assert "| validated | sa.Boolean | Yes | No | — | — |" in result
assert "| field2 | sa.Integer | No | No | No | — | range [1, 10] |" in result
assert "| field7 | sa.Text | No | No | No | — | one of test_enum |" in result
assert "| validated | sa.Boolean | Yes | No | No | — | — |" in result
def test_generate_markdown_table_shows_foreign_key(spec_ok_dir):
parsed_tables, _, _ = parse_spec(spec_ok_dir)
foreign_table = next(t for t in parsed_tables if t["table"]["table_name"] == "foreign_table")
result = generate_markdown_table(foreign_table)
assert "| owner_id | sa.String(36) | Yes | No | test_table.id | — |" in result
assert "| owner_id | sa.String(36) | Yes | No | No | test_table.id | — |" in result
def test_generate_markdown_table_lists_cross_rules(spec_ok_dir):
@@ -38,6 +38,18 @@ def test_generate_markdown_table_omits_cross_rules_section_when_none(spec_ok_dir
assert "**Cross-field rules:**" not in result
def test_generate_markdown_table_shows_unique(make_field):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("email", "str", "sa.Text", unique=True),
],
}
result = generate_markdown_table(table_spec)
assert "| email | sa.Text | No | Yes | No | — | — |" in result
def test_generate_markdown_file_covers_every_table(spec_ok_dir):
parsed_tables, _, cross_rules_spec = parse_spec(spec_ok_dir)
content = generate_markdown_file(parsed_tables, cross_rules_spec)
+7 -3
View File
@@ -31,13 +31,17 @@ def test_foreign_key_field_has_no_sa_foreign_key_constraint(spec_ok_dir):
assert "sa.ForeignKey" not in result # foreign keys are metadata-only, never a DB constraint
def test_required_field_is_not_optional(spec_ok_dir):
def test_storage_layer_is_permissive_regardless_of_required(spec_ok_dir):
parsed_tables, _, _ = parse_spec(spec_ok_dir)
test_table = next(t for t in parsed_tables if t["table"]["table_name"] == "test_table")
result = generate_schema_class(test_table)
assert "field1: Mapped[str] = mapped_column(sa.Text, nullable=False)" in result
assert "field2: Mapped[Optional[int]]" in result
# field1 and field4 are `required: true` in the Pydantic contract,
# but the storage layer never enforces it — every non-PK column stays
# nullable, so a row failing that rule can still be saved and flagged.
assert "field1: Mapped[Optional[str]] = mapped_column(sa.Text, nullable=True, default=None)" in result
assert "field4: Mapped[Optional[date]] = mapped_column(sa.Date, nullable=True, default=None)" in result
assert "nullable=False" not in result.split("validated:")[0] # nowhere before the fixed validated/errors columns
def test_generate_schema_file_is_valid_python_and_runs(spec_ok_dir):
+323 -90
View File
@@ -1,7 +1,3 @@
import sys
import types
import uuid
import pytest
from pydantic import BaseModel, ValidationError, model_validator
@@ -11,32 +7,111 @@ from ps_core.generate_validation import (
generate_validation_file,
render_cross_rule,
render_cross_rules_code,
render_field_checker,
)
from ps_core.parse_spec import parse_enums, parse_spec
from ps_core.parse_spec import parse_spec
# ---------------------------------------------------------------------------
# helpers to exec generated validation code without a real installed package
# (the generated header always does `from .enums import *`, which needs a
# real relative-import context — we fabricate one with a throwaway package)
# per-field checker codegen
# ---------------------------------------------------------------------------
def _install_fake_enums_package(enums_namespace: dict) -> str:
pkg_name = f"_fake_pkg_{uuid.uuid4().hex}"
pkg = types.ModuleType(pkg_name)
pkg.__path__ = []
enums_mod = types.ModuleType(f"{pkg_name}.enums")
enums_mod.__dict__.update(enums_namespace)
sys.modules[pkg_name] = pkg
sys.modules[f"{pkg_name}.enums"] = enums_mod
return pkg_name
def _exec_checker(checker_source: str, fn_name: str):
namespace: dict = {}
from ps_core.constraints import (
apply_strip, apply_upper, check_max_length, check_not_future,
check_range, check_regex, check_required, coerce_bool, normalize_enum,
)
namespace.update(dict(
apply_strip=apply_strip, apply_upper=apply_upper, check_max_length=check_max_length,
check_not_future=check_not_future, check_range=check_range, check_regex=check_regex,
check_required=check_required, coerce_bool=coerce_bool, normalize_enum=normalize_enum,
))
exec(compile(checker_source, "<generated>", "exec"), namespace)
return namespace[fn_name]
def _exec_validation_content(content: str, enums_namespace: dict) -> dict:
pkg_name = _install_fake_enums_package(enums_namespace)
namespace = {"__package__": pkg_name, "__name__": f"{pkg_name}.validation"}
exec(compile(content, "<generated>", "exec"), namespace)
return namespace
def test_render_field_checker_plain_field_is_identity(make_field):
field = make_field("name", "str", "sa.Text")
checker_source, field_line = render_field_checker("T", field)
fn = _exec_checker(checker_source, "_check_t_name")
assert fn("hello") == "hello"
assert fn(None) is None
assert "Annotated[Optional[str], BeforeValidator(_check_t_name)] = None" in field_line
def test_render_field_checker_required_raises(make_field):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "required", "message": "name is required"}])
checker_source, _ = render_field_checker("T", field)
fn = _exec_checker(checker_source, "_check_t_name")
assert fn("x") == "x"
with pytest.raises(ValueError, match="name is required"):
fn(None)
def test_render_field_checker_strip_then_upper_then_required(make_field):
field = make_field(
"code", "str", "sa.Text",
checks=[
{"kind": "strip"},
{"kind": "upper"},
{"kind": "required", "message": "code is required"},
],
)
checker_source, _ = render_field_checker("T", field)
fn = _exec_checker(checker_source, "_check_t_code")
assert fn(" abc ") == "ABC"
with pytest.raises(ValueError, match="code is required"):
fn(None)
def test_render_field_checker_bool_uses_coerce_bool(make_field):
field = make_field("flag", "bool", "sa.Integer")
checker_source, _ = render_field_checker("T", field)
fn = _exec_checker(checker_source, "_check_t_flag")
assert fn(1) is True
assert fn(None) is None
with pytest.raises(ValueError):
fn("nonsense")
def test_render_field_checker_enum_normalizes_and_checks_membership(make_field):
field = make_field(
"status", "str", "sa.Text",
pydantic_type="EnumField", enum_class="TestEnum",
)
checker_source = (
"class TestEnum(str, __import__('enum').Enum):\n"
" ITEM1 = 'ITEM1'\n"
" ITEM2 = 'ITEM2'\n\n"
) + render_field_checker("T", field)[0]
namespace: dict = {}
from ps_core.constraints import check_enum_membership, normalize_enum
namespace["normalize_enum"] = normalize_enum
namespace["check_enum_membership"] = check_enum_membership
exec(compile(checker_source, "<generated>", "exec"), namespace)
fn = namespace["_check_t_status"]
assert fn(" item1 ") == namespace["TestEnum"].ITEM1
with pytest.raises(ValueError, match="status must be one of"):
fn("not_a_member")
def test_render_field_checker_enum_custom_message_is_not_supported(make_field):
# enum_message was removed — the label ("status") is generic and
# baked into constraints.check_enum_membership, not overridable per field.
field = make_field("status", "str", "sa.Text", pydantic_type="EnumField", enum_class="TestEnum")
checker_source = (
"class TestEnum(str, __import__('enum').Enum):\n"
" ITEM1 = 'ITEM1'\n\n"
) + render_field_checker("T", field)[0]
namespace: dict = {}
from ps_core.constraints import check_enum_membership, normalize_enum
namespace["normalize_enum"] = normalize_enum
namespace["check_enum_membership"] = check_enum_membership
exec(compile(checker_source, "<generated>", "exec"), namespace)
fn = namespace["_check_t_status"]
with pytest.raises(ValueError, match="status must be one of.*NOT_A_MEMBER"):
fn("not_a_member")
# ---------------------------------------------------------------------------
@@ -44,10 +119,11 @@ def _exec_validation_content(content: str, enums_namespace: dict) -> dict:
# ---------------------------------------------------------------------------
def _wrap_in_model(body: str, fields: str) -> dict:
"""Compile a small BaseModel with the given field annotations and cross-rule body."""
source = (
"from typing import Optional\n"
"from pydantic import BaseModel, model_validator\n\n"
"from pydantic import BaseModel, model_validator\n"
"from pydantic_core import PydanticCustomError\n"
"from datetime import timedelta\n\n"
"class M(BaseModel):\n"
f"{fields}\n"
f"{body}\n"
@@ -57,19 +133,28 @@ def _wrap_in_model(body: str, fields: str) -> dict:
return namespace
def test_render_order_rule_passes_and_fails():
def test_render_order():
rule = {"kind": "order", "fields": ["a", "b"], "op": "le", "message": None, "display": "a must be <= b"}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " a: Optional[int] = None\n b: Optional[int] = None\n")
M = ns["M"]
assert M(a=1, b=2).a == 1
assert M(a=None, b=None).a is None # skipped when either side is None
M(a=1, b=2)
M(a=None, b=None)
with pytest.raises(ValidationError, match="a must be <= b"):
M(a=5, b=1)
def test_render_sum_equals_rule_passes_and_fails():
def test_render_equals():
rule = {"kind": "equals", "fields": ["a", "b"], "message": None, "display": "a must equal b"}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " a: Optional[int] = None\n b: Optional[int] = None\n")
M = ns["M"]
M(a=1, b=1)
with pytest.raises(ValidationError, match="a must equal b"):
M(a=1, b=2)
def test_render_sum_equals():
rule = {
"kind": "sum_equals", "target": "c", "parts": ["a", "b"], "tolerance": 0,
"message": None, "display": "c must equal the sum of a, b",
@@ -79,37 +164,194 @@ def test_render_sum_equals_rule_passes_and_fails():
body, " a: Optional[float] = None\n b: Optional[float] = None\n c: Optional[float] = None\n"
)
M = ns["M"]
assert M(a=1, b=2, c=3).c == 3
assert M(a=None, b=2, c=3).c == 3 # skipped, a missing
M(a=1, b=2, c=3)
with pytest.raises(ValidationError, match="must equal the sum"):
M(a=1, b=2, c=10)
def test_render_requires_rule_with_if_value():
def test_render_ratio_equals():
rule = {
"kind": "requires", "if_field": "flag", "then_field": "a", "if_value": True,
"message": None, "display": "a is required when flag == True",
"kind": "ratio_equals", "target": "imc", "numerator": "w", "denominator": "h",
"power": 2, "tolerance": 0.5, "message": None, "display": "imc must equal w / h**2",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(
body,
" w: Optional[float] = None\n h: Optional[float] = None\n imc: Optional[float] = None\n",
)
M = ns["M"]
M(w=10.0, h=1.0, imc=10.2) # within tolerance
with pytest.raises(ValidationError, match="must equal"):
M(w=10.0, h=1.0, imc=99.0)
M(w=10.0, h=0.0, imc=5.0) # denominator zero: skipped, no crash
def test_render_date_offset_equals():
from datetime import date
rule = {
"kind": "date_offset_equals", "base": "start", "offset_days_field": "n", "target": "end",
"message": None, "display": "end must equal start + n days",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(
body,
" from datetime import date as _date\n"
" start: Optional[_date] = None\n n: Optional[int] = None\n end: Optional[_date] = None\n",
)
M = ns["M"]
M(start=date(2024, 1, 1), n=10, end=date(2024, 1, 11))
with pytest.raises(ValidationError):
M(start=date(2024, 1, 1), n=10, end=date(2024, 2, 1))
def test_render_date_diff_equals():
from datetime import date
rule = {
"kind": "date_diff_equals", "start": "start", "end": "end", "target": "n",
"message": None, "display": "n must equal (end - start).days",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(
body,
" from datetime import date as _date\n"
" start: Optional[_date] = None\n end: Optional[_date] = None\n n: Optional[int] = None\n",
)
M = ns["M"]
M(start=date(2024, 1, 1), end=date(2024, 1, 11), n=10)
with pytest.raises(ValidationError):
M(start=date(2024, 1, 1), end=date(2024, 1, 11), n=3)
def test_render_comparison_equals_with_right_field():
rule = {
"kind": "comparison_equals", "target": "confirmed", "left": "score", "op": "ge", "right": "threshold",
"message": None, "display": "confirmed must equal (score >= threshold)",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(
body,
" score: Optional[int] = None\n threshold: Optional[int] = None\n"
" confirmed: Optional[bool] = None\n",
)
M = ns["M"]
M(score=6, threshold=5, confirmed=True)
with pytest.raises(ValidationError):
M(score=6, threshold=8, confirmed=True)
def test_render_comparison_equals_with_right_value():
rule = {
"kind": "comparison_equals", "target": "low", "left": "score", "op": "le", "right_value": 75.0,
"message": None, "display": "low must equal (score <= 75.0)",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " score: Optional[float] = None\n low: Optional[bool] = None\n")
M = ns["M"]
M(score=70.0, low=True)
with pytest.raises(ValidationError):
M(score=70.0, low=False)
def test_render_piecewise_lookup():
rule = {
"kind": "piecewise_lookup", "source": "age", "target": "bucket",
"breakpoints": [{"max": 10, "value": "young"}, {"max": 20, "value": "mid"}],
"otherwise": "old", "message": None, "display": "bucket must match age's bucket",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " age: Optional[int] = None\n bucket: Optional[str] = None\n")
M = ns["M"]
M(age=5, bucket="YOUNG")
M(age=15, bucket="MID")
M(age=99, bucket="OLD")
with pytest.raises(ValidationError):
M(age=5, bucket="OLD")
def test_render_requires_plain():
rule = {"kind": "requires", "if_field": "flag", "then_field": "a", "message": None, "display": "a required when flag"}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " flag: Optional[bool] = None\n a: Optional[int] = None\n")
M = ns["M"]
assert M(flag=False, a=None).flag is False
assert M(flag=True, a=1).a == 1
M(flag=False, a=None)
M(flag=True, a=1)
with pytest.raises(ValidationError):
M(flag=True, a=None)
def test_render_equals_rule():
rule = {"kind": "equals", "fields": ["a", "b"], "message": None, "display": "a must equal b"}
def test_render_requires_with_if_op():
rule = {
"kind": "requires", "if_field": "n", "if_op": "gt", "if_value": 0, "then_field": "flag", "then_value": True,
"message": None, "display": "flag must be true when n > 0",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " a: Optional[int] = None\n b: Optional[int] = None\n")
ns = _wrap_in_model(body, " n: Optional[int] = None\n flag: Optional[bool] = None\n")
M = ns["M"]
M(n=0, flag=False)
M(n=3, flag=True)
with pytest.raises(ValidationError):
M(n=3, flag=False)
assert M(a=1, b=1).a == 1
with pytest.raises(ValidationError, match="a must equal b"):
M(a=1, b=2)
def test_render_forbidden_if():
rule = {
"kind": "forbidden_if", "if_field": "flag", "if_value": False, "then_fields": ["a"],
"then_allowed_values": [], "message": None, "display": "a must be empty when flag is false",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " flag: Optional[bool] = None\n a: Optional[int] = None\n")
M = ns["M"]
M(flag=False, a=None)
M(flag=True, a=5)
with pytest.raises(ValidationError):
M(flag=False, a=5)
def test_render_forbidden_if_with_allowed_values():
rule = {
"kind": "forbidden_if", "if_field": "flag", "if_value": False, "then_fields": ["kind"],
"then_allowed_values": ["NONE"], "message": None, "display": "kind must be none when flag is false",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " flag: Optional[bool] = None\n kind: Optional[str] = None\n")
M = ns["M"]
M(flag=False, kind="NONE")
with pytest.raises(ValidationError):
M(flag=False, kind="SOMETHING")
def test_render_any_of_implies():
rule = {
"kind": "any_of_implies", "target": "risk",
"conditions": [{"field": "n", "op": "lt", "value": 7}, {"field": "flag", "op": "truthy"}],
"message": None, "display": "risk must equal true if any condition holds",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(
body, " n: Optional[int] = None\n flag: Optional[bool] = None\n risk: Optional[bool] = None\n"
)
M = ns["M"]
M(n=9, flag=False, risk=False)
M(n=3, flag=False, risk=True)
with pytest.raises(ValidationError):
M(n=3, flag=False, risk=False)
def test_render_conditional_equals():
rule = {
"kind": "conditional_equals", "if_field": "flag", "if_value": True,
"target": "threshold", "value_if_true": 6, "value_if_false": 5,
"message": None, "display": "threshold depends on flag",
}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " flag: Optional[bool] = None\n threshold: Optional[int] = None\n")
M = ns["M"]
M(flag=True, threshold=6)
M(flag=False, threshold=5)
with pytest.raises(ValidationError):
M(flag=True, threshold=5)
def test_render_unsupported_kind_raises():
@@ -121,30 +363,17 @@ def test_render_cross_rules_code_empty_list_is_empty_string():
assert render_cross_rules_code([]) == ""
# ---------------------------------------------------------------------------
# generate_validation_class / generate_validation_file: shape
# ---------------------------------------------------------------------------
def test_generate_validation_class_is_valid_python(spec_ok_dir):
parsed_tables, enums_spec, cross_rules_spec = parse_spec(spec_ok_dir)
test_table = next(t for t in parsed_tables if t["table"]["table_name"] == "test_table")
content = generate_validation_class(test_table, cross_rules_spec.get("test_table"))
compile(content, "<generated>", "exec")
assert "class TestTableCheck(BaseModel):" in content
assert "_cross_0" in content # the one cross rule from spec_ok's cross_rules.yaml
def test_generate_validation_class_marks_required_and_optional_fields(spec_ok_dir):
parsed_tables, _, cross_rules_spec = parse_spec(spec_ok_dir)
test_table = next(t for t in parsed_tables if t["table"]["table_name"] == "test_table")
content = generate_validation_class(test_table, cross_rules_spec.get("test_table"))
assert "field1: str\n" in content # required, no default
assert "field2: Optional[RangeInt(1, 10" in content # not required
def test_custom_message_with_quote_does_not_break_generated_code():
rule = {"kind": "equals", "fields": ["a", "b"], "message": "it's broken", "display": "a must equal b"}
body = render_cross_rule(rule, 0)
ns = _wrap_in_model(body, " a: Optional[int] = None\n b: Optional[int] = None\n")
M = ns["M"]
with pytest.raises(ValidationError, match="it's broken"):
M(a=1, b=2)
# ---------------------------------------------------------------------------
# full behavioral round trip: real enums + real validation, executed together
# full behavioral round trip against a real spec
# ---------------------------------------------------------------------------
def test_full_validation_file_behaves_end_to_end(spec_ok_dir):
@@ -154,39 +383,43 @@ def test_full_validation_file_behaves_end_to_end(spec_ok_dir):
enums_namespace: dict = {}
exec(compile(enums_content, "<generated>", "exec"), enums_namespace)
validation_content = generate_validation_file(parsed_tables, cross_rules_spec)
ns = _exec_validation_content(validation_content, enums_namespace)
import sys
import types
import uuid as uuid_mod
TestTableCheck = ns["TestTableCheck"]
ForeignTableCheck = ns["ForeignTableCheck"]
pkg_name = f"_fake_pkg_{uuid_mod.uuid4().hex}"
pkg = types.ModuleType(pkg_name)
pkg.__path__ = []
enums_mod = types.ModuleType(f"{pkg_name}.enums")
enums_mod.__dict__.update(enums_namespace)
sys.modules[pkg_name] = pkg
sys.modules[f"{pkg_name}.enums"] = enums_mod
validation_content = generate_validation_file(parsed_tables, cross_rules_spec)
namespace = {"__package__": pkg_name, "__name__": f"{pkg_name}.validation"}
exec(compile(validation_content, "<generated>", "exec"), namespace)
TestTableCheck = namespace["TestTableCheck"]
from datetime import date
good = TestTableCheck(
field1="hello", field2=5, field3=0.5, field4=date(2024, 1, 1), field6=1, field7="item1"
)
assert good.field7.value == "ITEM1"
good = TestTableCheck(field1="hello", field2=5, field4=date(2024, 1, 1))
assert good.field1 == "hello"
# range violation
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2024, 1, 1), field2=999)
with pytest.raises(ValidationError) as exc_info:
TestTableCheck(field4=date(2024, 1, 1)) # field1 omitted -> required check fires
assert exc_info.value.errors()[0]["type"] == "required"
# unknown enum member
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2024, 1, 1), field7="not_a_member")
with pytest.raises(ValidationError) as exc_info:
TestTableCheck(field1="x", field4=date(2024, 1, 1), field2=999) # range
assert exc_info.value.errors()[0]["type"] == "range"
# future date
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2999, 1, 1))
with pytest.raises(ValidationError) as exc_info:
TestTableCheck(field1="x", field4=date(2999, 1, 1)) # not_future
assert exc_info.value.errors()[0]["type"] == "not_future"
# cross rule: field6 true requires field3
with pytest.raises(ValidationError, match="field3 is required"):
with pytest.raises(ValidationError, match="field3 is required when field6 is true") as exc_info:
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=None)
assert exc_info.value.errors()[0]["type"] == "requires" # the cross-rule kind, not "value_error"
# cross rule satisfied
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=0.5)
# foreign_table check has no enum/rule fields, just required uuid
ForeignTableCheck(owner_id="anything-goes-here-shape-wise")
with pytest.raises(ValidationError):
ForeignTableCheck(owner_id=None)
+359 -88
View File
@@ -1,109 +1,380 @@
from pathlib import Path
import pytest
from ps_core.parse_spec import parse_cross_rules
from ps_core.parse_spec import parse_cross_rules, parse_single_cross_rule
DUMMY_PATH = Path("dummy.yaml")
@pytest.fixture
def parsed_tables(sample_table_spec):
return [sample_table_spec]
def fields_by_name(rich_table_spec):
return {f["field_name"]: f for f in rich_table_spec["fields"]}
def test_valid_rules_of_every_kind_parse(cross_rules_dir, parsed_tables):
result = parse_cross_rules(cross_rules_dir / "valid.yaml", parsed_tables)
rules = result["t"]
assert [r["kind"] for r in rules] == ["order", "sum_equals", "requires", "equals"]
order_rule = rules[0]
assert order_rule["fields"] == ["a", "b"]
assert order_rule["op"] == "le"
assert order_rule["display"] == "a must be <= b"
sum_rule = rules[1]
assert sum_rule["target"] == "c"
assert sum_rule["parts"] == ["a", "b"]
assert sum_rule["tolerance"] == 0.01
requires_rule = rules[2]
assert requires_rule["if_field"] == "flag"
assert requires_rule["then_field"] == "a"
assert requires_rule["tolerance"] == 0 # default fill, harmless on non-numeric kinds
equals_rule = rules[3]
assert equals_rule["fields"] == ["a", "b"]
@pytest.fixture
def enums_by_name(rich_enums_spec):
return {e["name"]: e for e in rich_enums_spec}
def test_missing_file_is_not_this_functions_job(tmp_path, parsed_tables):
# parse_cross_rules assumes the caller already checked existence
# (parse_spec only calls it when the path exists) — confirm it still
# raises a clear, ordinary FileNotFoundError rather than something odd.
with pytest.raises(FileNotFoundError):
parse_cross_rules(tmp_path / "missing.yaml", parsed_tables)
def _parse(rule, fields_by_name, enums_by_name, index=0, table_name="t"):
return parse_single_cross_rule(DUMMY_PATH, table_name, index, rule, fields_by_name, enums_by_name)
def test_empty_file_returns_empty_dict(cross_rules_dir, parsed_tables):
assert parse_cross_rules(cross_rules_dir / "empty_file.yaml", parsed_tables) == {}
# --- order / equals (existing kinds, sanity) ------------------------------------
def test_order_valid(fields_by_name, enums_by_name):
parsed = _parse({"kind": "order", "fields": ["a", "n"], "op": "le"}, fields_by_name, enums_by_name)
assert parsed["display"] == "a must be <= n"
def test_not_a_mapping_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="must map table name"):
parse_cross_rules(cross_rules_dir / "not_a_mapping.yaml", parsed_tables)
def test_unknown_table_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="unknown table 'no_such_table'"):
parse_cross_rules(cross_rules_dir / "unknown_table.yaml", parsed_tables)
def test_rules_not_a_list_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="non-empty list of rules"):
parse_cross_rules(cross_rules_dir / "not_a_list.yaml", parsed_tables)
def test_empty_rules_list_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="non-empty list of rules"):
parse_cross_rules(cross_rules_dir / "empty_list.yaml", parsed_tables)
def test_rule_not_a_mapping_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="must be a mapping"):
parse_cross_rules(cross_rules_dir / "rule_not_a_mapping.yaml", parsed_tables)
def test_unknown_kind_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="unsupported kind"):
parse_cross_rules(cross_rules_dir / "unknown_kind.yaml", parsed_tables)
def test_missing_required_key_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="missing key"):
parse_cross_rules(cross_rules_dir / "missing_required_key.yaml", parsed_tables)
def test_unknown_key_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="unknown key"):
parse_cross_rules(cross_rules_dir / "unknown_key.yaml", parsed_tables)
def test_unknown_field_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="unknown field"):
parse_cross_rules(cross_rules_dir / "unknown_field.yaml", parsed_tables)
def test_bad_op_raises(cross_rules_dir, parsed_tables):
def test_order_bad_op_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="'op' must be one of"):
parse_cross_rules(cross_rules_dir / "bad_op.yaml", parsed_tables)
_parse({"kind": "order", "fields": ["a", "n"], "op": "nope"}, fields_by_name, enums_by_name)
def test_order_wrong_field_count_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="exactly two field names"):
parse_cross_rules(cross_rules_dir / "order_wrong_field_count.yaml", parsed_tables)
def test_order_unknown_field_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="unknown field"):
_parse({"kind": "order", "fields": ["a", "ghost"], "op": "le"}, fields_by_name, enums_by_name)
def test_sum_equals_empty_parts_raises(cross_rules_dir, parsed_tables):
with pytest.raises(ValueError, match="non-empty list of field names"):
parse_cross_rules(cross_rules_dir / "sum_equals_empty_parts.yaml", parsed_tables)
def test_equals_valid(fields_by_name, enums_by_name):
parsed = _parse({"kind": "equals", "fields": ["a", "n"]}, fields_by_name, enums_by_name)
assert parsed["display"] == "a must equal n"
def test_sum_equals_bad_tolerance_raises(cross_rules_dir, parsed_tables):
# --- sum_equals ------------------------------------------------------------------
def test_sum_equals_valid(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "sum_equals", "target": "c", "parts": ["a", "b"], "tolerance": 0.1}, fields_by_name, enums_by_name
)
assert parsed["tolerance"] == 0.1
def test_sum_equals_empty_parts_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="non-empty list"):
_parse({"kind": "sum_equals", "target": "c", "parts": []}, fields_by_name, enums_by_name)
def test_sum_equals_bad_tolerance_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="'tolerance' must be a number"):
parse_cross_rules(cross_rules_dir / "sum_equals_bad_tolerance.yaml", parsed_tables)
_parse(
{"kind": "sum_equals", "target": "c", "parts": ["a"], "tolerance": "x"}, fields_by_name, enums_by_name
)
# --- ratio_equals ------------------------------------------------------------------
def test_ratio_equals_valid(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "ratio_equals", "target": "c", "numerator": "a", "denominator": "b", "power": 2},
fields_by_name, enums_by_name,
)
assert parsed["power"] == 2
def test_ratio_equals_bad_power_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="'power' must be an integer"):
_parse(
{"kind": "ratio_equals", "target": "c", "numerator": "a", "denominator": "b", "power": 1.5},
fields_by_name, enums_by_name,
)
# --- date_offset_equals / date_diff_equals ---------------------------------------------
def test_date_offset_equals_valid(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "date_offset_equals", "base": "d1", "offset_days_field": "n", "target": "d2"},
fields_by_name, enums_by_name,
)
assert parsed["display"].startswith("d2 must equal d1 + n days")
def test_date_offset_equals_bad_tolerance_days_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="'tolerance_days' must be an integer"):
_parse(
{"kind": "date_offset_equals", "base": "d1", "offset_days_field": "n", "target": "d2", "tolerance_days": 1.5},
fields_by_name, enums_by_name,
)
def test_date_diff_equals_valid(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "date_diff_equals", "start": "d1", "end": "d2", "target": "n"}, fields_by_name, enums_by_name
)
assert "d2 - d1" in parsed["display"]
# --- comparison_equals ------------------------------------------------------------------
def test_comparison_equals_valid_with_right_field(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "comparison_equals", "target": "flag", "left": "a", "op": "ge", "right": "n"},
fields_by_name, enums_by_name,
)
assert parsed["right"] == "n"
def test_comparison_equals_valid_with_right_value(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "comparison_equals", "target": "flag", "left": "a", "op": "le", "right_value": 75.0},
fields_by_name, enums_by_name,
)
assert parsed["right_value"] == 75.0
def test_comparison_equals_needs_exactly_one_of_right_or_right_value(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="exactly one of"):
_parse({"kind": "comparison_equals", "target": "flag", "left": "a", "op": "le"}, fields_by_name, enums_by_name)
with pytest.raises(ValueError, match="exactly one of"):
_parse(
{"kind": "comparison_equals", "target": "flag", "left": "a", "op": "le", "right": "n", "right_value": 1},
fields_by_name, enums_by_name,
)
def test_comparison_equals_bad_op_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="'op' must be one of"):
_parse(
{"kind": "comparison_equals", "target": "flag", "left": "a", "op": "nope", "right_value": 1},
fields_by_name, enums_by_name,
)
# --- piecewise_lookup ---------------------------------------------------------------------
def test_piecewise_lookup_valid_and_enum_checked(fields_by_name, enums_by_name):
parsed = _parse(
{
"kind": "piecewise_lookup",
"source": "a",
"target": "status",
"breakpoints": [{"max": 10, "value": "red"}, {"max": 20, "value": "green"}],
"otherwise": "blue",
},
fields_by_name, enums_by_name,
)
assert parsed["breakpoints"][0]["value"] == "red"
def test_piecewise_lookup_bad_breakpoint_value_for_enum_target_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="not members of enum"):
_parse(
{
"kind": "piecewise_lookup",
"source": "a",
"target": "status",
"breakpoints": [{"max": 10, "value": "purple"}],
"otherwise": "blue",
},
fields_by_name, enums_by_name,
)
def test_piecewise_lookup_non_increasing_breakpoints_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="strictly increasing"):
_parse(
{
"kind": "piecewise_lookup",
"source": "a",
"target": "n",
"breakpoints": [{"max": 10, "value": "x"}, {"max": 5, "value": "y"}],
"otherwise": "z",
},
fields_by_name, enums_by_name,
)
def test_piecewise_lookup_empty_breakpoints_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="non-empty list"):
_parse(
{"kind": "piecewise_lookup", "source": "a", "target": "n", "breakpoints": [], "otherwise": "z"},
fields_by_name, enums_by_name,
)
# --- requires ---------------------------------------------------------------------------------
def test_requires_truthy_condition(fields_by_name, enums_by_name):
parsed = _parse({"kind": "requires", "if_field": "flag", "then_field": "a"}, fields_by_name, enums_by_name)
assert "if_value" not in parsed
def test_requires_scalar_if_value_on_enum_field_is_uppercased(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "requires", "if_field": "status", "if_value": "red", "then_field": "a"},
fields_by_name, enums_by_name,
)
assert parsed["if_value"] == "RED"
def test_requires_list_if_value_on_enum_field_is_uppercased(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "requires", "if_field": "status", "if_value": ["red", "green"], "then_field": "a"},
fields_by_name, enums_by_name,
)
assert parsed["if_value"] == ["RED", "GREEN"]
def test_requires_then_value_on_enum_field_is_uppercased(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "requires", "if_field": "flag", "then_field": "status", "then_value": "red"},
fields_by_name, enums_by_name,
)
assert parsed["then_value"] == "RED"
def test_requires_if_op_needs_numeric_if_value(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="numeric 'if_value'"):
_parse(
{"kind": "requires", "if_field": "n", "if_op": "gt", "if_value": "x", "then_field": "a"},
fields_by_name, enums_by_name,
)
def test_requires_if_op_bad_op_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="'if_op' must be one of"):
_parse(
{"kind": "requires", "if_field": "n", "if_op": "nope", "if_value": 1, "then_field": "a"},
fields_by_name, enums_by_name,
)
def test_requires_missing_required_key_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="missing key"):
_parse({"kind": "requires", "if_field": "flag"}, fields_by_name, enums_by_name)
# --- forbidden_if -----------------------------------------------------------------------------
def test_forbidden_if_valid(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "forbidden_if", "if_field": "flag", "if_value": False, "then_fields": ["a", "b"]},
fields_by_name, enums_by_name,
)
assert parsed["then_fields"] == ["a", "b"]
def test_forbidden_if_then_allowed_values_normalized_for_enum(fields_by_name, enums_by_name):
parsed = _parse(
{
"kind": "forbidden_if", "if_field": "flag", "if_value": False,
"then_fields": ["status"], "then_allowed_values": ["red"],
},
fields_by_name, enums_by_name,
)
assert parsed["then_allowed_values"] == ["RED"]
def test_forbidden_if_empty_then_fields_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="non-empty list"):
_parse({"kind": "forbidden_if", "if_field": "flag", "then_fields": []}, fields_by_name, enums_by_name)
def test_forbidden_if_then_allowed_values_not_a_list_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="must be a list"):
_parse(
{"kind": "forbidden_if", "if_field": "flag", "then_fields": ["a"], "then_allowed_values": "nope"},
fields_by_name, enums_by_name,
)
# --- any_of_implies ---------------------------------------------------------------------------
def test_any_of_implies_valid(fields_by_name, enums_by_name):
parsed = _parse(
{
"kind": "any_of_implies",
"target": "flag",
"conditions": [{"field": "n", "op": "lt", "value": 7}, {"field": "flag", "op": "truthy"}],
},
fields_by_name, enums_by_name,
)
assert len(parsed["conditions"]) == 2
def test_any_of_implies_condition_missing_value_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="needs a 'value'"):
_parse(
{"kind": "any_of_implies", "target": "flag", "conditions": [{"field": "n", "op": "lt"}]},
fields_by_name, enums_by_name,
)
def test_any_of_implies_condition_bad_op_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="condition 'op' must be one of"):
_parse(
{"kind": "any_of_implies", "target": "flag", "conditions": [{"field": "n", "op": "nope", "value": 1}]},
fields_by_name, enums_by_name,
)
def test_any_of_implies_enum_condition_value_uppercased(fields_by_name, enums_by_name):
parsed = _parse(
{"kind": "any_of_implies", "target": "flag", "conditions": [{"field": "status", "op": "eq", "value": "red"}]},
fields_by_name, enums_by_name,
)
assert parsed["conditions"][0]["value"] == "RED"
# --- conditional_equals -----------------------------------------------------------------------
def test_conditional_equals_valid(fields_by_name, enums_by_name):
parsed = _parse(
{
"kind": "conditional_equals", "if_field": "flag", "if_value": True,
"target": "n", "value_if_true": 6, "value_if_false": 5,
},
fields_by_name, enums_by_name,
)
assert parsed["value_if_true"] == 6
def test_conditional_equals_missing_key_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="missing key"):
_parse({"kind": "conditional_equals", "if_field": "flag", "target": "n"}, fields_by_name, enums_by_name)
# --- generic cross-rule structure checks --------------------------------------------------
def test_unsupported_kind_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="unsupported kind"):
_parse({"kind": "not_real"}, fields_by_name, enums_by_name)
def test_unknown_key_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="unknown key"):
_parse({"kind": "order", "fields": ["a", "n"], "op": "le", "surprise": 1}, fields_by_name, enums_by_name)
def test_rule_not_a_mapping_raises(fields_by_name, enums_by_name):
with pytest.raises(ValueError, match="must be a mapping"):
_parse("just a string", fields_by_name, enums_by_name)
# --- parse_cross_rules: file-level parsing ------------------------------------------------
def test_parse_cross_rules_valid_file(cross_rules_dir, rich_table_spec, rich_enums_spec):
result = parse_cross_rules(cross_rules_dir / "valid.yaml", [rich_table_spec], rich_enums_spec)
assert "t" in result
def test_parse_cross_rules_missing_file_raises(tmp_path, rich_table_spec):
with pytest.raises(FileNotFoundError):
parse_cross_rules(tmp_path / "missing.yaml", [rich_table_spec])
def test_parse_cross_rules_empty_file_returns_empty_dict(cross_rules_dir, rich_table_spec):
assert parse_cross_rules(cross_rules_dir / "empty_file.yaml", [rich_table_spec]) == {}
def test_parse_cross_rules_unknown_table_raises(cross_rules_dir, rich_table_spec):
with pytest.raises(ValueError, match="unknown table"):
parse_cross_rules(cross_rules_dir / "unknown_table.yaml", [rich_table_spec])
def test_parse_cross_rules_not_a_mapping_raises(cross_rules_dir, rich_table_spec):
with pytest.raises(ValueError, match="must map table name"):
parse_cross_rules(cross_rules_dir / "not_a_mapping.yaml", [rich_table_spec])
+1 -1
View File
@@ -42,7 +42,7 @@ def test_enum_field_resolves_end_to_end(spec_ok_dir):
parsed_tables, _, _ = parse_spec(spec_ok_dir)
test_table = next(t for t in parsed_tables if t["table"]["table_name"] == "test_table")
field7 = next(f for f in test_table["fields"] if f["field_name"] == "field7")
assert field7["enum_class"] == "TestEnumField"
assert field7["enum_class"] == "TestEnum"
def test_returns_a_three_tuple(spec_ok_dir):
+56 -14
View File
@@ -6,10 +6,13 @@ from ps_core.parse_spec import (
validate_foreign_keys,
)
ENUM_NAMES = {"test_enum"}
def _checks_by_kind(field: dict) -> dict:
return {c["kind"]: c for c in field["checks"]}
# --- parse_single_table: happy paths -----------------------------------------
def test_valid_minimal_table(tables_dir):
@@ -22,17 +25,42 @@ def test_valid_minimal_table(tables_dir):
assert id_field["sql_type"] == "sa.String(36)"
name_field = result["fields"][1]
assert name_field["required"] is False
assert name_field["rule"] is None
assert name_field["checks"] == []
def test_enum_field_resolves_known_ref(tables_dir):
result = parse_single_table(tables_dir / "enum_known_ref.yaml", ENUM_NAMES)
status = next(f for f in result["fields"] if f["field_name"] == "status")
assert status["pydantic_type"] == "EnumField"
assert status["enum_class"] == "TestEnumField"
assert status["enum_class"] == "TestEnum"
assert status["enum_ref"] == "test_enum"
assert status["rule_display"] == "one of test_enum"
def test_multi_rule_field_stacks_and_orders_checks(tables_dir):
result = parse_single_table(tables_dir / "multi_rule_field.yaml", ENUM_NAMES)
code = next(f for f in result["fields"] if f["field_name"] == "code")
kinds = [c["kind"] for c in code["checks"]]
# fixed order regardless of YAML order: strip, upper, required, max_length, regex
assert kinds == ["strip", "upper", "required", "max_length", "regex"]
assert code["required"] is True
def test_range_and_required_together(tables_dir):
result = parse_single_table(tables_dir / "custom_messages.yaml", ENUM_NAMES)
age = next(f for f in result["fields"] if f["field_name"] == "age")
checks = _checks_by_kind(age)
assert checks["required"]["kind"] == "required"
assert checks["range"] == {"kind": "range", "min": 0, "max": 120}
def test_default_messages_when_not_given(tables_dir):
result = parse_single_table(tables_dir / "custom_messages.yaml", ENUM_NAMES)
# id has no rules at all — sanity that unrelated fields are untouched
id_field = result["fields"][0]
assert id_field["checks"] == []
# --- parse_single_table: structural failures ---------------------------------
def test_missing_table_section_raises(tables_dir):
@@ -80,18 +108,25 @@ def test_multiple_primary_keys_raises(tables_dir):
parse_single_table(tables_dir / "multiple_primary_keys.yaml", ENUM_NAMES)
# --- rules ---------------------------------------------------------------------
# --- rule legality per type -----------------------------------------------------
def test_rule_not_valid_for_type_raises(tables_dir):
with pytest.raises(ValueError, match="cannot use rule 'range'"):
with pytest.raises(ValueError, match=r"cannot use rule\(s\) \['range'\]"):
parse_single_table(tables_dir / "rule_not_valid_for_type.yaml", ENUM_NAMES)
def test_unknown_rule_raises(tables_dir):
with pytest.raises(ValueError, match="cannot use rule 'not_a_real_rule'"):
def test_unknown_rule_for_type_raises(tables_dir):
with pytest.raises(ValueError, match=r"cannot use rule\(s\) \['not_future'\]"):
parse_single_table(tables_dir / "unknown_rule.yaml", ENUM_NAMES)
def test_strip_on_wrong_type_raises(tables_dir):
with pytest.raises(ValueError, match=r"cannot use rule\(s\) \['strip'\]"):
parse_single_table(tables_dir / "strip_on_wrong_type.yaml", ENUM_NAMES)
# --- range ---------------------------------------------------------------------------
def test_range_missing_min_max_raises(tables_dir):
with pytest.raises(ValueError, match="missing 'min' or 'max'"):
parse_single_table(tables_dir / "range_missing_min_max.yaml", ENUM_NAMES)
@@ -102,7 +137,19 @@ def test_range_min_gt_max_raises(tables_dir):
parse_single_table(tables_dir / "range_min_gt_max.yaml", ENUM_NAMES)
# --- enums -----------------------------------------------------------------------
# --- max_length / regex ---------------------------------------------------------------
def test_bad_max_length_raises(tables_dir):
with pytest.raises(ValueError, match="positive integer"):
parse_single_table(tables_dir / "bad_max_length.yaml", ENUM_NAMES)
def test_bad_regex_pattern_raises(tables_dir):
with pytest.raises(ValueError, match="invalid regex pattern"):
parse_single_table(tables_dir / "bad_regex_pattern.yaml", ENUM_NAMES)
# --- enums -----------------------------------------------------------------------------
def test_enum_missing_ref_raises(tables_dir):
with pytest.raises(ValueError, match="has no 'enum' key"):
@@ -114,18 +161,13 @@ def test_enum_unknown_ref_raises(tables_dir):
parse_single_table(tables_dir / "enum_unknown_ref.yaml", ENUM_NAMES)
# --- foreign_key / required --------------------------------------------------------
# --- foreign_key -----------------------------------------------------------------------
def test_bad_foreign_key_format_raises(tables_dir):
with pytest.raises(ValueError, match="expected 'table.column'"):
parse_single_table(tables_dir / "bad_foreign_key_format.yaml", ENUM_NAMES)
def test_bad_required_type_raises(tables_dir):
with pytest.raises(ValueError, match="must be true or false"):
parse_single_table(tables_dir / "bad_required_type.yaml", ENUM_NAMES)
# --- parse_tables: directory-level checks -----------------------------------------
def test_parse_tables_reads_multiple_files(tables_dir):
+106 -2
View File
@@ -8,7 +8,7 @@ import sqlalchemy as sa
from pydantic import BaseModel, ValidationError
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from ps_core.runtime import check_foreign_keys, ingest, load_row, validate_row
from ps_core.runtime import check_foreign_keys, check_unique_fields, ingest, load_row, validate_row
# ---------------------------------------------------------------------------
@@ -72,6 +72,8 @@ def test_validate_row_failure_shape():
assert result["validated"] is False
errors = json.loads(result["errors"])
assert "name" in errors
assert set(errors["name"]) == {"rule", "message"}
assert errors["name"]["rule"] == "missing" # Pydantic's own built-in type for an absent required field
def test_validate_row_never_touches_a_database_object():
@@ -127,7 +129,8 @@ def test_check_foreign_keys_flags_orphan_and_spares_valid_link(engine):
assert good_child.validated is True
assert bad_child.validated is False
assert "parent_id" in json.loads(bad_child.errors)
bad_errors = json.loads(bad_child.errors)
assert bad_errors["parent_id"]["rule"] == "foreign_key"
assert null_child.validated is True # a NULL link is not a broken link, left untouched
assert null_child.errors is None
@@ -154,6 +157,107 @@ def test_check_foreign_keys_merges_with_existing_errors(engine):
assert "parent_id" in errs
# --- check_unique_fields ------------------------------------------------------------
def test_check_unique_fields_flags_every_row_in_a_duplicate_group(engine):
class_lookup = {"parent": _Parent}
parsed_tables = [
{"table": {"table_name": "parent"}, "fields": [
{"field_name": "name", "unique": True},
]},
]
with Session(engine) as session:
a = _Parent(name="dup", validated=True)
b = _Parent(name="dup", validated=True)
c = _Parent(name="unique", validated=True)
session.add_all([a, b, c])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
session.refresh(b)
session.refresh(c)
assert a.validated is False
assert b.validated is False
assert json.loads(a.errors)["name"]["rule"] == "unique"
assert json.loads(b.errors)["name"]["rule"] == "unique"
assert c.validated is True
assert c.errors is None
def test_check_unique_fields_ignores_fields_not_marked_unique(engine):
class_lookup = {"parent": _Parent}
parsed_tables = [
{"table": {"table_name": "parent"}, "fields": [
{"field_name": "name", "unique": False},
]},
]
with Session(engine) as session:
a = _Parent(name="dup", validated=True)
b = _Parent(name="dup", validated=True)
session.add_all([a, b])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
assert a.validated is True # unique not requested for this field — untouched
def test_check_unique_fields_ignores_null_values(engine):
class_lookup = {"child": _Child}
parsed_tables = [
{"table": {"table_name": "child"}, "fields": [
{"field_name": "parent_id", "unique": True},
]},
]
with Session(engine) as session:
a = _Child(parent_id=None, validated=True)
b = _Child(parent_id=None, validated=True) # two NULLs — not duplicates of each other
session.add_all([a, b])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
session.refresh(b)
assert a.validated is True
assert b.validated is True
assert a.errors is None
assert b.errors is None
def test_check_unique_fields_merges_with_existing_errors(engine):
class_lookup = {"parent": _Parent}
parsed_tables = [
{"table": {"table_name": "parent"}, "fields": [
{"field_name": "name", "unique": True},
]},
]
with Session(engine) as session:
a = _Parent(name="dup", validated=True, errors=json.dumps({"other_field": "already broken"}))
b = _Parent(name="dup", validated=True)
session.add_all([a, b])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
errs = json.loads(a.errors)
assert errs["other_field"] == "already broken"
assert errs["name"]["rule"] == "unique"
# ---------------------------------------------------------------------------
# full pipeline: parse a real spec -> generate real files -> exec -> ingest
# ---------------------------------------------------------------------------
Generated
+1 -1
View File
@@ -228,7 +228,7 @@ wheels = [
[[package]]
name = "ps-core"
version = "0.1.0"
version = "0.2.1"
source = { editable = "." }
dependencies = [
{ name = "jinja2" },