askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_object_governance.py · 11.6 KB · 244 lines
| 1 | """Governance introspection: the placement table live, and the workflow |
| 2 | diagram compiled from declarations. |
| 3 | |
| 4 | The claim under test is the one that separates this from every |
| 5 | hand-maintained workflow picture: because each kind of rule has exactly |
| 6 | one declared home, the diagram is COMPILED from the same declarations the |
| 7 | server enforces -- install a handler or add a transition and the next |
| 8 | render shows it, with no drawing to forget to update. |
| 9 | """ |
| 10 | |
| 11 | import json |
| 12 | import pathlib |
| 13 | |
| 14 | from conftest import stage_collection |
| 15 | |
| 16 | import object_governance |
| 17 | |
| 18 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 19 | PACKAGES = REPO_ROOT / "packages" |
| 20 | ROOTS = [PACKAGES / "app-payments" / "objects", PACKAGES / "app-invoices" / "objects"] |
| 21 | |
| 22 | |
| 23 | def setup_env(tmp_path, monkeypatch): |
| 24 | data_dir = tmp_path / "data" |
| 25 | for pkg, name in (("app-invoices", "invoices"), ("app-payments", "payments"), |
| 26 | ("app-tasks", "tasks")): |
| 27 | stage_collection(data_dir, pkg, name) |
| 28 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 29 | return data_dir |
| 30 | |
| 31 | |
| 32 | def test_governs_answers_the_seven_layers_in_one_call(tmp_path, monkeypatch): |
| 33 | data_dir = setup_env(tmp_path, monkeypatch) |
| 34 | info = object_governance.governs("payments", base_dir=data_dir, roots=ROOTS) |
| 35 | |
| 36 | # gate: the schema names its hook, and the report says it fails closed |
| 37 | assert info["gates"][0]["object_id"] == "hook_payments" |
| 38 | assert "fails closed" in info["gates"][0]["note"] |
| 39 | # reactions: parsed from HANDLES source, never by importing the objects |
| 40 | reacting = {r["object_id"] for r in info["reactions"]} |
| 41 | assert {"system_books", "system_invoice_status"} <= reacting |
| 42 | # declarations: enums/relations/transitions from the schema itself |
| 43 | assert "invoice_id" in info["declarations"]["relations"] |
| 44 | assert info["declarations"]["relations"]["invoice_id"] == "invoices" |
| 45 | |
| 46 | |
| 47 | def test_governs_reads_transitions_with_their_guards(tmp_path, monkeypatch): |
| 48 | data_dir = setup_env(tmp_path, monkeypatch) |
| 49 | info = object_governance.governs("invoices", base_dir=data_dir, roots=ROOTS) |
| 50 | moves = info["declarations"]["transitions"]["status"] |
| 51 | targets = {t["to"] for t in moves["draft"]} |
| 52 | assert targets == {"sent", "void"} |
| 53 | # guards travel with the edge -- who may make the move is part of the map. |
| 54 | # (invoices dropped its owner guards in app-invoices 0.15.0: who may move |
| 55 | # an invoice is a staff field permission now, so tasks carries the example.) |
| 56 | tasks = object_governance.governs("tasks", base_dir=data_dir, roots=ROOTS) |
| 57 | draft = tasks["declarations"]["transitions"]["status"]["draft"] |
| 58 | assert draft[0]["when"] == {"owner_id": "$user_id"} |
| 59 | |
| 60 | |
| 61 | def test_handles_parser_accepts_the_real_source_shape(tmp_path, monkeypatch): |
| 62 | """books.py's HANDLES has a trailing comma -- legal Python, illegal |
| 63 | JSON, and exactly the kind of gap that silently empties an index.""" |
| 64 | setup_env(tmp_path, monkeypatch) |
| 65 | handlers = object_governance._handler_index(ROOTS) |
| 66 | by_id = {h["object_id"]: h for h in handlers} |
| 67 | assert "system_books" in by_id |
| 68 | events = {(e["collection"], e["action"]) for e in by_id["system_books"]["events"]} |
| 69 | assert ("invoices", "created") in events |
| 70 | assert ("payments", "updated") in events |
| 71 | |
| 72 | |
| 73 | def test_mermaid_compiles_states_guards_gates_and_reactions(tmp_path, monkeypatch): |
| 74 | data_dir = setup_env(tmp_path, monkeypatch) |
| 75 | source = object_governance.workflow_mermaid("payments", base_dir=data_dir, roots=ROOTS) |
| 76 | assert source.startswith("flowchart LR") |
| 77 | assert 'gate: hook_payments' in source |
| 78 | assert '-->|"on created"| system_books' in source |
| 79 | # a reaction node is declared once even when it fires on several actions |
| 80 | assert source.count('system_books[/"system_books"/]') == 1 |
| 81 | |
| 82 | invoices = object_governance.workflow_mermaid("invoices", base_dir=data_dir, roots=ROOTS) |
| 83 | assert "invoices_draft --> invoices_sent" in invoices # an unguarded edge |
| 84 | assert "system_invoice_portal_link" in invoices |
| 85 | tasks = object_governance.workflow_mermaid("tasks", base_dir=data_dir, roots=ROOTS) |
| 86 | assert 'tasks_draft -->|"owner_id=$user_id"| tasks_open' in tasks |
| 87 | |
| 88 | |
| 89 | def test_missing_layers_report_as_empty_not_as_errors(tmp_path, monkeypatch): |
| 90 | """A collection with no hooks simply has no gate rows -- that IS the |
| 91 | honest report, and a governance tool that raised on a plain collection |
| 92 | would never get used.""" |
| 93 | data_dir = tmp_path / "data" |
| 94 | stage_collection(data_dir, "app-links", "links") |
| 95 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 96 | info = object_governance.governs("links", base_dir=data_dir, roots=ROOTS) |
| 97 | assert info["gates"] == [] |
| 98 | assert info["reactions"] == [] |
| 99 | assert info["declarations"]["transitions"] == {} |
| 100 | source = object_governance.workflow_mermaid("links", base_dir=data_dir, roots=ROOTS) |
| 101 | assert "links" in source # renders a plain node, not a traceback |
| 102 | |
| 103 | |
| 104 | def test_unknown_collection_is_a_plain_empty_report(tmp_path, monkeypatch): |
| 105 | data_dir = tmp_path / "data" |
| 106 | data_dir.mkdir() |
| 107 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 108 | info = object_governance.governs("nothing_here", base_dir=data_dir, roots=ROOTS) |
| 109 | assert info["collection"] == "nothing_here" |
| 110 | assert info["gates"] == [] and info["views"] == [] |
| 111 | assert info["declarations"]["unique"] == [] |
| 112 | assert info["declarations"]["locked_when"] == [] |
| 113 | |
| 114 | |
| 115 | def test_governs_reports_the_rules_enforced_inside_the_write_lock(tmp_path, monkeypatch): |
| 116 | """`unique` and `locked_when` refuse writes for every writer. A |
| 117 | placement table that left them out would say nothing stops a duplicate |
| 118 | or an edit to settled data on a collection where something does.""" |
| 119 | data_dir = tmp_path / "data" |
| 120 | (data_dir / "schemas").mkdir(parents=True) |
| 121 | (data_dir / "schemas" / "entries.json").write_text(json.dumps({ |
| 122 | "name": "entries", |
| 123 | "fields": [{"name": "id"}, {"name": "status"}, {"name": "ref"}, {"name": "owner_id"}], |
| 124 | "unique": [{"fields": ["ref"], "scope": ["owner_id"]}], |
| 125 | "locked_when": [{"when": {"status": "approved"}, "except": ["status"]}], |
| 126 | "hooks": {"before_write": "hook_entries"}, |
| 127 | })) |
| 128 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 129 | |
| 130 | info = object_governance.governs("entries", base_dir=data_dir, roots=ROOTS) |
| 131 | |
| 132 | assert info["declarations"]["unique"] == [ |
| 133 | {"fields": ["ref"], "scope": ["owner_id"], "ignore_case": False}] |
| 134 | assert info["declarations"]["locked_when"] == [ |
| 135 | {"when": {"status": ["approved"]}, "except": ["status"], "allow_delete": False}] |
| 136 | # ...and the hook's note no longer says it only sees creates and updates. |
| 137 | assert "delete" in info["gates"][0]["note"] |
| 138 | |
| 139 | |
| 140 | # --- the /flow page ----------------------------------------------------------- |
| 141 | |
| 142 | def _flow(payload): |
| 143 | import object_execution |
| 144 | import python_object_runtime |
| 145 | runtime = python_object_runtime.PythonObjectRuntime() |
| 146 | return object_execution.execute_object( |
| 147 | runtime, |
| 148 | object_execution.ObjectExecutionRequest("site_flow", method="GET", payload=payload), |
| 149 | roots=[PACKAGES / "app-views" / "objects"]).result |
| 150 | |
| 151 | |
| 152 | def test_flow_page_renders_the_compiled_picture(tmp_path, monkeypatch): |
| 153 | data_dir = setup_env(tmp_path, monkeypatch) |
| 154 | # The page compiles reactions from the SERVER's object roots (in |
| 155 | # production: the installed objects dir). Point the env at the package |
| 156 | # that carries system_books so the compiled picture has its reactions. |
| 157 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(PACKAGES / "app-payments" / "objects")) |
| 158 | anon = _flow({}) |
| 159 | assert "Sign in" in anon["body"] # the map is gated like the data |
| 160 | |
| 161 | index = _flow({"_identity": {"user_id": "dan"}}) |
| 162 | assert "/flow/invoices" in index["body"] |
| 163 | |
| 164 | detail = _flow({"_identity": {"user_id": "dan"}, "collection": "invoices"}) |
| 165 | body = detail["body"] |
| 166 | assert "<svg" in body # the drawn state machine |
| 167 | assert "system_books" in body # reactions listed |
| 168 | assert "flowchart LR" in body # mermaid source for reuse |
| 169 | guarded = _flow({"_identity": {"user_id": "dan"}, "collection": "tasks"})["body"] |
| 170 | assert "owner_id = $user_id" in guarded # guards are readable, not hidden |
| 171 | |
| 172 | |
| 173 | def test_flow_page_shows_the_rules_enforced_inside_the_write_lock(tmp_path, monkeypatch): |
| 174 | """governs() reports `unique` and `locked_when`, and the page dropped |
| 175 | them: a collection whose posted rows nobody can touch read on /flow as |
| 176 | if only its hook stood in the way. Each rule is shown with its fields, |
| 177 | its scope and condition, and the message a refused writer gets.""" |
| 178 | data_dir = tmp_path / "data" |
| 179 | (data_dir / "schemas").mkdir(parents=True) |
| 180 | (data_dir / "schemas" / "entries.json").write_text(json.dumps({ |
| 181 | "name": "entries", |
| 182 | "fields": [{"name": "id"}, {"name": "status"}, {"name": "ref"}, |
| 183 | {"name": "notes"}, {"name": "owner_id"}], |
| 184 | "unique": [{"fields": ["ref"], "scope": ["owner_id"], "ignore_case": True, |
| 185 | "message": "That <ref> is taken."}], |
| 186 | "locked_when": [{"when": {"status": ["approved", "billed"]}, |
| 187 | "except": ["status", "notes"], |
| 188 | "message": "Approved entries are final."}], |
| 189 | })) |
| 190 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 191 | |
| 192 | body = _flow({"_identity": {"user_id": "dan"}, "collection": "entries"})["body"] |
| 193 | |
| 194 | assert "Unique" in body and "Frozen" in body |
| 195 | assert "<code>ref</code>" in body and "per <code>owner_id</code>" in body |
| 196 | assert "ignoring case" in body |
| 197 | assert "That <ref> is taken." in body # escaped, like everything else |
| 198 | assert "<code>status</code> is approved or billed" in body |
| 199 | assert "may still change: <code>status</code>, <code>notes</code>" in body |
| 200 | assert "cannot be deleted" in body |
| 201 | assert "Approved entries are final." in body |
| 202 | |
| 203 | |
| 204 | def test_flow_page_says_when_nothing_is_enforced_in_the_lock(tmp_path, monkeypatch): |
| 205 | data_dir = setup_env(tmp_path, monkeypatch) |
| 206 | body = _flow({"_identity": {"user_id": "dan"}, "collection": "payments"})["body"] |
| 207 | assert "Inside the write lock" in body |
| 208 | assert "nothing frozen" in body |
| 209 | |
| 210 | |
| 211 | def test_flow_page_rejects_an_invalid_collection_name(tmp_path, monkeypatch): |
| 212 | setup_env(tmp_path, monkeypatch) |
| 213 | detail = _flow({"_identity": {"user_id": "dan"}, |
| 214 | "collection": "../../../etc/passwd"}) |
| 215 | # An unusable name falls back to the index rather than echoing anything. |
| 216 | assert "How things work" in detail["body"] |
| 217 | |
| 218 | |
| 219 | # --- the /urls page ------------------------------------------------------------- |
| 220 | |
| 221 | def test_urls_page_compiles_the_site_map(tmp_path, monkeypatch): |
| 222 | """A hand-written sitemap is wrong within a week; a compiled one cannot |
| 223 | be. Convention pages, routed patterns, view routes and the core API all |
| 224 | appear, and the anonymous gate holds -- the complete map of a server's |
| 225 | surface is reconnaissance data.""" |
| 226 | data_dir = setup_env(tmp_path, monkeypatch) |
| 227 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", |
| 228 | str(PACKAGES / "app-views" / "objects")) |
| 229 | import object_execution |
| 230 | import python_object_runtime |
| 231 | runtime = python_object_runtime.PythonObjectRuntime() |
| 232 | |
| 233 | def page(payload): |
| 234 | return object_execution.execute_object( |
| 235 | runtime, |
| 236 | object_execution.ObjectExecutionRequest("site_urls", method="GET", |
| 237 | payload=payload), |
| 238 | roots=[PACKAGES / "app-views" / "objects"]).result |
| 239 | |
| 240 | assert "Sign in" in page({})["body"] |
| 241 | body = page({"_identity": {"user_id": "dan"}})["body"] |
| 242 | assert "/webhooks/{name}" in body # core surface listed |
| 243 | assert "site_flow" in body # convention pages discovered |
| 244 | assert "convention" in body and "core" in body |