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

0 downloads

dbbasic-object-server/tests/test_app_templates_package.py
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.

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