Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_package_schema_rules.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_package_schema_rules.py · 3.7 KB · 90 lines
1"""The rules every shipped schema declares for the write lock.
2
3A `unique` or `locked_when` message is what a refused writer reads, and
4/flow prints it. fin_journals' was a developer note ("v8: ... checked
5inside the write lock -- object_finance.compose_posted_journal ..."),
6which tells the person refused nothing they can act on. The history
7belongs in the schema's description.
8"""
9
10import json
11import pathlib
12import re
13
14import pytest
15
16PACKAGES = pathlib.Path(__file__).resolve().parents[1] / "packages"
17
18
19def _rule_messages():
20 for path in sorted(PACKAGES.glob("*/schemas/*.json")):
21 schema = json.loads(path.read_text())
22 for kind in ("unique", "locked_when"):
23 rules = schema.get(kind) or []
24 for rule in rules if isinstance(rules, list) else [rules]:
25 yield f"{path.parent.parent.name}/{path.stem}:{kind}", rule.get("message", "")
26
27
28# What a developer note looks like: a version tag, a module or function
29# name, a field name in parentheses, the lock's own vocabulary.
30DEVELOPER_NOTE = re.compile(
31 r"^v\d+\b|\bobject_\w+|\w+\.\w+\(|\w+_\w+\.\w+|write lock|provenance marker|"
32 r"scan-then-write|generated_from")
33
34
35@pytest.mark.parametrize("where,message", list(_rule_messages()))
36def test_every_rule_message_is_a_sentence_for_the_person_refused(where, message):
37 assert message.strip(), f"{where} has no message"
38 assert not DEVELOPER_NOTE.search(message), f"{where}: {message}"
39
40
41# --- seeds ------------------------------------------------------------------------
42#
43# A package's first install writes its seed file into the fresh collection
44# byte for byte: no validation, no unique check (object_packages, the
45# seed_writes loop). That is the trusted package-author path, so the place
46# to catch a broken seed is here, in CI, not on somebody's first install.
47# Every row of every shipped seed is created, in file order, into a fresh
48# collection under its schema the way an ordinary write would be: field
49# validation, duplicate ids and `unique` keys (within the seed) all refuse.
50# `locked_when` binds edits and deletes of an existing row, never a create,
51# so a seed cannot break it; a row seeded already in a locked state is
52# simply frozen from the start, which is the rule doing its job.
53
54def _schema_for(seed):
55 own = seed.parent.parent / "schemas" / f"{seed.stem}.json"
56 if own.exists():
57 return own
58 found = sorted(PACKAGES.glob(f"*/schemas/{seed.stem}.json"))
59 return found[0] if found else None
60
61
62SEEDS = [seed for seed in sorted(PACKAGES.glob("*/seed/*.tsv")) if _schema_for(seed)]
63
64
65def test_the_seed_check_covers_the_shipped_seeds():
66 # site_routes ships no schema anywhere: nothing to validate against.
67 assert len(SEEDS) > 50
68 with_unique = {seed.stem for seed in SEEDS
69 if json.loads(_schema_for(seed).read_text()).get("unique")}
70 assert {"wallets", "wallet_entries", "usage_events"} <= with_unique, with_unique
71
72
73@pytest.mark.parametrize("seed", SEEDS, ids=lambda s: f"{s.parent.parent.name}/{s.stem}")
74def test_every_shipped_seed_row_is_one_the_collection_accepts(seed, tmp_path):
75 import csv
76 import io
77
78 import object_records
79
80 (tmp_path / "schemas").mkdir()
81 (tmp_path / "schemas" / f"{seed.stem}.json").write_text(_schema_for(seed).read_text())
82 refused = []
83 for row in csv.DictReader(io.StringIO(seed.read_text()), delimiter="\t"):
84 try:
85 object_records.create_collection_record(
86 seed.stem, {k: v for k, v in row.items() if k is not None and v is not None},
87 base_dir=tmp_path, actor="test", preserve_read_only=True)
88 except Exception as exc: # noqa: BLE001 -- every refusal is reported
89 refused.append(f"{row.get('id')}: {type(exc).__name__}: {exc}")
90 assert refused == [], refused