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_tasks_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, 18 minutes ago History
test_app_tasks_package.py · 16.9 KB · 408 lines
1"""Structural tests for packages/app-tasks (tasks).
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-tasks before this one; it fills that gap while also
7covering the v5 -> v6 "Work / CreateWork" field additions (task_type/
8template_id/instructions/metadata), reconciled against a private
9predecessor-system audit, not part of this repo. The guarded-transition
10machinery on `status` (schema v5's headline feature) is asserted intact
11and untouched throughout.
12"""
13
14import json
15import re
16from pathlib import Path
17
18import object_packages
19import object_permissions
20import object_records
21import object_schemas
22from package_pins import assert_includes_in_order
23
24PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
25APP_TASKS_DIR = PACKAGES_ROOT / "app-tasks"
26
27_SCHEMA_NAMES = ("tasks",)
28
29
30def _schema(name):
31 return json.loads((APP_TASKS_DIR / "schemas" / f"{name}.json").read_text())
32
33
34def test_get_package_normalizes_app_tasks_manifest():
35 package = object_packages.get_package("app-tasks", root=PACKAGES_ROOT)
36
37 assert package["id"] == "app-tasks"
38 assert package["name"] == "Tasks"
39 assert {schema["collection"] for schema in package["schemas"]} >= set(_SCHEMA_NAMES)
40 # 0.2.0 deletes the bespoke /tasks list page object: it held no business
41 # logic and is now a seeded VIEW record over the generic `list` block.
42 assert package["objects"] == []
43 assert {"path": "permissions/rules.json"} in package["permissions"]
44 # Plus "views"/"site_routes": one 59 detail view + route (/tasks/{id})
45 # composing task_comments and files as related children.
46 assert {entry["collection"] for entry in package["seed"]} >= set(_SCHEMA_NAMES) | {
47 "views", "site_routes",
48 }
49 assert package["migrations"] == []
50 # template_id is a soft/optional relation (see dbbasic-package.json's
51 # description) -- no install-order dependency on app-templates is
52 # declared, the same choice app-invoices made for customer_id -> contacts.
53 assert {"id": "app-projects", "version": None} in package["dependencies"]
54
55
56def test_dry_run_app_tasks_package_is_safe(tmp_path):
57 object_root = tmp_path / "objects"
58 object_root.mkdir()
59
60 plan = object_packages.dry_run_package(
61 "app-tasks",
62 root=PACKAGES_ROOT,
63 base_dir=tmp_path / "data",
64 object_roots=[object_root],
65 )
66
67 assert plan["safe_to_install"] is True
68 assert plan["warnings"] == []
69 assert {schema["collection"] for schema in plan["schemas"]} >= set(_SCHEMA_NAMES)
70
71
72def test_install_app_tasks_package_loads_schema(tmp_path):
73 data_dir = tmp_path / "data"
74 object_root = tmp_path / "objects"
75 object_root.mkdir()
76
77 object_packages.install_package(
78 "app-tasks", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root],
79 )
80
81 schema = object_schemas.get_schema("tasks", base_dir=data_dir)
82 assert schema["name"] == "tasks"
83 # tasks.py was deleted (0.2.0): the /tasks list page is now a seeded
84 # VIEW record over the generic `list` block, not an installed object file.
85 assert not (object_root / "site" / "tasks.py").exists()
86
87
88def test_schema_json_file_is_valid():
89 payload = _schema("tasks")
90 assert payload["name"] == "tasks"
91 assert isinstance(payload["version"], int)
92
93
94def test_tasks_schema_is_now_version_6_additive_only():
95 """tasks.json went 5 -> 6 adding task_type/template_id/instructions/
96 metadata, then 7 -> 8 adding views.filter_fields (status/urgency) for the
97 generative filter bar, then 8 -> 9 adding capabilities.comments (the
98 generic comment thread on the task detail), then 9 -> 10 adding
99 capabilities.attachments (the generic attachment widget), then 10 -> 11
100 adding capabilities.shareable (the generic record-sharing widget). Every
101 field that existed at v5 is still present, unchanged in name/type -- these
102 schema changes are purely additive.
103 """
104 schema = _schema("tasks")
105 # A label nothing compares: "at least the version that added all of this", not an
106 # exact number every later schema edit would have to chase (docs/package-authoring.md,
107 # "What A Schema's version Does").
108 assert schema["version"] >= 11
109 assert_includes_in_order(schema["views"]["filter_fields"], ["status", "urgency"])
110 assert schema["capabilities"]["comments"] is True
111 assert schema["capabilities"]["attachments"] is True
112 assert schema["capabilities"]["shareable"] is True
113 by_name = {f["name"]: f for f in schema["fields"]}
114
115 for name in ("id", "title", "description", "project_id", "status",
116 "urgency", "due_date", "assigned_to", "created_at", "owner_id"):
117 assert name in by_name, f"v5 field {name!r} must not be removed"
118 assert by_name["title"]["required"] is True
119 assert by_name["created_at"]["read_only"] is True
120
121 for new_field in ("instructions", "metadata"):
122 field = by_name[new_field]
123 assert field["type"] == "textarea"
124 assert "required" not in field or not field["required"]
125
126 task_type = by_name["task_type"]
127 assert task_type["type"] == "enum"
128 assert_includes_in_order(task_type["enum"], ["BASIC", "STANDARD", "CONTRACT"])
129 assert task_type["default"] == "STANDARD"
130
131 template_id = by_name["template_id"]
132 assert template_id["relation"]["collection"] == "templates"
133 assert "required" not in template_id or not template_id["required"]
134
135
136def test_metadata_field_has_no_dedicated_json_type():
137 """Same convention as app-templates' schema/default_values fields --
138 this codebase's field-type contract (docs/schema-forms.md) has no
139 dedicated json type, so metadata stores JSON as a string in a
140 `textarea` field.
141 """
142 by_name = {f["name"]: f for f in _schema("tasks")["fields"]}
143 assert by_name["metadata"]["type"] == "textarea"
144
145
146def test_urgency_is_exact_source_parity_and_untouched():
147 """The parity doc calls urgency an EXACT MATCH with the audited
148 predecessor and says not to alter it.
149 """
150 urgency = {f["name"]: f for f in _schema("tasks")["fields"]}["urgency"]
151 assert_includes_in_order(urgency["enum"], ["low", "normal", "high", "critical"])
152 assert urgency["default"] == "normal"
153 assert "transitions" not in urgency
154
155
156def test_status_guarded_transitions_are_completely_untouched():
157 """The headline feature of schema v5 -- who-per-verb transition guards
158 on `status` -- must survive the v6 field-add byte-for-byte in shape.
159 """
160 status = {f["name"]: f for f in _schema("tasks")["fields"]}["status"]
161 assert_includes_in_order(status["enum"], [
162 "draft", "open", "assigned", "waiting_on_client",
163 "approved", "disputed", "cancelled",
164 ])
165 assert status["default"] == "open"
166 transitions = status["transitions"]
167 assert set(transitions.keys()) == {"draft", "open", "assigned", "waiting_on_client", "disputed"}
168
169 draft_targets = {entry["to"] for entry in transitions["draft"]}
170 assert draft_targets == {"open", "assigned", "cancelled"}
171 assert all(entry["when"] == {"owner_id": "$user_id"} for entry in transitions["draft"])
172
173 open_targets = {
174 entry if isinstance(entry, str) else entry["to"] for entry in transitions["open"]
175 }
176 assert open_targets == {"assigned", "cancelled"}
177
178 assigned_targets = {entry["to"] for entry in transitions["assigned"]}
179 assert assigned_targets == {"waiting_on_client", "open", "cancelled"}
180
181 waiting_targets = {
182 entry if isinstance(entry, str) else entry["to"]
183 for entry in transitions["waiting_on_client"]
184 }
185 assert waiting_targets == {"approved", "disputed", "assigned"}
186
187 disputed_targets = {entry["to"] for entry in transitions["disputed"]}
188 assert disputed_targets == {"assigned", "cancelled"}
189 # approved and cancelled remain terminal (absent from the map).
190 assert "approved" not in transitions
191 assert "cancelled" not in transitions
192
193
194def test_guarded_transition_enforcement_still_works_end_to_end(tmp_path):
195 """Exercises the guard machinery against the live v6 schema file (not
196 a stand-in), the same shape as test_object_import.py's schema-delta
197 check, to prove the v6 field-add didn't disturb enforcement.
198 """
199 data_dir = tmp_path / "data"
200 schema_path = data_dir / "schemas" / "tasks.json"
201 schema_path.parent.mkdir(parents=True, exist_ok=True)
202 schema_path.write_text((APP_TASKS_DIR / "schemas" / "tasks.json").read_text())
203
204 task = object_records.create_collection_record(
205 "tasks",
206 {"id": "t1", "title": "Draft task", "status": "draft", "task_type": "CONTRACT"},
207 base_dir=data_dir,
208 roots=[],
209 )
210 assert task["status"] == "draft"
211 assert task["task_type"] == "CONTRACT"
212
213 updated = object_records.update_collection_record(
214 "tasks", "t1", {"status": "assigned"}, base_dir=data_dir, roots=[],
215 )
216 assert updated["status"] == "assigned"
217
218 task2 = object_records.create_collection_record(
219 "tasks", {"id": "t2", "title": "Another", "status": "assigned"}, base_dir=data_dir, roots=[],
220 )
221 with __import__("pytest").raises(object_records.InvalidRecordPayloadError):
222 object_records.update_collection_record(
223 "tasks", "t2", {"status": "draft"}, base_dir=data_dir, roots=[],
224 )
225
226
227def test_tasks_form_and_list_wire_the_new_fields():
228 schema = _schema("tasks")
229 assert_includes_in_order(schema["forms"]["default"]["fields"], [
230 "title", "description", "instructions", "project_id",
231 "task_type", "template_id", "status", "urgency", "due_date", "assigned_to",
232 ])
233 assert "task_type" in schema["views"]["list_fields"]
234 assert "instructions" in schema["search"]["fields"]
235
236
237def test_create_task_record_accepts_new_work_fields(tmp_path):
238 data_dir = tmp_path / "data"
239 schema_path = data_dir / "schemas" / "tasks.json"
240 schema_path.parent.mkdir(parents=True, exist_ok=True)
241 schema_path.write_text((APP_TASKS_DIR / "schemas" / "tasks.json").read_text())
242
243 templates_schema_path = data_dir / "schemas" / "templates.json"
244 templates_schema_path.write_text(
245 (PACKAGES_ROOT / "app-templates" / "schemas" / "templates.json").read_text()
246 )
247 object_records.create_collection_record(
248 "templates", {"id": "tpl_1", "name": "A Template", "body": "x"},
249 base_dir=data_dir, roots=[],
250 )
251
252 record = object_records.create_collection_record(
253 "tasks",
254 {
255 "id": "t3",
256 "title": "Ship the feature",
257 "task_type": "BASIC",
258 "template_id": "tpl_1",
259 "instructions": "Follow the checklist.",
260 "metadata": json.dumps({"priority_score": 8}),
261 },
262 base_dir=data_dir,
263 roots=[],
264 )
265 assert record["task_type"] == "BASIC"
266 assert record["template_id"] == "tpl_1"
267 assert json.loads(record["metadata"])["priority_score"] == 8
268
269 # A v5-style record with none of the new fields must still be valid
270 # (additive fields read back as empty/default, never required) and
271 # task_type falls back to its schema default.
272 legacy = object_records.create_collection_record(
273 "tasks", {"id": "t4", "title": "Old-style task"}, base_dir=data_dir, roots=[],
274 )
275 assert legacy["task_type"] == "STANDARD"
276 assert legacy["template_id"] == ""
277 assert legacy["metadata"] == ""
278
279
280def test_invalid_task_type_is_rejected(tmp_path):
281 data_dir = tmp_path / "data"
282 schema_path = data_dir / "schemas" / "tasks.json"
283 schema_path.parent.mkdir(parents=True, exist_ok=True)
284 schema_path.write_text((APP_TASKS_DIR / "schemas" / "tasks.json").read_text())
285
286 with __import__("pytest").raises(object_records.InvalidRecordPayloadError):
287 object_records.create_collection_record(
288 "tasks", {"id": "t5", "title": "Bad", "task_type": "URGENT"},
289 base_dir=data_dir, roots=[],
290 )
291
292
293def test_seed_tsv_is_header_only_and_omits_only_the_stamped_created_at_field():
294 """tasks.tsv ships header-only (established precedent: app-notes,
295 app-contacts, app-invoices all ship header-only seeds too). The header
296 matches the schema's own field order for readability, the same as
297 app-invoices' seed -- except `created_at`, which was already omitted
298 from this seed file before v6 (it's the server-stamped read_only
299 timestamp; nothing to seed) and stays omitted, unrelated to this
300 change.
301 """
302 schema = _schema("tasks")
303 path = APP_TASKS_DIR / "seed" / "tasks.tsv"
304 lines = path.read_text().splitlines()
305 assert len(lines) == 1, "tasks.tsv should be header-only"
306 header = lines[0].split("\t")
307 expected = [f["name"] for f in schema["fields"] if f["name"] != "created_at"]
308 assert header == expected
309
310
311def test_additive_field_adds_need_no_migration_entry():
312 """This system has no migration *execution* at all yet -- every
313 package in the repo ships an empty "migrations": [] array, and
314 object_packages.py's own install-plan builder refuses to proceed if a
315 package declares any migration ("Package migration execution is not
316 implemented yet"). Records are schemaless TSV rows (object_records.py's
317 _project_record fills any field missing from a row with ""), so an
318 additive field-add is already fully handled by the schema change alone.
319 """
320 package = object_packages.get_package("app-tasks", root=PACKAGES_ROOT)
321 assert package["migrations"] == []
322
323 source = Path(object_packages.__file__).read_text()
324 assert "Package migration execution is not implemented yet" in source
325
326
327def _app_tasks_policy():
328 payload = json.loads((APP_TASKS_DIR / "permissions" / "rules.json").read_text())
329 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
330
331
332def test_owner_can_crud_own_task_with_new_fields():
333 policy = _app_tasks_policy()
334 subject = object_permissions.PermissionSubject(user_id="7")
335 record = {"owner_id": "7", "title": "Mine", "task_type": "CONTRACT", "template_id": "tpl_1"}
336 for action in (
337 object_permissions.CREATE, object_permissions.READ,
338 object_permissions.UPDATE, object_permissions.DELETE,
339 ):
340 decision = object_permissions.check_permission(
341 subject, action, policy=policy, collection="tasks", record=record,
342 )
343 assert decision.allowed is True, f"tasks/{action} should be allowed for the owner"
344
345
346def test_assignee_can_read_and_update_but_not_delete():
347 policy = _app_tasks_policy()
348 subject = object_permissions.PermissionSubject(user_id="9")
349 record = {"owner_id": "7", "assigned_to": "9", "title": "Assigned to me"}
350
351 for action in (object_permissions.READ, object_permissions.UPDATE):
352 decision = object_permissions.check_permission(
353 subject, action, policy=policy, collection="tasks", record=record,
354 )
355 assert decision.allowed is True
356
357 decision = object_permissions.check_permission(
358 subject, object_permissions.DELETE, policy=policy, collection="tasks", record=record,
359 )
360 assert decision.allowed is False
361
362
363def test_anonymous_cannot_read_any_task():
364 policy = _app_tasks_policy()
365 record = {"owner_id": "7", "title": "Private"}
366 decision = object_permissions.check_permission(
367 None, object_permissions.READ, policy=policy, collection="tasks", record=record,
368 )
369 assert decision.allowed is False
370
371
372def test_no_public_execute_grant_survives_for_the_deleted_tasks_page():
373 """/tasks is a seeded view; no package ships site_tasks, so a public
374 grant for it would make any object later created under that id public
375 without anybody deciding so (bug-reports/2026-11-28-06-14-43)."""
376 policy = _app_tasks_policy()
377 decision = object_permissions.check_permission(
378 None, object_permissions.EXECUTE, policy=policy, object_id="site_tasks",
379 )
380 assert decision.allowed is False
381
382
383def test_no_disallowed_org_names_leak_into_the_package():
384 """Public repo hygiene: no internal org/codename references anywhere
385 in this package's source.
386 """
387 # Built from fragments so this guard file itself stays clean of the very
388 # internal names it forbids (otherwise the test would flag its own source).
389 banned = re.compile(
390 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
391 re.IGNORECASE,
392 )
393 for path in APP_TASKS_DIR.rglob("*"):
394 if "__pycache__" in path.parts:
395 continue # compiled bytes can match a name by chance
396 if path.is_dir():
397 continue
398 text = path.read_text(encoding="utf-8", errors="ignore")
399 assert not banned.search(text), f"disallowed reference found in {path}"
400
401
402def test_this_test_file_has_no_disallowed_org_names():
403 banned = re.compile(
404 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
405 re.IGNORECASE,
406 )
407 text = Path(__file__).read_text(encoding="utf-8", errors="ignore")
408 assert not banned.search(text), "disallowed reference found in this test file itself"