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