3 Commits

Author SHA1 Message Date
AlbertoPMDM 07d7efe1f4 fixed cross rules error messages 2026-09-14 13:25:06 -06:00
AlbertoPMDM a9d166de6f added a module that does all of the validation, corresponding documentation, and tests 2026-09-08 20:45:09 -06:00
AlbertoPMDM 563aefd79d updated version 2026-09-08 20:44:40 -06:00
6 changed files with 382 additions and 16 deletions
+32 -1
View File
@@ -236,7 +236,7 @@ for a cross rule). Each entry is `{"rule": <name>, "message": <text>}`:
```json
{
"field2": {"rule": "range", "message": "field2 must be between 1 and 10, got 99"},
"_cross_field": {"rule": "requires", "message": "field3 is required when field6 is true"}
"_cross_field": {"rule": "requires[field6,field3]", "message": "field3 is required when field6 is true"}
}
```
@@ -250,6 +250,19 @@ and `unique` set the same `rule` key by hand, in
`check_foreign_keys`/`check_unique_fields`, since neither ever goes
through Pydantic at all.
A cross-rule's `rule` is not just its kind (`order`, `requires`, ...) —
it's the kind plus every field the rule is about, e.g.
`piecewise_lookup[pnn_edad_gestacional_sem,pnn_clasificacion_eg]`. The
kind alone isn't specific enough: a table can have two different
`requires` rules about entirely different fields, and both would
otherwise collapse into the same reason in any report grouped by `rule`.
This field list is computed once, from the rule's own definition, at
generation time — never from a row's data — so it's identical across
every row that fails that same rule, unlike `message`, which bakes in
the actual failing values and is close to unique per row. Group a report
by `rule`, not by `message`, if you want a count per reason rather than
a near-unique bucket per row.
## A note on cross-rule messages
Field-level rules (`required`, `range`, `regex`, and so on) never take a
@@ -260,6 +273,24 @@ 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.
## Re-validating data already in the database (`ps_core.validate_all`)
```bash
python -m ps_core.validate_all --spec-dir spec --generated-dir generated
```
Re-runs the full cascade — Pydantic checks, then foreign keys, then
uniqueness — against every row already in the database, rewriting
`validated`/`errors` for each one. Same `--spec-dir`/`--generated-dir`
split as `ps_core.devdata.fill`, for the same reason: `--spec-dir` is
every rule ps_core knows about, `--generated-dir` only says where the
real classes already live.
Use this after a bulk import that didn't go through
`ps_core.runtime.ingest`, after changing a rule in the spec (existing
rows were checked under the old rules), or on demand whenever you want
current data re-checked without touching a single row's actual values.
## Synthetic data for development (`ps_core.devdata`)
Not imported by anything else in `ps_core` — a separate subpackage for
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "ps-core"
version = "0.2.2"
version = "0.2.4"
description = "YAML-driven generator for SQLAlchemy storage models, Pydantic validation contracts, and data dictionaries."
readme = "README.md"
requires-python = ">=3.10"
+40 -13
View File
@@ -19,7 +19,7 @@ from __future__ import annotations
from typing import Any
from ps_core.parse_spec import OP_SYMBOLS
from ps_core.parse_spec import OP_SYMBOLS, _referenced_fields_for_kind
from ps_core.templating import env
# ---------------------------------------------------------------------------
@@ -115,15 +115,31 @@ def _raise(error_type: str, template: str, context_src: str, indent: str = "
return f"{indent}raise PydanticCustomError({error_type!r}, {template!r}, {context_src})"
def _error_type_for_rule(rule: dict[str, Any]) -> str:
"""
A cross rule's `kind` alone (e.g. "requires") is not specific enough:
a table can have two different `requires` rules, about different
fields, and both would collapse into the same reason in any report
grouped by error type. This appends the fields the rule is actually
about — computed once, at generation time, from the rule's own
definition — never from a row's data, so it stays identical across
every row that fails this same rule, unlike the message text (which
bakes in the specific failing values and is unique per row).
"""
fields = _referenced_fields_for_kind(rule["kind"], rule)
return f"{rule['kind']}[{','.join(fields)}]"
def _render_order(rule: dict[str, Any], name: str) -> str:
left, right = rule["fields"]
op_symbol = OP_SYMBOLS[rule["op"]]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{left} is not None and self.{right} is not None:",
f" if not (self.{left} {op_symbol} self.{right}):",
_raise("order", "{_msg}: {left} vs {right}", f"{{'_msg': _msg, 'left': self.{left}, 'right': self.{right}}}"),
_raise(error_type, "{_msg}: {left} vs {right}", f"{{'_msg': _msg, 'left': self.{left}, 'right': self.{right}}}"),
]
return _wrap_method(name, body)
@@ -131,11 +147,12 @@ def _render_order(rule: dict[str, Any], name: str) -> str:
def _render_equals(rule: dict[str, Any], name: str) -> str:
a, b = rule["fields"]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{a} is not None and self.{b} is not None:",
f" if self.{a} != self.{b}:",
_raise("equals", "{_msg}: {a} vs {b}", f"{{'_msg': _msg, 'a': self.{a}, 'b': self.{b}}}"),
_raise(error_type, "{_msg}: {a} vs {b}", f"{{'_msg': _msg, 'a': self.{a}, 'b': self.{b}}}"),
]
return _wrap_method(name, body)
@@ -145,13 +162,14 @@ def _render_sum_equals(rule: dict[str, Any], name: str) -> str:
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"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and {none_checks}:",
f" _expected = {sum_expr}",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"sum_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -163,13 +181,14 @@ def _render_ratio_equals(rule: dict[str, Any], name: str) -> str:
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"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{num} is not None and self.{den} not in (None, 0):",
f" _expected = self.{num} / ({denom_expr})",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"ratio_equals", "{_msg}: got {got}, expected {expected:.4f}",
error_type, "{_msg}: got {got}, expected {expected:.4f}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -180,13 +199,14 @@ 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"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{base} is not None and self.{offset} is not None:",
f" _expected = self.{base} + timedelta(days=self.{offset})",
f" if abs((self.{target} - _expected).days) > {tol!r}:",
_raise(
"date_offset_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -197,13 +217,14 @@ 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"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{start} is not None and self.{end} is not None:",
f" _expected = (self.{end} - self.{start}).days",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"date_diff_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -215,6 +236,7 @@ def _render_comparison_equals(rule: dict[str, Any], name: str) -> str:
op_symbol = OP_SYMBOLS[op]
tol = rule.get("tolerance", 0)
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
if "right" in rule:
right_field = rule["right"]
@@ -235,7 +257,7 @@ def _render_comparison_equals(rule: dict[str, Any], name: str) -> str:
f" _expected = bool({cond_expr})",
f" if bool(self.{target}) != _expected:",
_raise(
"comparison_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -246,6 +268,7 @@ 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"]
error_type = _error_type_for_rule(rule)
branch: list[str] = []
for i, bp in enumerate(breakpoints):
@@ -261,7 +284,7 @@ def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
body.append(" if _actual != _expected:")
body.append(
_raise(
"piecewise_lookup", "{_msg}: got {got}, expected {expected} for " + source + "={source_value}",
error_type, "{_msg}: got {got}, expected {expected} for " + source + "={source_value}",
f"{{'_msg': _msg, 'got': _actual, 'expected': _expected, 'source_value': self.{source}}}",
)
)
@@ -271,6 +294,7 @@ def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
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"]
error_type = _error_type_for_rule(rule)
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
if "then_value" in rule:
@@ -280,7 +304,7 @@ def _render_requires(rule: dict[str, Any], name: str) -> str:
body.append(f" if self.{then_field} is None:")
body.append(
_raise(
"requires", "{_msg}",
error_type, "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{then_field}}}",
)
)
@@ -291,6 +315,7 @@ 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"]
error_type = _error_type_for_rule(rule)
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
for tf in then_fields:
@@ -298,7 +323,7 @@ def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
body.append(f" if _val is not None and _val not in {allowed_values!r}:")
body.append(
_raise(
"forbidden_if", "{_msg}",
error_type, "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{tf}, 'value': _val}}",
)
)
@@ -308,6 +333,7 @@ def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
def _render_any_of_implies(rule: dict[str, Any], name: str) -> str:
target = rule["target"]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
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]
@@ -317,7 +343,7 @@ def _render_any_of_implies(rule: dict[str, Any], name: str) -> str:
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"any_of_implies", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
@@ -329,6 +355,7 @@ def _render_conditional_equals(rule: dict[str, Any], name: str) -> str:
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"]
error_type = _error_type_for_rule(rule)
cond = _condition_expr(if_field, rule)
body = [
f"_msg = {msg!r}",
@@ -341,7 +368,7 @@ def _render_conditional_equals(rule: dict[str, Any], name: str) -> str:
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"conditional_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
+124
View File
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
"""
python -m ps_core.validate_all --spec-dir spec --generated-dir generated --db-url sqlite:///dev.db
Re-runs the full validation cascade against every row already in the
database — Pydantic checks first, then foreign keys, then uniqueness —
and rewrites `validated`/`errors` for every row in every table.
Use this after a bulk import that didn't go through ps_core.runtime.ingest,
after changing a rule in the spec (existing rows were validated under
the old rules), or just to re-check data on demand.
Needs --generated-dir to already hold schema.py/validation.py/enums.py —
run build.py (or ps_core.generate_all) first. This mirrors
ps_core.devdata.fill's own --spec-dir/--generated-dir split: --spec-dir
supplies every rule ps_core knows about, --generated-dir only says where
the real classes live to import.
"""
from __future__ import annotations
import argparse
import importlib
import sys
from pathlib import Path
from typing import Any
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from ps_core.parse_spec import parse_spec
from ps_core.runtime import check_foreign_keys, check_unique_fields, validate_row
def _import_generated(generated_dir: Path):
generated_dir = generated_dir.resolve()
pkg_name = generated_dir.name
sys.path.insert(0, str(generated_dir.parent))
try:
schema = importlib.import_module(f"{pkg_name}.schema")
validation = importlib.import_module(f"{pkg_name}.validation")
finally:
sys.path.remove(str(generated_dir.parent))
return schema, validation
def _build_lookups(parsed_tables, schema_mod, validation_mod):
class_lookup, check_lookup = {}, {}
for table_spec in parsed_tables:
class_name = table_spec["table"]["class_name"]
table_name = table_spec["table"]["table_name"]
class_lookup[table_name] = getattr(schema_mod, class_name)
check_lookup[table_name] = getattr(validation_mod, f"{class_name}Check")
return class_lookup, check_lookup
def revalidate_all(
session: Any,
parsed_tables: list[dict],
class_lookup: dict[str, type],
check_lookup: dict[str, type],
) -> None:
"""
Phase 1: run every row already in every table through validate_row,
rewriting validated/errors. Phase 2/3: check_foreign_keys and
check_unique_fields, same as fill.py's final phases, since neither
of those ever goes through Pydantic — they need their own pass
regardless of what phase 1 found.
"""
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
table_cls = class_lookup[table_name]
check_cls = check_lookup[table_name]
for row in session.query(table_cls).all():
raw = {
f["field_name"]: getattr(row, f["field_name"])
for f in table_spec["fields"] if not f["primary_key"]
}
result = validate_row(raw, check_cls)
row.validated = result["validated"]
row.errors = result["errors"]
session.commit()
print(" validated every row")
check_foreign_keys(session, parsed_tables, class_lookup)
session.commit()
print(" checked foreign keys")
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
print(" checked unique fields")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec-dir", type=Path, required=True)
parser.add_argument(
"--generated-dir", type=Path, required=True,
help="where build.py wrote schema.py/validation.py/enums.py",
)
parser.add_argument("--db-url", default="sqlite:///dev.db")
args = parser.parse_args()
print(f"Parsing spec from {args.spec_dir} ...")
try:
parsed_tables, _, _ = parse_spec(args.spec_dir)
except (ValueError, FileNotFoundError) as e:
print(f"\nSpec error: {e}", file=sys.stderr)
sys.exit(1)
print(f"Importing generated code from {args.generated_dir} ...")
schema_mod, validation_mod = _import_generated(args.generated_dir)
class_lookup, check_lookup = _build_lookups(parsed_tables, schema_mod, validation_mod)
engine = create_engine(args.db_url, echo=False)
print(f"Revalidating {len(parsed_tables)} table(s) in {args.db_url} ...")
with Session(engine) as session:
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
print("Done.")
if __name__ == "__main__":
main()
+31 -1
View File
@@ -295,6 +295,34 @@ def test_render_requires_with_if_op():
M(n=3, flag=False)
def test_error_type_disambiguates_two_rules_of_the_same_kind_on_one_table():
# a table with two different `requires` rules must produce two
# distinguishable error types — the generic "requires" alone would
# make them indistinguishable in any report grouped by type
rule_a = {"kind": "requires", "if_field": "flag_a", "then_field": "x", "message": None, "display": "d1"}
rule_b = {"kind": "requires", "if_field": "flag_b", "then_field": "y", "message": None, "display": "d2"}
body_a = render_cross_rule(rule_a, 0)
body_b = render_cross_rule(rule_b, 1)
ns = _wrap_in_model(
body_a + "\n" + body_b,
" flag_a: Optional[bool] = None\n x: Optional[int] = None\n"
" flag_b: Optional[bool] = None\n y: Optional[int] = None\n",
)
M = ns["M"]
with pytest.raises(ValidationError) as exc_a:
M(flag_a=True, x=None, flag_b=False)
with pytest.raises(ValidationError) as exc_b:
M(flag_a=False, flag_b=True, y=None)
type_a = exc_a.value.errors()[0]["type"]
type_b = exc_b.value.errors()[0]["type"]
assert type_a == "requires[flag_a,x]"
assert type_b == "requires[flag_b,y]"
assert type_a != type_b
def test_render_forbidden_if():
rule = {
"kind": "forbidden_if", "if_field": "flag", "if_value": False, "then_fields": ["a"],
@@ -420,6 +448,8 @@ def test_full_validation_file_behaves_end_to_end(spec_ok_dir):
with pytest.raises(ValidationError, match="field3 is required when field6 is true") as exc_info:
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=None)
assert exc_info.value.errors()[0]["type"] == "requires" # the cross-rule kind, not "value_error"
# the cross-rule kind, not "value_error" — plus the fields it's about,
# since a table could have more than one "requires" rule
assert exc_info.value.errors()[0]["type"] == "requires[field6,field3]"
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=0.5)
+154
View File
@@ -0,0 +1,154 @@
import json
import sys
import uuid
import sqlalchemy as sa
from sqlalchemy.orm import Session
from ps_core.generate_all import generate_all
from ps_core.parse_spec import parse_spec
from ps_core.validate_all import _build_lookups, revalidate_all
def _build_and_import(spec_dir, out_dir):
generate_all(spec_dir, out_dir)
pkg_name = out_dir.name
sys.path.insert(0, str(out_dir.parent))
try:
import importlib
schema = importlib.import_module(f"{pkg_name}.schema")
validation = importlib.import_module(f"{pkg_name}.validation")
finally:
sys.path.remove(str(out_dir.parent))
return schema, validation
def _setup(spec_devdata_dir, tmp_path):
parsed_tables, enums_spec, _ = parse_spec(spec_devdata_dir)
out_dir = tmp_path / f"gen_{uuid.uuid4().hex}"
schema_mod, validation_mod = _build_and_import(spec_devdata_dir, out_dir)
class_lookup, check_lookup = _build_lookups(parsed_tables, schema_mod, validation_mod)
engine = sa.create_engine("sqlite://")
schema_mod.Base.metadata.create_all(engine)
return parsed_tables, class_lookup, check_lookup, engine
def test_revalidate_all_flags_a_row_inserted_without_any_checks(spec_devdata_dir, tmp_path):
parsed_tables, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
Widget = class_lookup["widget"]
with Session(engine) as session:
# inserted directly, bypassing ingest/validate_row entirely —
# quantity is out of range, and validated/errors were never set
bad = Widget(code="ABC", quantity=999)
session.add(bad)
session.commit()
assert bad.validated is False # the schema's own default, never actually checked
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
session.refresh(bad)
assert bad.validated is False
errs = json.loads(bad.errors)
assert errs["quantity"]["rule"] == "range"
def test_revalidate_all_marks_a_good_row_valid(spec_devdata_dir, tmp_path):
parsed_tables, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
Widget = class_lookup["widget"]
with Session(engine) as session:
good = Widget(code="ABC", quantity=5, color="RED")
session.add(good)
session.commit()
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
session.refresh(good)
assert good.validated is True
assert good.errors is None
def test_revalidate_all_re_checks_after_a_row_becomes_stale(spec_devdata_dir, tmp_path):
# simulates: a row was valid when first checked, but something about
# it (or the rules) has since changed — revalidate_all must actually
# re-run the checks, not just trust the existing validated flag
parsed_tables, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
Widget = class_lookup["widget"]
with Session(engine) as session:
row = Widget(code="ABC", quantity=5, validated=True, errors=None)
session.add(row)
session.commit()
row.quantity = 999 # now invalid, but validated/errors still say otherwise
session.commit()
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
session.refresh(row)
assert row.validated is False
assert json.loads(row.errors)["quantity"]["rule"] == "range"
def test_revalidate_all_catches_a_foreign_key_that_became_orphaned(spec_devdata_dir, tmp_path):
parsed_tables, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
Widget, Order = class_lookup["widget"], class_lookup["order"]
with Session(engine) as session:
w = Widget(code="ABC", quantity=5)
session.add(w)
session.commit()
order = Order(widget_id=w.id, validated=True)
session.add(order)
session.commit()
session.delete(w) # the parent is gone — order.widget_id is now an orphan
session.commit()
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
session.refresh(order)
assert order.validated is False
assert json.loads(order.errors)["widget_id"]["rule"] == "foreign_key"
def test_revalidate_all_catches_duplicates_created_outside_ingest(spec_devdata_dir, tmp_path):
parsed_tables, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
Widget = class_lookup["widget"]
with Session(engine) as session:
a = Widget(code="DUP", quantity=1, validated=True)
b = Widget(code="DUP", quantity=2, validated=True)
session.add_all([a, b])
session.commit()
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
session.refresh(a)
session.refresh(b)
assert a.validated is False
assert b.validated is False
assert json.loads(a.errors)["code"]["rule"] == "unique"
assert json.loads(b.errors)["code"]["rule"] == "unique"
def test_revalidate_all_runs_over_every_table(spec_devdata_dir, tmp_path):
parsed_tables, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
Widget, Order = class_lookup["widget"], class_lookup["order"]
with Session(engine) as session:
w = Widget(code="ABC", quantity=5)
session.add(w)
session.commit()
session.add(Order(widget_id=w.id))
session.commit()
revalidate_all(session, parsed_tables, class_lookup, check_lookup)
assert session.query(Widget).first().validated is True
assert session.query(Order).first().validated is True