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_app_materialize_package.py · 12.5 KB · 303 lines
| 1 | """Structural + permission tests for packages/app-materialize |
| 2 | (plan/vocabulary/61-materialize-spec.md). |
| 3 | |
| 4 | Mirrors tests/test_app_rollup_package.py's package/schema/permission |
| 5 | conventions. The worked end-to-end examples (recurring journal, |
| 6 | depreciation, CreateWork) and mapping-vocabulary unit coverage live in |
| 7 | tests/test_object_materialize.py instead; this file exercises the real |
| 8 | package manifest, real permission policy, and the real installed |
| 9 | materialize_seed.py's HANDLES-regeneration mechanism. |
| 10 | """ |
| 11 | |
| 12 | import json |
| 13 | import re |
| 14 | from pathlib import Path |
| 15 | |
| 16 | import object_handlers |
| 17 | import object_materialize |
| 18 | import object_packages |
| 19 | import object_permissions |
| 20 | import object_records |
| 21 | import object_schemas |
| 22 | from package_pins import assert_includes_in_order |
| 23 | |
| 24 | PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages" |
| 25 | APP_MATERIALIZE_DIR = PACKAGES_ROOT / "app-materialize" |
| 26 | |
| 27 | |
| 28 | def _write_schema(data_dir, collection, fields, storage=None): |
| 29 | payload = {"name": collection, "fields": fields} |
| 30 | if storage: |
| 31 | payload["storage"] = storage |
| 32 | path = data_dir / "schemas" / f"{collection}.json" |
| 33 | path.parent.mkdir(parents=True, exist_ok=True) |
| 34 | path.write_text(json.dumps(payload)) |
| 35 | return path |
| 36 | |
| 37 | |
| 38 | # --- Package manifest / install -------------------------------------------- |
| 39 | |
| 40 | def test_get_package_normalizes_app_materialize_manifest(): |
| 41 | package = object_packages.get_package("app-materialize", root=PACKAGES_ROOT) |
| 42 | |
| 43 | assert package["id"] == "app-materialize" |
| 44 | assert package["name"] == "Materialize" |
| 45 | assert package["seed"] == [] |
| 46 | assert {"path": "permissions/rules.json"} in package["permissions"] |
| 47 | assert {schema["collection"] for schema in package["schemas"]} >= {"materialize_definitions"} |
| 48 | assert {obj["id"] for obj in package["objects"]} >= { |
| 49 | "system_materialize_run", "system_materialize_seed", "site_materialize_run_button", |
| 50 | } |
| 51 | |
| 52 | |
| 53 | def test_dry_run_app_materialize_package_is_safe(tmp_path): |
| 54 | object_root = tmp_path / "objects" |
| 55 | object_root.mkdir() |
| 56 | |
| 57 | plan = object_packages.dry_run_package( |
| 58 | "app-materialize", root=PACKAGES_ROOT, base_dir=tmp_path / "data", object_roots=[object_root], |
| 59 | ) |
| 60 | |
| 61 | assert plan["safe_to_install"] is True |
| 62 | assert plan["warnings"] == [] |
| 63 | assert {schema["collection"] for schema in plan["schemas"]} >= {"materialize_definitions"} |
| 64 | |
| 65 | |
| 66 | def test_install_app_materialize_package_loads_schema_and_objects(tmp_path): |
| 67 | data_dir = tmp_path / "data" |
| 68 | object_root = tmp_path / "objects" |
| 69 | object_root.mkdir() |
| 70 | |
| 71 | object_packages.install_package( |
| 72 | "app-materialize", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root], |
| 73 | ) |
| 74 | |
| 75 | schema = object_schemas.get_schema("materialize_definitions", base_dir=data_dir) |
| 76 | assert schema["name"] == "materialize_definitions" |
| 77 | field_names = [f["name"] for f in schema["fields"]] |
| 78 | assert_includes_in_order(field_names, [ |
| 79 | "id", "name", "source_collection", "source_filter", "trigger", "output_collection", |
| 80 | "child_collection", "child_source_field", "child_link_field", "idempotency_key", |
| 81 | "mapping", "balance_check", "debit_account_id", "credit_account_id", "actor", |
| 82 | "last_run_at", "enabled", "block", |
| 83 | ]) |
| 84 | by_name = {f["name"]: f for f in schema["fields"]} |
| 85 | assert by_name["last_run_at"].get("read_only") is True |
| 86 | assert by_name["enabled"].get("default") == "true" |
| 87 | assert by_name["block"].get("default") == "false" |
| 88 | assert schema["views"]["list_mode"] == "table" |
| 89 | |
| 90 | assert (object_root / "system" / "materialize_run.py").is_file() |
| 91 | assert (object_root / "system" / "materialize_seed.py").is_file() |
| 92 | assert (object_root / "site" / "materialize_run_button.py").is_file() |
| 93 | |
| 94 | |
| 95 | def test_schema_json_file_is_valid_and_versioned(): |
| 96 | payload = json.loads((APP_MATERIALIZE_DIR / "schemas" / "materialize_definitions.json").read_text()) |
| 97 | assert payload["name"] == "materialize_definitions" |
| 98 | assert payload["version"] >= 1 |
| 99 | assert payload["views"]["list_mode"] == "table" |
| 100 | |
| 101 | |
| 102 | def test_no_disallowed_org_names_leak_into_the_package(): |
| 103 | """Public repo hygiene: no internal org/codename references anywhere |
| 104 | in this package's source (same guard as tests/test_app_rollup_package.py). |
| 105 | """ |
| 106 | banned = re.compile( |
| 107 | "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]), |
| 108 | re.IGNORECASE, |
| 109 | ) |
| 110 | for path in APP_MATERIALIZE_DIR.rglob("*"): |
| 111 | if "__pycache__" in path.parts: |
| 112 | continue # compiled bytes can match a name by chance |
| 113 | if path.is_dir(): |
| 114 | continue |
| 115 | text = path.read_text(encoding="utf-8", errors="ignore") |
| 116 | assert not banned.search(text), f"disallowed reference found in {path}" |
| 117 | |
| 118 | |
| 119 | def test_materialize_seed_object_source_declares_no_handles(): |
| 120 | """HANDLES ships empty and stays empty: v1 does NOT rewrite the installed |
| 121 | object at runtime to track the definition set (no self-modifying source |
| 122 | under the poll loop). Event-mode runs via the manual path instead; the |
| 123 | shipped file never hand-lists collections. |
| 124 | """ |
| 125 | text = (APP_MATERIALIZE_DIR / "objects" / "system" / "materialize_seed.py").read_text() |
| 126 | assert object_handlers.extract_handles(text) == [] |
| 127 | |
| 128 | |
| 129 | # --- Permissions: materialize_definitions is admin-owned, full stop ------- |
| 130 | |
| 131 | def _app_materialize_policy(extra_rules=()): |
| 132 | payload = json.loads((APP_MATERIALIZE_DIR / "permissions" / "rules.json").read_text()) |
| 133 | rules = list(payload["rules"]) + list(extra_rules) |
| 134 | return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": rules}) |
| 135 | |
| 136 | |
| 137 | def test_materialize_definitions_denied_to_registered_non_admin_for_every_action(): |
| 138 | policy = _app_materialize_policy() |
| 139 | subject = object_permissions.PermissionSubject(user_id="7") |
| 140 | record = {"id": "m1", "name": "Recurring journals", "source_collection": "fin_recurring"} |
| 141 | |
| 142 | for action in ( |
| 143 | object_permissions.CREATE, object_permissions.READ, |
| 144 | object_permissions.UPDATE, object_permissions.DELETE, |
| 145 | ): |
| 146 | decision = object_permissions.check_permission( |
| 147 | subject, action, policy=policy, collection="materialize_definitions", record=record, |
| 148 | ) |
| 149 | assert decision.allowed is False, action |
| 150 | |
| 151 | |
| 152 | def test_materialize_definitions_unreachable_by_anonymous_reads(): |
| 153 | policy = _app_materialize_policy() |
| 154 | decision = object_permissions.check_permission( |
| 155 | None, object_permissions.READ, policy=policy, collection="materialize_definitions", |
| 156 | ) |
| 157 | assert decision.allowed is False |
| 158 | |
| 159 | |
| 160 | def test_materialize_definitions_allowed_for_admin_role(): |
| 161 | policy = _app_materialize_policy() |
| 162 | admin = object_permissions.PermissionSubject(user_id="1", roles=("admin",)) |
| 163 | |
| 164 | for action in ( |
| 165 | object_permissions.CREATE, object_permissions.READ, |
| 166 | object_permissions.UPDATE, object_permissions.DELETE, |
| 167 | ): |
| 168 | decision = object_permissions.check_permission( |
| 169 | admin, action, policy=policy, collection="materialize_definitions", |
| 170 | ) |
| 171 | assert decision.allowed is True, action |
| 172 | |
| 173 | |
| 174 | def test_materialize_run_execute_denied_to_non_admin_and_allowed_for_admin(): |
| 175 | policy = _app_materialize_policy() |
| 176 | non_admin = object_permissions.PermissionSubject(user_id="7") |
| 177 | admin = object_permissions.PermissionSubject(user_id="1", roles=("admin",)) |
| 178 | |
| 179 | denied = object_permissions.check_permission( |
| 180 | non_admin, object_permissions.EXECUTE, policy=policy, object_id="system_materialize_run", |
| 181 | ) |
| 182 | allowed = object_permissions.check_permission( |
| 183 | admin, object_permissions.EXECUTE, policy=policy, object_id="system_materialize_run", |
| 184 | ) |
| 185 | assert denied.allowed is False |
| 186 | assert allowed.allowed is True |
| 187 | |
| 188 | |
| 189 | # --- Event-mode fixtures + CreateWork worked example --------------------- |
| 190 | # (No HANDLES-rewrite tests: v1 deliberately has no runtime source rewriter; |
| 191 | # event-mode runs through the manual path, exercised by the worked example |
| 192 | # below.) |
| 193 | |
| 194 | def _install_with_tasks_fixture(data_dir, object_root): |
| 195 | object_packages.install_package( |
| 196 | "app-materialize", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root], |
| 197 | ) |
| 198 | _write_schema(data_dir, "tasks", [ |
| 199 | {"name": "id"}, {"name": "title", "type": "text"}, |
| 200 | {"name": "template_id", "type": "text", "relation": {"collection": "templates", "display_field": "name"}}, |
| 201 | ]) |
| 202 | |
| 203 | |
| 204 | def _event_definition(**overrides): |
| 205 | base = { |
| 206 | "id": "matgen_task_seed", |
| 207 | "name": "CreateWork seed", |
| 208 | "source_collection": "tasks", |
| 209 | "trigger": json.dumps({"mode": "event", "on": "record.created"}), |
| 210 | "output_collection": "tasks", |
| 211 | "idempotency_key": "{definition_id}_{source_id}", |
| 212 | "mapping": json.dumps({}), |
| 213 | "enabled": "true", |
| 214 | "block": "false", |
| 215 | } |
| 216 | base.update(overrides) |
| 217 | return base |
| 218 | |
| 219 | |
| 220 | def test_event_mode_definition_runs_through_the_manual_path(tmp_path): |
| 221 | """Event-mode is valid but v1 runs it manually (no auto HANDLES): a |
| 222 | definition with trigger.mode == "event" generates correctly when driven |
| 223 | through generate_one_event, the same call the (inert) seed handler would |
| 224 | make -- proving degrade-to-manual works without any source rewriting.""" |
| 225 | data_dir = tmp_path / "data" |
| 226 | object_root = tmp_path / "objects" |
| 227 | object_root.mkdir() |
| 228 | _install_with_tasks_fixture(data_dir, object_root) |
| 229 | definition = _event_definition() |
| 230 | object_records.create_collection_record( |
| 231 | "materialize_definitions", definition, base_dir=data_dir, roots=[object_root], actor="admin", |
| 232 | ) |
| 233 | # The seed object ships inert -- nothing rewrote it. |
| 234 | installed_text = (object_root / "system" / "materialize_seed.py").read_text() |
| 235 | assert object_handlers.extract_handles(installed_text) == [] |
| 236 | |
| 237 | # compute_event_handles still reports what a future deliberate sync WOULD |
| 238 | # wire, but it is pure computation with no side effect on the object. |
| 239 | assert object_materialize.compute_event_handles(base_dir=data_dir, roots=[object_root]) == [ |
| 240 | "tasks.record.created" |
| 241 | ] |
| 242 | assert (object_root / "system" / "materialize_seed.py").read_text() == installed_text |
| 243 | |
| 244 | |
| 245 | # --- Worked example: CreateWork end-to-end through the real package ------- |
| 246 | |
| 247 | def test_worked_example_creatework_seed_via_materialize_run(tmp_path): |
| 248 | data_dir = tmp_path / "data" |
| 249 | object_root = tmp_path / "objects" |
| 250 | object_root.mkdir() |
| 251 | _install_with_tasks_fixture(data_dir, object_root) |
| 252 | _write_schema(data_dir, "templates", [ |
| 253 | {"name": "id"}, {"name": "name", "type": "text"}, {"name": "default_values", "type": "textarea"}, |
| 254 | ]) |
| 255 | object_records.create_collection_record( |
| 256 | "templates", |
| 257 | {"id": "tmpl1", "name": "Onboarding", "default_values": json.dumps({"title": "Seeded title"})}, |
| 258 | base_dir=data_dir, roots=[object_root], |
| 259 | ) |
| 260 | object_records.create_collection_record( |
| 261 | "tasks", {"id": "task1", "title": "", "template_id": "tmpl1"}, base_dir=data_dir, roots=[object_root], |
| 262 | ) |
| 263 | object_records.create_collection_record( |
| 264 | "materialize_definitions", _event_definition(), base_dir=data_dir, roots=[object_root], actor="admin", |
| 265 | ) |
| 266 | |
| 267 | result = object_materialize.generate_definition( |
| 268 | object_records.get_collection_record("materialize_definitions", "matgen_task_seed", base_dir=data_dir, roots=[object_root]), |
| 269 | base_dir=data_dir, roots=[object_root], |
| 270 | ) |
| 271 | assert result["generated"] == 1 |
| 272 | |
| 273 | updated = object_records.get_collection_record("tasks", "task1", base_dir=data_dir, roots=[object_root]) |
| 274 | assert updated["title"] == "Seeded title" |
| 275 | |
| 276 | |
| 277 | def _load_materialize_seed(): |
| 278 | import importlib.util |
| 279 | |
| 280 | path = APP_MATERIALIZE_DIR / "objects" / "system" / "materialize_seed.py" |
| 281 | spec = importlib.util.spec_from_file_location("materialize_seed_under_test", path) |
| 282 | module = importlib.util.module_from_spec(spec) |
| 283 | spec.loader.exec_module(module) |
| 284 | return module |
| 285 | |
| 286 | |
| 287 | def test_materialize_seed_event_recognises_the_raw_create_verb(tmp_path, monkeypatch): |
| 288 | """object_server's dispatcher passes the RAW change verb in |
| 289 | request["action"] ("create"/"update"/"delete"); only request["event"] uses |
| 290 | the past-participle form. The handler once compared against "created", so |
| 291 | a real create was rejected at the verb gate and could never dispatch. |
| 292 | A create that passes the gate goes on to look for event-mode definitions |
| 293 | (none exist here), so it stops with a different skip reason. |
| 294 | """ |
| 295 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data")) |
| 296 | seed = _load_materialize_seed() |
| 297 | base = {"event": "notes.record.created", "collection": "notes", "record_id": "n1"} |
| 298 | |
| 299 | create = seed.EVENT({**base, "action": "create"}) |
| 300 | assert create["skipped"] == "no enabled event-mode definition for notes" |
| 301 | |
| 302 | for verb in ("update", "delete", ""): |
| 303 | assert seed.EVENT({**base, "action": verb})["skipped"] == "not a record.created event" |