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_app_templates_package.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, 19 minutes ago History
test_app_templates_package.py · 13.1 KB · 313 lines
1"""Structural tests for packages/app-templates (templates).
2
3Mirrors the package/schema/permission testing conventions used for
4packages/app-contacts and packages/app-invoices in tests/test_app_contacts_
5package.py and tests/test_app_invoices_package.py. There was no dedicated
6test file for app-templates before this one; it fills that gap while also
7covering the v1 -> v2 structured-data field additions (schema/ui_schema/
8instructions/ai_prompt/ai_assistance/default_values/example_data) and the
9new /templates page, reconciled against a private predecessor-system
10audit, not part of this repo.
11"""
12
13import json
14import re
15from pathlib import Path
16
17import object_packages
18import object_permissions
19import object_records
20import object_schemas
21from package_pins import assert_includes_in_order
22
23PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
24APP_TEMPLATES_DIR = PACKAGES_ROOT / "app-templates"
25
26_SCHEMA_NAMES = ("templates",)
27
28
29def _schema(name):
30 return json.loads((APP_TEMPLATES_DIR / "schemas" / f"{name}.json").read_text())
31
32
33def test_get_package_normalizes_app_templates_manifest():
34 package = object_packages.get_package("app-templates", root=PACKAGES_ROOT)
35
36 assert package["id"] == "app-templates"
37 assert package["name"] == "Templates"
38 assert {schema["collection"] for schema in package["schemas"]} >= set(_SCHEMA_NAMES)
39 # 0.3.0 deletes the bespoke /templates list page object: it held no
40 # business logic and is now a seeded VIEW record over the generic
41 # `list` block.
42 assert package["objects"] == []
43 assert {"path": "permissions/rules.json"} in package["permissions"]
44 assert {entry["collection"] for entry in package["seed"]} >= set(_SCHEMA_NAMES) | {
45 "views", "site_routes",
46 }
47 # No migration mechanism is exercised here: additive field-adds don't
48 # need one (see test_additive_field_adds_need_no_migration_entry below).
49 assert package["migrations"] == []
50
51
52def test_dry_run_app_templates_package_is_safe(tmp_path):
53 object_root = tmp_path / "objects"
54 object_root.mkdir()
55
56 plan = object_packages.dry_run_package(
57 "app-templates",
58 root=PACKAGES_ROOT,
59 base_dir=tmp_path / "data",
60 object_roots=[object_root],
61 )
62
63 assert plan["safe_to_install"] is True
64 assert plan["warnings"] == []
65 assert {schema["collection"] for schema in plan["schemas"]} >= set(_SCHEMA_NAMES)
66
67
68def test_install_app_templates_package_loads_schema(tmp_path):
69 data_dir = tmp_path / "data"
70 object_root = tmp_path / "objects"
71 object_root.mkdir()
72
73 object_packages.install_package(
74 "app-templates", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root],
75 )
76
77 schema = object_schemas.get_schema("templates", base_dir=data_dir)
78 assert schema["name"] == "templates"
79 # templates.py was deleted (0.3.0): the /templates list page is now a
80 # seeded VIEW record over the generic `list` block.
81 assert not (object_root / "site" / "templates.py").exists()
82
83
84def test_schema_json_file_is_valid():
85 payload = _schema("templates")
86 assert payload["name"] == "templates"
87 assert isinstance(payload["version"], int)
88
89
90def test_templates_schema_is_now_version_2_additive_only():
91 """templates.json went 1 -> 2 adding schema/ui_schema/instructions/
92 ai_prompt/ai_assistance/default_values/example_data. Every field that
93 existed at v1 is still present, unchanged in name/type -- this schema
94 change is purely additive (live records with no value for the new
95 fields just read those fields back as empty, same as any other
96 optional field on a schemaless TSV collection). v2 -> v3 adds created_at
97 (baseline record metadata), also additive. v3 -> v4 adds handler and
98 run_cost_cents (app-runner: which engine executes a template and what
99 one run costs), also additive -- a template with neither is a document
100 rather than a job, which is every template that existed before v4.
101 """
102 schema = _schema("templates")
103 assert schema["version"] >= 4
104 by_name = {f["name"]: f for f in schema["fields"]}
105
106 # Fields present since v1, untouched.
107 for name in ("id", "name", "description", "category", "body", "tags",
108 "is_public", "created_at", "owner_id"):
109 assert name in by_name, f"v1 field {name!r} must not be removed"
110 assert by_name["name"]["required"] is True
111 assert by_name["body"]["required"] is True
112 assert by_name["is_public"]["type"] == "boolean"
113 assert by_name["is_public"]["default"] == "false"
114
115 # New v2 fields -- none required, so v1 records missing them stay valid.
116 for new_field in ("schema", "ui_schema", "instructions", "ai_prompt",
117 "default_values", "example_data"):
118 field = by_name[new_field]
119 assert field["type"] == "textarea"
120 assert "required" not in field or not field["required"]
121
122 ai_assistance = by_name["ai_assistance"]
123 assert ai_assistance["type"] == "enum"
124 assert_includes_in_order(ai_assistance["enum"], ["none", "suggestions", "auto_fill", "full"])
125 assert ai_assistance["default"] == "suggestions"
126
127
128def test_templates_json_fields_have_no_dedicated_json_type():
129 """This codebase's field-type contract (docs/schema-forms.md) only
130 lists text/textarea/integer/number/boolean/date/datetime/enum/computed
131 -- there is no `json` type. schema/ui_schema/default_values/example_data
132 therefore store JSON as a string in a `textarea` field, the same
133 convention app-invoices uses for structured text (e.g. customer_address)
134 and the one now mirrored by app-tasks' `metadata` field.
135 """
136 contract = (Path(__file__).resolve().parents[1] / "docs" / "schema-forms.md").read_text()
137 type_line = next(line for line in contract.splitlines() if line.strip().startswith("- `type`"))
138 declared_types = re.findall(r"`([a-z_]+)`", type_line)
139 assert "json" not in declared_types
140 by_name = {f["name"]: f for f in _schema("templates")["fields"]}
141 for json_field in ("schema", "ui_schema", "default_values", "example_data"):
142 assert by_name[json_field]["type"] == "textarea"
143
144
145def test_templates_form_and_list_wire_the_new_fields():
146 schema = _schema("templates")
147 assert_includes_in_order(schema["forms"]["default"]["fields"], [
148 "name", "description", "category", "body", "schema",
149 "instructions", "ai_prompt", "ai_assistance",
150 "default_values", "tags", "is_public",
151 ])
152 assert "ai_assistance" in schema["views"]["list_fields"]
153 assert "instructions" in schema["search"]["fields"]
154
155
156def test_ai_assistance_fields_are_config_only_not_an_ai_engine():
157 """ai_prompt/ai_assistance are stored config; nothing in this package
158 (or repo) reads them to call an AI provider. Same posture as other
159 deferred-infra fields elsewhere in this codebase.
160 """
161 for path in APP_TEMPLATES_DIR.rglob("*.py"):
162 text = path.read_text(encoding="utf-8", errors="ignore")
163 assert "openai" not in text.lower()
164 assert "anthropic" not in text.lower()
165
166
167def test_seed_tsv_is_header_only_and_matches_schema_field_order():
168 schema = _schema("templates")
169 path = APP_TEMPLATES_DIR / "seed" / "templates.tsv"
170 lines = path.read_text().splitlines()
171 assert len(lines) == 1, "templates.tsv should be header-only"
172 header = lines[0].split("\t")
173 assert header == [f["name"] for f in schema["fields"]]
174
175
176def test_additive_field_adds_need_no_migration_entry():
177 """This system has no migration *execution* at all yet -- every
178 package in the repo ships an empty "migrations": [] array, and
179 object_packages.py's own install-plan builder refuses to proceed if a
180 package declares any migration ("Package migration execution is not
181 implemented yet"). Records are schemaless TSV rows (object_records.py's
182 _project_record fills any field missing from a row with ""), so an
183 additive field-add is already fully handled by the schema change alone.
184 """
185 package = object_packages.get_package("app-templates", root=PACKAGES_ROOT)
186 assert package["migrations"] == []
187
188 source = Path(object_packages.__file__).read_text()
189 assert "Package migration execution is not implemented yet" in source
190
191
192def test_create_template_record_accepts_new_structured_fields(tmp_path):
193 data_dir = tmp_path / "data"
194 schema_path = data_dir / "schemas" / "templates.json"
195 schema_path.parent.mkdir(parents=True, exist_ok=True)
196 schema_path.write_text((APP_TEMPLATES_DIR / "schemas" / "templates.json").read_text())
197
198 record = object_records.create_collection_record(
199 "templates",
200 {
201 "id": "tpl_1",
202 "name": "Onboarding Contract",
203 "body": "fallback text",
204 "schema": json.dumps({"type": "object", "properties": {"amount": {"type": "number"}}}),
205 "default_values": json.dumps({"amount": 0}),
206 "ai_assistance": "auto_fill",
207 },
208 base_dir=data_dir,
209 roots=[],
210 )
211 assert record["ai_assistance"] == "auto_fill"
212 assert json.loads(record["schema"])["type"] == "object"
213
214 # A v1-style record with none of the new fields must still be valid
215 # (additive fields read back as empty, never required).
216 legacy = object_records.create_collection_record(
217 "templates",
218 {"id": "tpl_2", "name": "Legacy Template", "body": "just a body"},
219 base_dir=data_dir,
220 roots=[],
221 )
222 assert legacy["schema"] == ""
223 assert legacy["ai_assistance"] in ("", "suggestions")
224
225
226def _app_templates_policy():
227 payload = json.loads((APP_TEMPLATES_DIR / "permissions" / "rules.json").read_text())
228 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
229
230
231def test_owner_can_crud_own_templates():
232 policy = _app_templates_policy()
233 subject = object_permissions.PermissionSubject(user_id="7")
234 record = {"owner_id": "7", "name": "Mine", "is_public": "false"}
235 for action in (
236 object_permissions.CREATE, object_permissions.READ,
237 object_permissions.UPDATE, object_permissions.DELETE,
238 ):
239 decision = object_permissions.check_permission(
240 subject, action, policy=policy, collection="templates", record=record,
241 )
242 assert decision.allowed is True, f"templates/{action} should be allowed for the owner"
243
244
245def test_others_cannot_touch_someone_elses_private_template():
246 policy = _app_templates_policy()
247 subject = object_permissions.PermissionSubject(user_id="8")
248 record = {"owner_id": "7", "name": "Not mine", "is_public": "false"}
249 for action in (
250 object_permissions.UPDATE, object_permissions.DELETE,
251 ):
252 decision = object_permissions.check_permission(
253 subject, action, policy=policy, collection="templates", record=record,
254 )
255 assert decision.allowed is False, f"templates/{action} should be denied for a non-owner"
256
257
258def test_registered_user_can_read_a_public_template():
259 policy = _app_templates_policy()
260 subject = object_permissions.PermissionSubject(user_id="8")
261 record = {"owner_id": "7", "name": "Shared", "is_public": "true"}
262 decision = object_permissions.check_permission(
263 subject, object_permissions.READ, policy=policy, collection="templates", record=record,
264 )
265 assert decision.allowed is True
266
267
268def test_anonymous_cannot_read_any_template():
269 policy = _app_templates_policy()
270 record = {"owner_id": "7", "name": "Shared", "is_public": "true"}
271 decision = object_permissions.check_permission(
272 None, object_permissions.READ, policy=policy, collection="templates", record=record,
273 )
274 assert decision.allowed is False
275
276
277def test_no_public_execute_grant_survives_for_the_deleted_templates_page():
278 """/templates is a seeded view; no package ships site_templates, so a
279 public grant for it would make any object later created under that id
280 public without anybody deciding so (bug-reports/2026-11-28-06-14-43)."""
281 policy = _app_templates_policy()
282 decision = object_permissions.check_permission(
283 None, object_permissions.EXECUTE, policy=policy, object_id="site_templates",
284 )
285 assert decision.allowed is False
286
287
288def test_no_disallowed_org_names_leak_into_the_package():
289 """Public repo hygiene: no internal org/codename references anywhere
290 in this package's source.
291 """
292 # Built from fragments so this guard file itself stays clean of the very
293 # internal names it forbids (otherwise the test would flag its own source).
294 banned = re.compile(
295 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
296 re.IGNORECASE,
297 )
298 for path in APP_TEMPLATES_DIR.rglob("*"):
299 if "__pycache__" in path.parts:
300 continue # compiled bytes can match a name by chance
301 if path.is_dir():
302 continue
303 text = path.read_text(encoding="utf-8", errors="ignore")
304 assert not banned.search(text), f"disallowed reference found in {path}"
305
306
307def test_this_test_file_has_no_disallowed_org_names():
308 banned = re.compile(
309 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
310 re.IGNORECASE,
311 )
312 text = Path(__file__).read_text(encoding="utf-8", errors="ignore")
313 assert not banned.search(text), "disallowed reference found in this test file itself"