8 Commits

Author SHA1 Message Date
AlbertoPMDM aab4a11334 updated way in which rules are defined and parsed in order to be able to apply multiple 2026-09-07 18:32:19 -06:00
AlbertoPMDM c15e161a72 tests / fixtures 2026-09-07 18:31:16 -06:00
AlbertoPMDM d20ca04f49 updated rule templates 2026-09-07 18:30:42 -06:00
AlbertoPMDM 26d0ac4f8a updated rule format 2026-09-07 18:30:21 -06:00
AlbertoPMDM eea7d6a8ad updated 2026-09-07 18:29:46 -06:00
AlbertoPMDM a44bab3c2c updated version 2026-09-07 18:27:57 -06:00
AlbertoPMDM 51562f64b2 updated readme 2026-09-07 18:05:38 -06:00
AlbertoPMDM 61d99591e5 updated version 2026-09-07 18:05:27 -06:00
31 changed files with 1964 additions and 714 deletions
+145 -55
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,143 @@ 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).
```yaml
test_table:
- kind: requires
if_field: field6
if_value: true
then_field: field3
message: "field3 is required when field6 is true"
```
## Cross-field rules (`cross_rules.yaml`)
Supported kinds:
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,8 +181,8 @@ 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 generated.schema import Base, TestTable, ForeignTable
from generated.validation import TestTableCheck, ForeignTableCheck
from ps_core.runtime import ingest, check_foreign_keys
from ps_core.parse_spec import parse_spec
from sqlalchemy import create_engine
@@ -121,7 +198,10 @@ 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,
{"test_table": TestTable, "foreign_table": ForeignTable},
)
session.commit()
```
@@ -129,3 +209,13 @@ with Session(engine) as session:
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.
## 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.
-1
View File
@@ -4,4 +4,3 @@ test_table:
if_value: true
then_field: field3
message: "field3 is required when field6 is true"
+3 -8
View File
@@ -10,27 +10,22 @@ 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
field5:
type: datetime
required: false
field6:
type: bool
required: false
field7:
type: enum
enum: test_enum
required: false
+65 -56
View File
@@ -1,60 +1,77 @@
# -*- 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 a generic message built from a `label` (normally the field
name, passed in automatically by the generated checker function) —
matching the pattern below. To change the wording for every field that
uses a given rule, edit the f-string here once; there is no per-field
message override in the spec YAML.
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
"""
from __future__ import annotations
import re as _re
from datetime import date
from typing import Annotated, Optional
from pydantic import AfterValidator, BeforeValidator, StringConstraints
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 ValueError(f"{label} is required")
return v
def check_range(v, lo, hi, label: str = "value"):
if v < lo or v > hi:
raise ValueError(f"{label} must be between {lo} and {hi}, got {v}")
return v
def check_not_future(v: date, label: str = "value"):
if v > date.today():
raise ValueError(f"{label} must not be a future date, got {v}")
return v
def check_regex(v: str, pattern: str, label: str = "value"):
if not _re.fullmatch(pattern, v):
raise ValueError(f"{label} does not match the expected format, got {v!r}")
return v
def check_max_length(v: str, max_length: int, label: str = "value"):
if len(v) > max_length:
raise ValueError(f"{label} exceeds {max_length} characters, got {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 +80,18 @@ 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 ValueError(f"{label}: unrecognized type for boolean field: {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 ValueError(f"{label} must be one of: {sorted(allowed)}, got {v!r}")
return enum_cls(v)
+303 -61
View File
@@ -2,88 +2,317 @@
"""
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 _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}):",
f" raise ValueError(f\"{{_msg}}: {{self.{left}}} vs {{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}:",
f" raise ValueError(f\"{{_msg}}: {{self.{a}}} vs {{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}:",
f" raise ValueError(f\"{{_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}:",
f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected:.4f}}\")",
]
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}:",
f" raise ValueError(f\"{{_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}:",
f" raise ValueError(f\"{{_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:",
f" raise ValueError(f\"{{_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(
f" raise ValueError(f\"{{_msg}}: got {{_actual}}, expected {{_expected}} for {source}={{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"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(f" raise ValueError({msg!r})")
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"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(f" raise ValueError({msg!r})")
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(f" raise ValueError(f\"{{_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(f" raise ValueError(f\"{{_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 +330,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 []),
)
+445 -80
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,18 @@ 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")
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),
"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 +421,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 +498,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 +532,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 +659,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 +681,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 +693,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 +794,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 +803,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 +843,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
-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
+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 }}
+16 -5
View File
@@ -1,9 +1,20 @@
# -*- 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 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
+56 -70
View File
@@ -40,81 +40,67 @@ def spec_bad_fk_dir() -> Path:
return FIXTURES_DIR / "spec_bad_fk"
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,
"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 -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
+94 -107
View File
@@ -1,94 +1,126 @@
from datetime import date, timedelta
from enum import Enum
import pytest
from pydantic import BaseModel, ValidationError
from ps_core.constraints import (
FlexBool,
MaxLenStr,
NotFutureDate,
RangeFloat,
RangeInt,
RegexStr,
check_enum,
apply_strip,
apply_upper,
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 +128,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"
@@ -153,14 +151,3 @@ def test_normalize_enum_strips_and_uppercases():
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
def test_check_enum_rejects_non_member():
checker = check_enum(_Color)
with pytest.raises(ValueError, match="must be one of"):
checker("BLUE")
+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():
+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):
+315 -87
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,10 @@ 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 datetime import timedelta\n\n"
"class M(BaseModel):\n"
f"{fields}\n"
f"{body}\n"
@@ -57,19 +132,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 +163,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 +362,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 +382,39 @@ 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)
TestTableCheck(field4=date(2024, 1, 1)) # field1 omitted -> required check fires
# unknown enum member
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2024, 1, 1), field7="not_a_member")
TestTableCheck(field1="x", field4=date(2024, 1, 1), field2=999) # range
# future date
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2999, 1, 1))
TestTableCheck(field1="x", field4=date(2999, 1, 1)) # 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"):
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=None)
# 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):