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
29 changed files with 59 additions and 1315 deletions
-1
View File
@@ -19,4 +19,3 @@ wheels/
# auto-generated testing files
generated
*.db
+7 -94
View File
@@ -105,24 +105,6 @@ to block an insert. Call `ps_core.runtime.check_foreign_keys` after your
insert batch to flag orphans the same way any other rule gets flagged
(`validated=False`, `errors` updated).
## Uniqueness
```yaml
email:
type: text
unique: true
```
Same philosophy as foreign keys, on purpose: **never** a database UNIQUE
constraint, since that could silently reject a row outright rather than
let it be saved and flagged. Call `ps_core.runtime.check_unique_fields`
after your insert batch — it flags every row sharing a duplicate value
on that column (a `NULL` is never treated as a duplicate of another
`NULL`), the same way `check_foreign_keys` flags orphans.
This checks single-column uniqueness only. There is no `unique_together`
for multi-column uniqueness.
## Cross-field rules (`cross_rules.yaml`)
Table name → list of rules, each a fixed, named **kind** — never a raw
@@ -201,13 +183,12 @@ in-process or load it from disk later.
```python
from generated.schema import Base, TestTable, ForeignTable
from generated.validation import TestTableCheck, ForeignTableCheck
from ps_core.runtime import ingest, check_foreign_keys, check_unique_fields
from ps_core.runtime import ingest, check_foreign_keys
from ps_core.parse_spec import parse_spec
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
parsed_tables, _, _ = parse_spec("spec")
class_lookup = {"test_table": TestTable, "foreign_table": ForeignTable}
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
@@ -217,38 +198,17 @@ with Session(engine) as session:
session.add(row)
session.commit()
check_foreign_keys(session, parsed_tables, class_lookup)
check_unique_fields(session, parsed_tables, class_lookup)
check_foreign_keys(
session, parsed_tables,
{"test_table": TestTable, "foreign_table": ForeignTable},
)
session.commit()
```
`validate_row` (used inside `ingest`) takes and returns plain data, so it
is safe to run in a separate worker process — only `check_cls` needs to
be importable by name on both sides. `load_row`, `check_foreign_keys`,
and `check_unique_fields` must run in the process that owns the database
session.
## The shape of a stored error
`errors` is a JSON object, one entry per failed field (or `_cross_field`
for a cross rule). Each entry is `{"rule": <name>, "message": <text>}`:
```json
{
"field2": {"rule": "range", "message": "field2 must be between 1 and 10, got 99"},
"_cross_field": {"rule": "requires", "message": "field3 is required when field6 is true"}
}
```
`rule` is never parsed back out of the message — every check in
`constraints.py` and every cross-rule kind raises
`pydantic_core.PydanticCustomError(rule_name, ...)`, which is still a
real `ValueError` (so `except ValueError` keeps working everywhere), but
also sets `e.errors()[i]["type"]` to that exact rule name.
`ps_core.runtime.validate_row` reads that field directly. `foreign_key`
and `unique` set the same `rule` key by hand, in
`check_foreign_keys`/`check_unique_fields`, since neither ever goes
through Pydantic at all.
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
@@ -259,50 +219,3 @@ fields, so a single generic template can't cover them all. Their
optional `message` key is inserted into the generated file as a plain
string literal (safely `repr()`'d), regardless of what characters it
contains — no injection risk from quotes or braces in the text.
## Synthetic data for development (`ps_core.devdata`)
Not imported by anything else in `ps_core` — a separate subpackage for
generating good and deliberately-bad data against a spec, for local
development and testing. Its own dependency direction: it reads
`parse_spec`'s output and calls into `ps_core.runtime`, never the other
way around, so a plain `pip install ps_core` needs none of it.
```bash
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated
```
`--generated-dir` points at wherever `build.py` (or `generate_all`)
already wrote `schema.py`/`validation.py`/`enums.py` — this script
imports the real classes rather than reconstruct them, and does not
regenerate anything itself.
Runs in five phases, across every table together — not table by table —
so table order never matters, even with circular or self-referential
foreign keys: build every table's skeleton row (every field except
foreign keys) → backfill every foreign key, now that every table has
rows → run real validation → check foreign keys → check unique fields.
Four independent rate flags, each an independent coin flip per row (a
single row can be more than one of these at once):
| flag | default | what it does |
|---|---|---|
| `--count` | `20` | rows generated per table |
| `--orphan-rate` | `0.0` | fraction of rows whose foreign key(s) point at nothing on purpose |
| `--faulty-rate` | `0.0` | fraction of rows with one randomly chosen field deliberately breaking its own rule |
| `--repeated-rate` | `0.0` | fraction of rows whose `unique: true` field(s) are copied from an earlier row, on purpose |
```bash
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated \
--count 100 --orphan-rate 0.3 --faulty-rate 0.3 --repeated-rate 0.2
```
`devdata.good` builds values by reading `field["checks"]` directly — no
retries, no calls into Pydantic, every value correct by construction.
`devdata.faulty` breaks one field's own rule the same deterministic way.
Only cross-field-rule violations need Pydantic at all
(`faulty_row_for_cross_rule`): since a cross rule's condition lives in
generated code, not in any field's `checks`, there's nothing structured
to read, so that one function generates candidates and asks
`check_cls(**row)` to say when one actually violates the rule.
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "ps-core"
version = "0.2.1"
version = "0.1.0"
description = "YAML-driven generator for SQLAlchemy storage models, Pydantic validation contracts, and data dictionaries."
readme = "README.md"
requires-python = ">=3.10"
-1
View File
@@ -8,7 +8,6 @@ fields:
field1:
type: text
required: true
unique: true
field2:
type: integer
range: true
+16 -36
View File
@@ -5,26 +5,22 @@ Composable validation primitives.
These are written once, by hand, and imported by every generated
validation file. They are never regenerated.
Each raises pydantic_core.PydanticCustomError, not a plain ValueError.
PydanticCustomError IS a ValueError (so every existing `except ValueError`
/ `pytest.raises(ValueError)` still works), but it also carries the rule
name as a real field — e.errors()[i]["type"] — instead of forcing anyone
downstream to parse it back out of the message text. The first argument
to PydanticCustomError below is that rule name; keep it stable, since
ps_core.runtime.validate_row stores it alongside the message.
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.
The message wording is still built here, from a `label` (normally the
field name, passed in automatically by the generated checker function).
To change the wording for every field that uses a given rule, edit the
template string here once.
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 pydantic_core import PydanticCustomError
def apply_strip(v):
"""Transform. Never raises."""
@@ -42,39 +38,31 @@ def apply_upper(v):
def check_required(v, label: str = "value"):
if v is None:
raise PydanticCustomError("required", "{label} is required", {"label": label})
raise ValueError(f"{label} is required")
return v
def check_range(v, lo, hi, label: str = "value"):
if v < lo or v > hi:
raise PydanticCustomError(
"range", "{label} must be between {lo} and {hi}, got {v}", {"label": label, "lo": lo, "hi": hi, "v": v}
)
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 PydanticCustomError("not_future", "{label} must not be a future date, got {v}", {"label": label, "v": v})
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 PydanticCustomError(
"regex", "{label} does not match the expected format, got {v}", {"label": label, "v": 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 PydanticCustomError(
"max_length",
"{label} exceeds {max_length} characters, got {length}",
{"label": label, "max_length": max_length, "length": len(v)},
)
raise ValueError(f"{label} exceeds {max_length} characters, got {len(v)}")
return v
@@ -92,11 +80,7 @@ def coerce_bool(v, label: str = "value"):
return bool(v)
if isinstance(v, str) and v.strip() in ("0", "1"):
return bool(int(v.strip()))
raise PydanticCustomError(
"bool_coercion",
"{label}: unrecognized type for boolean field: {type_name}",
{"label": label, "type_name": str(type(v))},
)
raise ValueError(f"{label}: unrecognized type for boolean field: {type(v)}")
def normalize_enum(v):
@@ -109,9 +93,5 @@ def normalize_enum(v):
def check_enum_membership(v, enum_cls, label: str = "value"):
allowed = {m.value for m in enum_cls}
if v not in allowed:
raise PydanticCustomError(
"enum_membership",
"{label} must be one of: {allowed}, got {v}",
{"label": label, "allowed": sorted(allowed), "v": v},
)
raise ValueError(f"{label} must be one of: {sorted(allowed)}, got {v!r}")
return enum_cls(v)
View File
-95
View File
@@ -1,95 +0,0 @@
# -*- coding: utf-8 -*-
"""
Builds rows that fail exactly one named thing: a single field's own
rule (deterministic, no Pydantic involved), a foreign key (orphaned on
purpose), or a specific cross-field rule (needs Pydantic as an oracle,
since a cross rule's condition lives in generated code, not in any
field's checks).
"""
from __future__ import annotations
import random
import uuid
from datetime import date, timedelta
from typing import Any
from pydantic import ValidationError
from ps_core.devdata.good import good_skeleton_row, good_value
def break_field(field: dict[str, Any]) -> Any:
"""Deterministically violate ONE field's own rule set."""
checks = {c["kind"]: c for c in field["checks"]}
if "required" in checks:
return None
if "range" in checks:
return checks["range"]["max"] + 1
if "max_length" in checks:
return "x" * (checks["max_length"]["max_length"] + 1)
if "regex" in checks:
return "###invalid###"
if "not_future" in checks:
return date.today() + timedelta(days=1)
if field["pydantic_type"] == "EnumField":
return "NOT_A_REAL_MEMBER"
if field["py_type"] == "bool":
return "nonsense"
raise ValueError(f"break_field: '{field['field_name']}' has no rule to break")
def faulty_skeleton_row(
table_spec: dict[str, Any], enums_by_name: dict[str, dict], field_name: str
) -> dict[str, Any]:
"""A good skeleton row except `field_name`, which deliberately fails its own rule."""
row = good_skeleton_row(table_spec, enums_by_name)
target = next(f for f in table_spec["fields"] if f["field_name"] == field_name)
row[field_name] = break_field(target)
return row
def faulty_foreign_key() -> str:
"""A well-formed id that (almost certainly) points at nothing."""
return str(uuid.uuid4())
def faulty_row_for_cross_rule(
table_spec: dict[str, Any],
check_cls: type,
enums_by_name: dict[str, dict],
cross_rule: dict[str, Any] | None = None,
tries: int = 50,
) -> dict[str, Any]:
"""
No single field to break deterministically here — a cross rule
relates fields to each other. Keep nudging fields on an otherwise-good
row until Pydantic raises a cross-rule error (empty `loc`).
Pass `cross_rule` (one entry from cross_rules_spec[table_name]) to
only touch the fields that specific rule actually references, rather
than nudging at random and hoping to hit it.
"""
if cross_rule is not None:
from ps_core.parse_spec import _referenced_fields_for_kind
candidate_names = _referenced_fields_for_kind(cross_rule["kind"], cross_rule)
candidates = [f for f in table_spec["fields"] if f["field_name"] in candidate_names]
else:
candidates = [f for f in table_spec["fields"] if not f["primary_key"] and not f["foreign_key"]]
for _ in range(tries):
row = good_skeleton_row(table_spec, enums_by_name)
target = random.choice(candidates)
row[target["field_name"]] = good_value(target, enums_by_name) # re-roll: may drift out of the relationship
try:
check_cls(**row)
except ValidationError as e:
if any(not err["loc"] for err in e.errors()): # cross-rule errors carry no field location
return row
raise RuntimeError(
f"faulty_row_for_cross_rule: no violation found in {tries} tries — "
f"try more, or pass a narrower `cross_rule`"
)
-211
View File
@@ -1,211 +0,0 @@
# -*- coding: utf-8 -*-
"""
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated --count 100 --orphan-rate 0.3 --faulty-rate 0.5 --repeated-rate 0.2
Fills every table in the spec with synthetic data — good rows, with
optional fractions of deliberately orphaned foreign keys, deliberately
broken field values, and deliberately repeated (duplicate) values on
any field marked `unique: true`. Everything needed to know *what* to
generate comes from --spec-dir; --generated-dir only points at where
build.py already wrote schema.py/validation.py/enums.py, so this script
can import the real classes rather than reconstruct them.
Runs in five phases, across ALL tables together — not table by table —
which is what lets table order stay irrelevant even with circular or
self-referential foreign keys:
1. Skeleton rows for every table (every field except FK), inserted
with FK fields absent. A --faulty-rate fraction of rows get one
randomly chosen field deliberately broken; a --repeated-rate
fraction of rows get their unique-marked field(s) copied from an
earlier row in the same table, on purpose.
2. Every foreign key backfilled — good (a real parent id) or
deliberately orphaned — now that every table already has rows.
3. Real validation against the now-complete row, same as
ps_core.runtime.ingest would do for real data.
4. Foreign keys checked, catching orphans phase 3 structurally cannot.
5. Unique fields checked, catching the repeats from phase 1 the same way.
"""
from __future__ import annotations
import argparse
import importlib
import random
import sys
from pathlib import Path
from typing import Any
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from ps_core.devdata.faulty import break_field, faulty_foreign_key
from ps_core.devdata.good import good_foreign_key, good_skeleton_row
from ps_core.parse_spec import parse_spec
from ps_core.runtime import check_foreign_keys, check_unique_fields, load_row, validate_row
def _import_generated(generated_dir: Path):
generated_dir = generated_dir.resolve()
pkg_name = generated_dir.name
sys.path.insert(0, str(generated_dir.parent))
try:
schema = importlib.import_module(f"{pkg_name}.schema")
validation = importlib.import_module(f"{pkg_name}.validation")
finally:
sys.path.remove(str(generated_dir.parent))
return schema, validation
def _build_lookups(parsed_tables, schema_mod, validation_mod):
class_lookup, check_lookup = {}, {}
for table_spec in parsed_tables:
class_name = table_spec["table"]["class_name"]
table_name = table_spec["table"]["table_name"]
class_lookup[table_name] = getattr(schema_mod, class_name)
check_lookup[table_name] = getattr(validation_mod, f"{class_name}Check")
return class_lookup, check_lookup
def _breakable_fields(table_spec: dict) -> list[dict]:
"""Fields break_field actually knows how to break — see faulty.py."""
return [
f for f in table_spec["fields"]
if f["checks"] or f["pydantic_type"] == "EnumField" or f["py_type"] == "bool"
]
def fill_all(
session: Any,
parsed_tables: list[dict],
enums_by_name: dict[str, dict],
class_lookup: dict[str, type],
check_lookup: dict[str, type],
count: int,
orphan_rate: float,
faulty_rate: float,
repeated_rate: float,
) -> None:
rows_by_table: dict[str, list] = {}
# phase 1: skeletons for every table, any order, FK fields absent.
# faulty_rate breaks one field's own rule; repeated_rate copies a
# unique-marked field's value from an earlier row, on purpose.
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
table_cls = class_lookup[table_name]
breakable = _breakable_fields(table_spec)
unique_fields = [f["field_name"] for f in table_spec["fields"] if f["unique"]]
raw_rows: list[dict] = []
rows = []
for _ in range(count):
raw = good_skeleton_row(table_spec, enums_by_name)
if unique_fields and raw_rows and random.random() < repeated_rate:
source = random.choice(raw_rows)
for uf in unique_fields:
if uf in raw: # a unique field could itself be a foreign key, absent here
raw[uf] = source[uf]
if breakable and random.random() < faulty_rate:
target = random.choice(breakable)
raw[target["field_name"]] = break_field(target)
raw_rows.append(raw)
row = load_row(raw, table_cls)
session.add(row)
rows.append(row)
rows_by_table[table_name] = rows
session.commit()
print(f" inserted {count} skeleton row(s) each, across {len(parsed_tables)} table(s)")
# phase 2: backfill every foreign key, now that every table has rows
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
fk_fields = [f for f in table_spec["fields"] if f["foreign_key"]]
if not fk_fields:
continue
for row in rows_by_table[table_name]:
make_orphan = random.random() < orphan_rate
for f in fk_fields:
target_table, target_col = f["foreign_key"].split(".", 1)
value = (
faulty_foreign_key()
if make_orphan
else good_foreign_key(session, class_lookup[target_table], target_col)
)
setattr(row, f["field_name"], value)
session.commit()
print(" backfilled foreign keys")
# phase 3: real validation, now that every row is actually complete
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
check_cls = check_lookup[table_name]
for row in rows_by_table[table_name]:
raw = {
f["field_name"]: getattr(row, f["field_name"])
for f in table_spec["fields"] if not f["primary_key"]
}
result = validate_row(raw, check_cls)
row.validated = result["validated"]
row.errors = result["errors"]
session.commit()
print(" validated every row")
# phase 4: catch what phase 3 structurally cannot — foreign keys
check_foreign_keys(session, parsed_tables, class_lookup)
session.commit()
print(" checked foreign keys")
# phase 5: catch what phase 3 structurally cannot — uniqueness
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
print(" checked unique fields")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec-dir", type=Path, required=True)
parser.add_argument(
"--generated-dir", type=Path, required=True,
help="where build.py wrote schema.py/validation.py/enums.py",
)
parser.add_argument("--db-url", default="sqlite:///dev.db")
parser.add_argument("--count", type=int, default=20, help="rows per table")
parser.add_argument("--orphan-rate", type=float, default=0.0, help="fraction of rows with a deliberately bad FK")
parser.add_argument("--faulty-rate", type=float, default=0.0, help="fraction of rows with one deliberately broken field")
parser.add_argument(
"--repeated-rate", type=float, default=0.0,
help="fraction of rows with unique-marked field(s) deliberately duplicated from an earlier row",
)
args = parser.parse_args()
print(f"Parsing spec from {args.spec_dir} ...")
try:
parsed_tables, enums_spec, _ = parse_spec(args.spec_dir)
except (ValueError, FileNotFoundError) as e:
print(f"\nSpec error: {e}", file=sys.stderr)
sys.exit(1)
enums_by_name = {e["name"]: e for e in enums_spec}
print(f"Importing generated code from {args.generated_dir} ...")
schema_mod, validation_mod = _import_generated(args.generated_dir)
class_lookup, check_lookup = _build_lookups(parsed_tables, schema_mod, validation_mod)
engine = create_engine(args.db_url, echo=False)
schema_mod.Base.metadata.create_all(engine)
print(f"Filling {len(parsed_tables)} table(s), {args.count} row(s) each, into {args.db_url} ...")
with Session(engine) as session:
fill_all(
session, parsed_tables, enums_by_name, class_lookup, check_lookup,
args.count, args.orphan_rate, args.faulty_rate, args.repeated_rate,
)
print("Done.")
if __name__ == "__main__":
main()
-77
View File
@@ -1,77 +0,0 @@
# -*- coding: utf-8 -*-
"""
Builds plausible, rule-respecting values — read directly from
field["checks"], never by asking Pydantic to accept-or-reject. Fast and
deterministic: every value is correct by construction, no retries.
Foreign key fields are deliberately left out of every row built here —
see fill.py for why, and for how they get filled in afterward.
"""
from __future__ import annotations
import random
import string
from datetime import date, datetime, timedelta
from typing import Any
def _sample_text(field_name: str, checks: dict[str, dict]) -> str:
if "regex" in checks:
raise ValueError(
f"good_value: no generic sampler for a regex pattern on '{field_name}' "
f"({checks['regex']['pattern']!r}) — write a per-field generator for "
f"this field and call it instead of good_value for it"
)
max_length = checks.get("max_length", {}).get("max_length", 20)
length = random.randint(1, max(1, min(max_length, 20)))
return "".join(random.choices(string.ascii_letters, k=length))
def good_value(field: dict[str, Any], enums_by_name: dict[str, dict]) -> Any:
"""One plausible value for a single field, respecting every check it declares."""
checks = {c["kind"]: c for c in field["checks"]}
if field["pydantic_type"] == "EnumField":
elements = enums_by_name[field["enum_ref"]]["elements"]
return random.choice(elements)
if field["py_type"] == "bool":
return random.choice([True, False])
if field["py_type"] == "date":
return date.today() - timedelta(days=random.randint(0, 3650)) # not_future satisfied by construction
if field["py_type"] == "datetime":
return datetime.now() - timedelta(days=random.randint(0, 3650))
if field["py_type"] in ("int", "float"):
if "range" in checks:
lo, hi = checks["range"]["min"], checks["range"]["max"]
return random.randint(lo, hi) if field["py_type"] == "int" else round(random.uniform(lo, hi), 4)
return random.randint(0, 100) if field["py_type"] == "int" else round(random.uniform(0, 100), 2)
return _sample_text(field["field_name"], checks) # text, uuid
def good_skeleton_row(table_spec: dict[str, Any], enums_by_name: dict[str, dict]) -> dict[str, Any]:
"""
Every field except the primary key and any foreign key. Deliberately
incomplete — fill.py inserts this, then backfills foreign keys once
parent rows actually exist.
"""
return {
f["field_name"]: good_value(f, enums_by_name)
for f in table_spec["fields"]
if not f["primary_key"] and not f["foreign_key"]
}
def good_foreign_key(session: Any, target_table_cls: type, target_col: str) -> Any:
"""A real id already sitting in the parent table."""
existing = session.query(getattr(target_table_cls, target_col)).all()
if not existing:
raise RuntimeError(
f"good_foreign_key: no rows in {target_table_cls.__tablename__} yet — "
f"insert that table's rows before backfilling links to it"
)
return random.choice(existing)[0]
+15 -62
View File
@@ -105,16 +105,6 @@ def _render_single_condition(c: dict[str, Any]) -> str:
return f"(self.{field} is not None and self.{field} {op_symbol} {c['value']!r})"
def _raise(error_type: str, template: str, context_src: str, indent: str = " ") -> str:
"""
One line: raise PydanticCustomError(error_type, template, context).
error_type becomes e.errors()[i]["type"] at runtime — the rule name,
kept as data, not parsed back out of the message text. context_src
is already-built dict-literal source (e.g. "{\'_msg\': _msg, \'left\': self.a}").
"""
return f"{indent}raise PydanticCustomError({error_type!r}, {template!r}, {context_src})"
def _render_order(rule: dict[str, Any], name: str) -> str:
left, right = rule["fields"]
op_symbol = OP_SYMBOLS[rule["op"]]
@@ -123,7 +113,7 @@ def _render_order(rule: dict[str, Any], name: str) -> str:
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}}}"),
f" raise ValueError(f\"{{_msg}}: {{self.{left}}} vs {{self.{right}}}\")",
]
return _wrap_method(name, body)
@@ -135,7 +125,7 @@ def _render_equals(rule: dict[str, Any], name: str) -> str:
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}}}"),
f" raise ValueError(f\"{{_msg}}: {{self.{a}}} vs {{self.{b}}}\")",
]
return _wrap_method(name, body)
@@ -150,10 +140,7 @@ def _render_sum_equals(rule: dict[str, Any], name: str) -> str:
f"if self.{target} is not None and {none_checks}:",
f" _expected = {sum_expr}",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"sum_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected}}\")",
]
return _wrap_method(name, body)
@@ -168,10 +155,7 @@ def _render_ratio_equals(rule: dict[str, Any], name: str) -> str:
f"if self.{target} is not None and self.{num} is not None and self.{den} not in (None, 0):",
f" _expected = self.{num} / ({denom_expr})",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"ratio_equals", "{_msg}: got {got}, expected {expected:.4f}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected:.4f}}\")",
]
return _wrap_method(name, body)
@@ -185,10 +169,7 @@ def _render_date_offset_equals(rule: dict[str, Any], name: str) -> str:
f"if self.{target} is not None and self.{base} is not None and self.{offset} is not None:",
f" _expected = self.{base} + timedelta(days=self.{offset})",
f" if abs((self.{target} - _expected).days) > {tol!r}:",
_raise(
"date_offset_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected}}\")",
]
return _wrap_method(name, body)
@@ -202,10 +183,7 @@ def _render_date_diff_equals(rule: dict[str, Any], name: str) -> str:
f"if self.{target} is not None and self.{start} is not None and self.{end} is not None:",
f" _expected = (self.{end} - self.{start}).days",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"date_diff_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected}}\")",
]
return _wrap_method(name, body)
@@ -234,10 +212,7 @@ def _render_comparison_equals(rule: dict[str, Any], name: str) -> str:
f"if {guard}:",
f" _expected = bool({cond_expr})",
f" if bool(self.{target}) != _expected:",
_raise(
"comparison_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected}}\")",
]
return _wrap_method(name, body)
@@ -260,10 +235,7 @@ def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
body.append(f" _actual = getattr(self.{target}, 'value', self.{target})")
body.append(" if _actual != _expected:")
body.append(
_raise(
"piecewise_lookup", "{_msg}: got {got}, expected {expected} for " + source + "={source_value}",
f"{{'_msg': _msg, 'got': _actual, 'expected': _expected, 'source_value': self.{source}}}",
)
f" raise ValueError(f\"{{_msg}}: got {{_actual}}, expected {{_expected}} for {source}={{self.{source}}}\")"
)
return _wrap_method(name, body)
@@ -272,18 +244,13 @@ def _render_requires(rule: dict[str, Any], name: str) -> str:
if_field, then_field = rule["if_field"], rule["then_field"]
msg = rule.get("message") or rule["display"]
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
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(
_raise(
"requires", "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{then_field}}}",
)
)
body.append(f" raise ValueError({msg!r})")
return _wrap_method(name, body)
@@ -292,16 +259,11 @@ def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
allowed_values = [v.upper() if isinstance(v, str) else v for v in rule.get("then_allowed_values", [])]
msg = rule.get("message") or rule["display"]
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
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(
_raise(
"forbidden_if", "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{tf}, 'value': _val}}",
)
)
body.append(f" raise ValueError({msg!r})")
return _wrap_method(name, body)
@@ -315,12 +277,7 @@ def _render_any_of_implies(rule: dict[str, Any], name: str) -> str:
body.append(f"if self.{target} is not None:")
body.append(" _expected = any(_components)")
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"any_of_implies", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
body.append(f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected}}\")")
return _wrap_method(name, body)
@@ -339,14 +296,10 @@ def _render_conditional_equals(rule: dict[str, Any], name: str) -> str:
body.append(f" if abs(self.{target} - _expected) > {tol!r}:")
else:
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"conditional_equals", "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
body.append(f" raise ValueError(f\"{{_msg}}: got {{self.{target}}}, expected {{_expected}}\")")
return _wrap_method(name, body)
_RENDERERS = {
"order": _render_order,
"equals": _render_equals,
-5
View File
@@ -341,10 +341,6 @@ def parse_single_table(yaml_path: Path, enum_names: set[str]) -> dict[str, Any]:
f"{foreign_key!r}, expected 'table.column'"
)
unique = field_spec.get("unique", False)
if not isinstance(unique, bool):
raise ValueError(f"{yaml_path}: field '{field_name}' 'unique' must be true or false")
fields.append({
"field_name": field_name,
"py_type": PY_TYPES[field_type],
@@ -354,7 +350,6 @@ def parse_single_table(yaml_path: Path, enum_names: set[str]) -> dict[str, Any]:
"sql_type": SQL_TYPES[field_type],
"primary_key": field_spec.get("primary_key", False),
"foreign_key": foreign_key,
"unique": unique,
"checks": checks,
"required": any(c["kind"] == "required" for c in checks),
"rule_display": build_rule_display(checks, pydantic_type, enum_ref),
+1 -2
View File
@@ -8,7 +8,6 @@ one holding the database session (see validator.validate_row).
from ps_core.runtime.foreign_keys import check_foreign_keys
from ps_core.runtime.ingest import ingest
from ps_core.runtime.loader import load_row
from ps_core.runtime.unique import check_unique_fields
from ps_core.runtime.validator import validate_row
__all__ = ["load_row", "validate_row", "ingest", "check_foreign_keys", "check_unique_fields"]
__all__ = ["load_row", "validate_row", "ingest", "check_foreign_keys"]
+1 -4
View File
@@ -53,8 +53,5 @@ def check_foreign_keys(
for row in bad_rows:
row.validated = False
errs = json.loads(row.errors) if row.errors else {}
errs[f["field_name"]] = {
"rule": "foreign_key",
"message": f"no matching row in {target_table_name}.{target_col_name}",
}
errs[f["field_name"]] = f"no matching row in {target_table_name}.{target_col_name}"
row.errors = json.dumps(errs)
-69
View File
@@ -1,69 +0,0 @@
# -*- coding: utf-8 -*-
"""
Uniqueness is never enforced as a database constraint (no UNIQUE column,
for the same reason foreign keys carry no FK constraint — see
foreign_keys.py): a duplicate should not block a row from being saved.
Instead, this runs as a second pass, after every row is already in the
database: it flags every row sharing a duplicate value by setting
`validated = False` and recording the reason in `errors`, the same
columns every other rule already writes to.
Call this once per batch, after your inserts are committed, and commit
again afterward.
This checks single-column uniqueness only (`unique: true` on one field).
It does not implement multi-column ("unique together") uniqueness.
"""
from __future__ import annotations
import json
from typing import Any
import sqlalchemy as sa
def check_unique_fields(
session: Any,
parsed_tables: list[dict[str, Any]],
class_lookup: dict[str, type],
) -> None:
"""
parsed_tables — the list returned by parse_spec.parse_spec (or its
`parsed_tables` element).
class_lookup — {table_name: orm_class}, built by the caller from
whatever module holds the generated schema classes.
Kept explicit, rather than read from globals(), so
this function has no dependency on how those classes
were loaded.
"""
for table_spec in parsed_tables:
table_name = table_spec["table"]["table_name"]
table_cls = class_lookup[table_name]
for f in table_spec["fields"]:
if not f["unique"]:
continue
column = getattr(table_cls, f["field_name"])
duplicate_values = (
session.query(column)
.filter(column.isnot(None))
.group_by(column)
.having(sa.func.count() > 1)
.all()
)
if not duplicate_values:
continue
values = [row[0] for row in duplicate_values]
bad_rows = session.query(table_cls).filter(column.in_(values)).all()
for row in bad_rows:
row.validated = False
errs = json.loads(row.errors) if row.errors else {}
errs[f["field_name"]] = {
"rule": "unique",
"message": f"duplicate value for {f['field_name']}: {getattr(row, f['field_name'])!r}",
}
row.errors = json.dumps(errs)
+2 -7
View File
@@ -19,19 +19,14 @@ from pydantic import BaseModel, ValidationError
def validate_row(raw_data: dict[str, Any], check_cls: type[BaseModel]) -> dict[str, Any]:
"""
Returns {"validated": True, "errors": None} on success, or
{"validated": False, "errors": <json string>} on failure.
Each entry in the JSON is {"rule": <name>, "message": <text>} — the
rule name is `err["type"]`, which every check in constraints.py and
every cross-rule kind sets explicitly via PydanticCustomError, rather
than something parsed back out of the message text.
{"validated": False, "errors": <json string of field -> message>} on failure.
"""
try:
check_cls.model_validate(raw_data)
return {"validated": True, "errors": None}
except ValidationError as e:
field_errors = {
(".".join(str(p) for p in err["loc"]) or "_cross_field"): {"rule": err["type"], "message": err["msg"]}
".".join(str(p) for p in err["loc"]) or "_cross_field": err["msg"]
for err in e.errors()
}
return {"validated": False, "errors": json.dumps(field_errors)}
+5 -5
View File
@@ -2,13 +2,13 @@
**Class name:** `{{ table.class_name }}`
| Field | SQL Type | Required | Unique | Primary Key | Foreign Key | Rule |
|---|---|---|---|---|---|---|
| Field | SQL Type | Required | Primary Key | Foreign Key | Rule |
|---|---|---|---|---|---|
{% for f in fields %}
| {{ f.field_name }} | {{ f.sql_type }} | {{ "Yes" if f.required else "No" }} | {{ "Yes" if f.unique else "No" }} | {{ "Yes" if f.primary_key else "No" }} | {{ f.foreign_key if f.foreign_key else "—" }} | {{ f.rule_display if f.rule_display else "—" }} |
| {{ f.field_name }} | {{ f.sql_type }} | {{ "Yes" if f.required else "No" }} | {{ "Yes" if f.primary_key else "No" }} | {{ f.foreign_key if f.foreign_key else "—" }} | {{ f.rule_display if f.rule_display else "—" }} |
{% endfor %}
| validated | sa.Boolean | Yes | No | No | — | — |
| errors | sa.Text | No | No | No | — | — |
| validated | sa.Boolean | Yes | No | — | — |
| errors | sa.Text | No | No | — | — |
{% if cross_rules %}
**Cross-field rules:**
@@ -4,7 +4,6 @@ from datetime import date, datetime, timedelta
from typing import Annotated, Optional
from pydantic import BaseModel, BeforeValidator, ConfigDict, model_validator
from pydantic_core import PydanticCustomError
from ps_core.constraints import (
apply_strip,
-6
View File
@@ -40,11 +40,6 @@ def spec_bad_fk_dir() -> Path:
return FIXTURES_DIR / "spec_bad_fk"
@pytest.fixture
def spec_devdata_dir() -> Path:
return FIXTURES_DIR / "spec_devdata"
def _plain_field(field_name: str, py_type: str, sql_type: str, **overrides) -> dict:
field = {
"field_name": field_name,
@@ -55,7 +50,6 @@ def _plain_field(field_name: str, py_type: str, sql_type: str, **overrides) -> d
"sql_type": sql_type,
"primary_key": False,
"foreign_key": None,
"unique": False,
"checks": [],
"required": False,
"rule_display": None,
-3
View File
@@ -1,3 +0,0 @@
color:
- red
- green
-10
View File
@@ -1,10 +0,0 @@
table:
name: order
fields:
id:
type: uuid
primary_key: true
widget_id:
type: uuid
required: true
foreign_key: widget.id
-18
View File
@@ -1,18 +0,0 @@
table:
name: widget
fields:
id:
type: uuid
primary_key: true
code:
type: text
required: true
unique: true
quantity:
type: integer
range: true
min: 1
max: 10
color:
type: enum
enum: color
-66
View File
@@ -1,13 +1,10 @@
from datetime import date, timedelta
import pytest
from pydantic import BaseModel, ValidationError
from pydantic_core import PydanticCustomError
from ps_core.constraints import (
apply_strip,
apply_upper,
check_enum_membership,
check_max_length,
check_not_future,
check_range,
@@ -154,66 +151,3 @@ def test_normalize_enum_strips_and_uppercases():
def test_normalize_enum_passes_through_none():
assert normalize_enum(None) is None
# --- check_enum_membership ----------------------------------------------------------------
class _Color(str, __import__("enum").Enum):
RED = "RED"
GREEN = "GREEN"
def test_check_enum_membership_accepts_member():
assert check_enum_membership("RED", _Color) == _Color.RED
def test_check_enum_membership_rejects_non_member():
with pytest.raises(ValueError, match="must be one of"):
check_enum_membership("BLUE", _Color)
# --- every check carries its rule name as a structured type, not just message text -----
#
# Each function raises PydanticCustomError, not a plain ValueError. It IS a
# ValueError (existing `except ValueError` / `pytest.raises(ValueError)`
# still works everywhere), but Pydantic also exposes the rule name at
# e.errors()[i]["type"] — this is what ps_core.runtime.validate_row reads
# to store {"rule": ..., "message": ...} instead of a bare string.
@pytest.mark.parametrize("fn,args,expected_type", [
(check_required, (None,), "required"),
(check_range, (99, 1, 10), "range"),
(check_not_future, (date.today() + timedelta(days=1),), "not_future"),
(check_regex, ("abc", "[A-Z]{3}"), "regex"),
(check_max_length, ("abcdef", 5), "max_length"),
(coerce_bool, ("nonsense",), "bool_coercion"),
])
def test_check_functions_raise_pydantic_custom_error_with_matching_type(fn, args, expected_type):
with pytest.raises(PydanticCustomError) as exc_info:
fn(*args)
assert exc_info.value.type == expected_type
def test_check_enum_membership_raises_pydantic_custom_error_with_matching_type():
with pytest.raises(PydanticCustomError) as exc_info:
check_enum_membership("BLUE", _Color)
assert exc_info.value.type == "enum_membership"
def test_rule_name_survives_through_a_real_pydantic_model():
from typing import Annotated, Optional
from pydantic import BeforeValidator
def _check(v):
return check_range(v, 1, 10, label="age")
class M(BaseModel):
age: Annotated[Optional[int], BeforeValidator(_check)] = None
with pytest.raises(ValidationError) as exc_info:
M(age=99)
err = exc_info.value.errors()[0]
assert err["type"] == "range"
assert err["msg"] == "age must be between 1 and 10, got 99"
-153
View File
@@ -1,153 +0,0 @@
from datetime import date
import pytest
from pydantic import BaseModel, ValidationError, model_validator
from ps_core.devdata.faulty import break_field, faulty_foreign_key, faulty_row_for_cross_rule, faulty_skeleton_row
@pytest.fixture
def enums_by_name():
return {"color": {"name": "color", "class_name": "Color", "elements": ["RED", "GREEN"]}}
def test_break_field_required(make_field):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "required"}])
assert break_field(field) is None
def test_break_field_range(make_field):
field = make_field("n", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 10}])
assert break_field(field) == 11
def test_break_field_max_length(make_field):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "max_length", "max_length": 5}])
assert len(break_field(field)) == 6
def test_break_field_regex(make_field):
field = make_field("code", "str", "sa.Text", checks=[{"kind": "regex", "pattern": "[A-Z]{3}"}])
import re
assert not re.fullmatch("[A-Z]{3}", break_field(field))
def test_break_field_not_future(make_field):
field = make_field("d", "date", "sa.Date", checks=[{"kind": "not_future"}])
assert break_field(field) > date.today()
def test_break_field_enum(make_field):
field = make_field("status", "str", "sa.Text", pydantic_type="EnumField", enum_ref="color")
assert break_field(field) == "NOT_A_REAL_MEMBER"
def test_break_field_bool(make_field):
field = make_field("flag", "bool", "sa.Integer")
assert break_field(field) == "nonsense"
def test_break_field_prioritizes_required_over_other_checks(make_field):
# required check goes first, matching the fixed CHECK_ORDER in parse_spec
field = make_field("n", "int", "sa.Integer", checks=[
{"kind": "required"}, {"kind": "range", "min": 1, "max": 10},
])
assert break_field(field) is None
def test_break_field_raises_when_nothing_to_break(make_field):
field = make_field("name", "str", "sa.Text") # no checks, not enum, not bool
with pytest.raises(ValueError, match="has no rule to break"):
break_field(field)
def test_faulty_skeleton_row_breaks_only_the_named_field(make_field, enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("age", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 10}]),
make_field("name", "str", "sa.Text"),
],
}
row = faulty_skeleton_row(table_spec, enums_by_name, "age")
assert row["age"] == 11
assert isinstance(row["name"], str) # untouched, still a plain generated value
def test_faulty_foreign_key_is_a_uuid_shaped_string():
import uuid
value = faulty_foreign_key()
assert uuid.UUID(value) # parses without raising
# --- faulty_row_for_cross_rule: the oracle path -----------------------------------------
def _make_order_check_cls():
from typing import Optional
class M(BaseModel):
a: Optional[int] = None
b: Optional[int] = None
@model_validator(mode="after")
def _order(self):
if self.a is not None and self.b is not None and self.a > self.b:
raise ValueError("a must not exceed b")
return self
return M
def test_faulty_row_for_cross_rule_finds_a_violation(make_field, enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("a", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
make_field("b", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
],
}
check_cls = _make_order_check_cls()
row = faulty_row_for_cross_rule(table_spec, check_cls, enums_by_name, tries=200)
with pytest.raises(ValidationError):
check_cls(**row)
def test_faulty_row_for_cross_rule_respects_narrowed_candidates(make_field, enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("a", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
make_field("b", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 100}]),
],
}
check_cls = _make_order_check_cls()
cross_rule = {"kind": "order", "fields": ["a", "b"], "op": "le"}
row = faulty_row_for_cross_rule(table_spec, check_cls, enums_by_name, cross_rule=cross_rule, tries=200)
with pytest.raises(ValidationError):
check_cls(**row)
def test_faulty_row_for_cross_rule_raises_when_no_violation_found(make_field, enums_by_name):
# a check_cls with no cross rule at all — the oracle can never find a
# cross-rule error (empty loc), so it must give up loudly, not hang
from typing import Optional
class AlwaysFine(BaseModel):
a: Optional[int] = None
b: Optional[int] = None
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("a", "int", "sa.Integer"),
make_field("b", "int", "sa.Integer"),
],
}
with pytest.raises(RuntimeError, match="no violation found"):
faulty_row_for_cross_rule(table_spec, AlwaysFine, enums_by_name, tries=5)
-134
View File
@@ -1,134 +0,0 @@
import json
import sys
import uuid
import sqlalchemy as sa
from sqlalchemy.orm import Session
from ps_core.devdata.fill import _build_lookups, fill_all
from ps_core.generate_all import generate_all
from ps_core.parse_spec import parse_spec
def _build_and_import(spec_dir, out_dir):
generate_all(spec_dir, out_dir)
pkg_name = out_dir.name
sys.path.insert(0, str(out_dir.parent))
try:
import importlib
schema = importlib.import_module(f"{pkg_name}.schema")
validation = importlib.import_module(f"{pkg_name}.validation")
finally:
sys.path.remove(str(out_dir.parent))
return schema, validation
def _setup(spec_devdata_dir, tmp_path):
parsed_tables, enums_spec, _ = parse_spec(spec_devdata_dir)
enums_by_name = {e["name"]: e for e in enums_spec}
out_dir = tmp_path / f"gen_{uuid.uuid4().hex}"
schema_mod, validation_mod = _build_and_import(spec_devdata_dir, out_dir)
class_lookup, check_lookup = _build_lookups(parsed_tables, schema_mod, validation_mod)
engine = sa.create_engine("sqlite://")
schema_mod.Base.metadata.create_all(engine)
return parsed_tables, enums_by_name, class_lookup, check_lookup, engine
def test_fill_all_basic_run_produces_valid_rows(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
widgets = session.query(class_lookup["widget"]).all()
orders = session.query(class_lookup["order"]).all()
assert len(widgets) == 10
assert len(orders) == 10
assert all(w.validated for w in widgets)
assert all(o.validated for o in orders)
def test_fill_all_orphan_rate_one_flags_every_link(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=1.0, faulty_rate=0.0, repeated_rate=0.0)
orders = session.query(class_lookup["order"]).all()
assert all(not o.validated for o in orders)
assert all(json.loads(o.errors)["widget_id"]["rule"] == "foreign_key" for o in orders)
def test_fill_all_orphan_rate_zero_flags_nothing(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
orders = session.query(class_lookup["order"]).all()
assert all(o.validated for o in orders)
assert all(o.errors is None for o in orders)
def test_fill_all_faulty_rate_one_flags_every_widget(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=1.0, repeated_rate=0.0)
widgets = session.query(class_lookup["widget"]).all()
assert all(not w.validated for w in widgets)
assert all(w.errors is not None for w in widgets)
def test_fill_all_repeated_rate_one_flags_unique_field(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=1.0)
widgets = session.query(class_lookup["widget"]).all()
codes = [w.code for w in widgets]
assert len(set(codes)) < len(codes) # genuine duplicates exist
flagged_unique = [
w for w in widgets
if w.errors and json.loads(w.errors).get("code", {}).get("rule") == "unique"
]
assert flagged_unique # at least the duplicates got caught
def test_fill_all_zero_rates_never_produce_duplicates_by_accident(spec_devdata_dir, tmp_path):
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=10,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
widgets = session.query(class_lookup["widget"]).all()
assert all(w.validated for w in widgets)
assert all(w.errors is None for w in widgets)
def test_fill_all_table_order_does_not_matter(spec_devdata_dir, tmp_path):
# parsed_tables happens to list "order" before "widget" alphabetically —
# order (the FK child) still ends up correctly linked after phase 2
parsed_tables, enums_by_name, class_lookup, check_lookup, engine = _setup(spec_devdata_dir, tmp_path)
assert parsed_tables[0]["table"]["table_name"] == "order" # confirms the ordering this test is about
with Session(engine) as session:
fill_all(session, parsed_tables, enums_by_name, class_lookup, check_lookup, count=5,
orphan_rate=0.0, faulty_rate=0.0, repeated_rate=0.0)
widget_ids = {w.id for w in session.query(class_lookup["widget"]).all()}
orders = session.query(class_lookup["order"]).all()
assert all(o.widget_id in widget_ids for o in orders)
-122
View File
@@ -1,122 +0,0 @@
from datetime import date, datetime
import pytest
from ps_core.devdata.good import good_foreign_key, good_skeleton_row, good_value
@pytest.fixture
def enums_by_name():
return {"color": {"name": "color", "class_name": "Color", "elements": ["RED", "GREEN", "BLUE"]}}
def test_good_value_enum_picks_a_real_member(make_field, enums_by_name):
field = make_field("status", "str", "sa.Text", pydantic_type="EnumField", enum_ref="color")
for _ in range(20):
assert good_value(field, enums_by_name) in enums_by_name["color"]["elements"]
def test_good_value_bool_is_a_real_bool(make_field, enums_by_name):
field = make_field("flag", "bool", "sa.Integer")
assert good_value(field, enums_by_name) in (True, False)
def test_good_value_date_is_never_in_the_future(make_field, enums_by_name):
field = make_field("d", "date", "sa.Date")
for _ in range(20):
assert good_value(field, enums_by_name) <= date.today()
def test_good_value_datetime_is_never_in_the_future(make_field, enums_by_name):
field = make_field("d", "datetime", "sa.DateTime")
for _ in range(20):
assert good_value(field, enums_by_name) <= datetime.now()
def test_good_value_int_respects_range(make_field, enums_by_name):
field = make_field("n", "int", "sa.Integer", checks=[{"kind": "range", "min": 1, "max": 10}])
for _ in range(50):
v = good_value(field, enums_by_name)
assert isinstance(v, int)
assert 1 <= v <= 10
def test_good_value_float_respects_range(make_field, enums_by_name):
field = make_field("n", "float", "sa.Float", checks=[{"kind": "range", "min": 0.1, "max": 1.0}])
for _ in range(50):
v = good_value(field, enums_by_name)
assert 0.1 <= v <= 1.0
def test_good_value_int_with_no_range_still_returns_an_int(make_field, enums_by_name):
field = make_field("n", "int", "sa.Integer")
assert isinstance(good_value(field, enums_by_name), int)
def test_good_value_text_respects_max_length(make_field, enums_by_name):
field = make_field("name", "str", "sa.Text", checks=[{"kind": "max_length", "max_length": 5}])
for _ in range(20):
assert len(good_value(field, enums_by_name)) <= 5
def test_good_value_text_with_regex_raises_with_a_clear_message(make_field, enums_by_name):
field = make_field("code", "str", "sa.Text", checks=[{"kind": "regex", "pattern": "[A-Z]{3}"}])
with pytest.raises(ValueError, match="no generic sampler for a regex pattern"):
good_value(field, enums_by_name)
def test_good_skeleton_row_excludes_primary_key_and_foreign_key(enums_by_name):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
{"field_name": "id", "primary_key": True, "foreign_key": None, "py_type": "str",
"pydantic_type": "str", "checks": []},
{"field_name": "owner_id", "primary_key": False, "foreign_key": "other.id", "py_type": "str",
"pydantic_type": "str", "checks": []},
{"field_name": "name", "primary_key": False, "foreign_key": None, "py_type": "str",
"pydantic_type": "str", "checks": []},
],
}
row = good_skeleton_row(table_spec, enums_by_name)
assert set(row) == {"name"}
def test_good_foreign_key_picks_a_real_existing_id():
import sqlalchemy as sa
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Parent(Base):
__tablename__ = "parent"
id: Mapped[str] = mapped_column(sa.String(36), primary_key=True)
engine = sa.create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([Parent(id="a"), Parent(id="b")])
session.commit()
for _ in range(10):
assert good_foreign_key(session, Parent, "id") in ("a", "b")
def test_good_foreign_key_raises_when_parent_table_is_empty():
import sqlalchemy as sa
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Parent(Base):
__tablename__ = "parent2"
id: Mapped[str] = mapped_column(sa.String(36), primary_key=True)
engine = sa.create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
with pytest.raises(RuntimeError, match="no rows in parent2"):
good_foreign_key(session, Parent, "id")
+4 -16
View File
@@ -9,16 +9,16 @@ def test_generate_markdown_table_contains_expected_rows(spec_ok_dir):
assert "## test_table" in result
assert "**Class name:** `TestTable`" in result
assert "| field2 | sa.Integer | No | No | No | — | range [1, 10] |" in result
assert "| field7 | sa.Text | No | No | No | — | one of test_enum |" in result
assert "| validated | sa.Boolean | Yes | No | No | — | — |" in result
assert "| field2 | sa.Integer | No | No | — | range [1, 10] |" in result
assert "| field7 | sa.Text | No | No | — | one of test_enum |" in result
assert "| validated | sa.Boolean | Yes | No | — | — |" in result
def test_generate_markdown_table_shows_foreign_key(spec_ok_dir):
parsed_tables, _, _ = parse_spec(spec_ok_dir)
foreign_table = next(t for t in parsed_tables if t["table"]["table_name"] == "foreign_table")
result = generate_markdown_table(foreign_table)
assert "| owner_id | sa.String(36) | Yes | No | No | test_table.id | — |" in result
assert "| owner_id | sa.String(36) | Yes | No | test_table.id | — |" in result
def test_generate_markdown_table_lists_cross_rules(spec_ok_dir):
@@ -38,18 +38,6 @@ def test_generate_markdown_table_omits_cross_rules_section_when_none(spec_ok_dir
assert "**Cross-field rules:**" not in result
def test_generate_markdown_table_shows_unique(make_field):
table_spec = {
"table": {"table_name": "t", "class_name": "T"},
"fields": [
make_field("id", "str", "sa.String(36)", primary_key=True),
make_field("email", "str", "sa.Text", unique=True),
],
}
result = generate_markdown_table(table_spec)
assert "| email | sa.Text | No | Yes | No | — | — |" in result
def test_generate_markdown_file_covers_every_table(spec_ok_dir):
parsed_tables, _, cross_rules_spec = parse_spec(spec_ok_dir)
content = generate_markdown_file(parsed_tables, cross_rules_spec)
+4 -9
View File
@@ -122,7 +122,6 @@ def _wrap_in_model(body: str, fields: str) -> dict:
source = (
"from typing import Optional\n"
"from pydantic import BaseModel, model_validator\n"
"from pydantic_core import PydanticCustomError\n"
"from datetime import timedelta\n\n"
"class M(BaseModel):\n"
f"{fields}\n"
@@ -406,20 +405,16 @@ def test_full_validation_file_behaves_end_to_end(spec_ok_dir):
good = TestTableCheck(field1="hello", field2=5, field4=date(2024, 1, 1))
assert good.field1 == "hello"
with pytest.raises(ValidationError) as exc_info:
with pytest.raises(ValidationError):
TestTableCheck(field4=date(2024, 1, 1)) # field1 omitted -> required check fires
assert exc_info.value.errors()[0]["type"] == "required"
with pytest.raises(ValidationError) as exc_info:
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2024, 1, 1), field2=999) # range
assert exc_info.value.errors()[0]["type"] == "range"
with pytest.raises(ValidationError) as exc_info:
with pytest.raises(ValidationError):
TestTableCheck(field1="x", field4=date(2999, 1, 1)) # not_future
assert exc_info.value.errors()[0]["type"] == "not_future"
with pytest.raises(ValidationError, match="field3 is required when field6 is true") as exc_info:
with pytest.raises(ValidationError, match="field3 is required when field6 is true"):
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"
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=0.5)
+2 -106
View File
@@ -8,7 +8,7 @@ import sqlalchemy as sa
from pydantic import BaseModel, ValidationError
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from ps_core.runtime import check_foreign_keys, check_unique_fields, ingest, load_row, validate_row
from ps_core.runtime import check_foreign_keys, ingest, load_row, validate_row
# ---------------------------------------------------------------------------
@@ -72,8 +72,6 @@ def test_validate_row_failure_shape():
assert result["validated"] is False
errors = json.loads(result["errors"])
assert "name" in errors
assert set(errors["name"]) == {"rule", "message"}
assert errors["name"]["rule"] == "missing" # Pydantic's own built-in type for an absent required field
def test_validate_row_never_touches_a_database_object():
@@ -129,8 +127,7 @@ def test_check_foreign_keys_flags_orphan_and_spares_valid_link(engine):
assert good_child.validated is True
assert bad_child.validated is False
bad_errors = json.loads(bad_child.errors)
assert bad_errors["parent_id"]["rule"] == "foreign_key"
assert "parent_id" in json.loads(bad_child.errors)
assert null_child.validated is True # a NULL link is not a broken link, left untouched
assert null_child.errors is None
@@ -157,107 +154,6 @@ def test_check_foreign_keys_merges_with_existing_errors(engine):
assert "parent_id" in errs
# --- check_unique_fields ------------------------------------------------------------
def test_check_unique_fields_flags_every_row_in_a_duplicate_group(engine):
class_lookup = {"parent": _Parent}
parsed_tables = [
{"table": {"table_name": "parent"}, "fields": [
{"field_name": "name", "unique": True},
]},
]
with Session(engine) as session:
a = _Parent(name="dup", validated=True)
b = _Parent(name="dup", validated=True)
c = _Parent(name="unique", validated=True)
session.add_all([a, b, c])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
session.refresh(b)
session.refresh(c)
assert a.validated is False
assert b.validated is False
assert json.loads(a.errors)["name"]["rule"] == "unique"
assert json.loads(b.errors)["name"]["rule"] == "unique"
assert c.validated is True
assert c.errors is None
def test_check_unique_fields_ignores_fields_not_marked_unique(engine):
class_lookup = {"parent": _Parent}
parsed_tables = [
{"table": {"table_name": "parent"}, "fields": [
{"field_name": "name", "unique": False},
]},
]
with Session(engine) as session:
a = _Parent(name="dup", validated=True)
b = _Parent(name="dup", validated=True)
session.add_all([a, b])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
assert a.validated is True # unique not requested for this field — untouched
def test_check_unique_fields_ignores_null_values(engine):
class_lookup = {"child": _Child}
parsed_tables = [
{"table": {"table_name": "child"}, "fields": [
{"field_name": "parent_id", "unique": True},
]},
]
with Session(engine) as session:
a = _Child(parent_id=None, validated=True)
b = _Child(parent_id=None, validated=True) # two NULLs — not duplicates of each other
session.add_all([a, b])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
session.refresh(b)
assert a.validated is True
assert b.validated is True
assert a.errors is None
assert b.errors is None
def test_check_unique_fields_merges_with_existing_errors(engine):
class_lookup = {"parent": _Parent}
parsed_tables = [
{"table": {"table_name": "parent"}, "fields": [
{"field_name": "name", "unique": True},
]},
]
with Session(engine) as session:
a = _Parent(name="dup", validated=True, errors=json.dumps({"other_field": "already broken"}))
b = _Parent(name="dup", validated=True)
session.add_all([a, b])
session.commit()
check_unique_fields(session, parsed_tables, class_lookup)
session.commit()
session.refresh(a)
errs = json.loads(a.errors)
assert errs["other_field"] == "already broken"
assert errs["name"]["rule"] == "unique"
# ---------------------------------------------------------------------------
# full pipeline: parse a real spec -> generate real files -> exec -> ingest
# ---------------------------------------------------------------------------
Generated
+1 -1
View File
@@ -228,7 +228,7 @@ wheels = [
[[package]]
name = "ps-core"
version = "0.2.1"
version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "jinja2" },