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_contacts_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_contacts_package.py · 13.8 KB · 326 lines
1"""Structural tests for packages/app-contacts (contacts, organizations,
2interactions, tags).
3
4Mirrors the package/schema/permission testing conventions used for
5packages/app-finance and packages/app-invoices in tests/test_app_finance_
6package.py and tests/test_app_invoices_package.py. There was no dedicated
7test file for app-contacts before this one; it fills that gap while also
8covering the CRM-depth field additions (lead_status/job_title on contacts;
9kind=task/outcome/duration_minutes/subject on interactions) reconciled
10against a private predecessor-system audit, not part of this repo.
11"""
12
13import json
14import re
15from pathlib import Path
16
17import object_packages
18import object_permissions
19import object_schemas
20from package_pins import assert_includes_in_order
21
22PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
23APP_CONTACTS_DIR = PACKAGES_ROOT / "app-contacts"
24
25_SCHEMA_NAMES = ("contacts", "organizations", "interactions", "tags")
26
27
28def _schema(name):
29 return json.loads((APP_CONTACTS_DIR / "schemas" / f"{name}.json").read_text())
30
31
32def test_get_package_normalizes_app_contacts_manifest():
33 package = object_packages.get_package("app-contacts", root=PACKAGES_ROOT)
34
35 assert package["id"] == "app-contacts"
36 assert package["name"] == "Contacts"
37 assert {schema["collection"] for schema in package["schemas"]} >= set(_SCHEMA_NAMES)
38 # 0.2.0 deletes the bespoke /contacts 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 {"path": "permissions/rules.json"} in package["permissions"]
43 # Plus "views"/"site_routes": one 59 detail view + route per collection,
44 # seeded into app-views'/site routing's own shared collections (a soft
45 # reference, like template_id's into app-templates -- see
46 # dbbasic-package.json's description).
47 assert {entry["collection"] for entry in package["seed"]} >= set(_SCHEMA_NAMES) | {
48 "views", "site_routes",
49 }
50 # No migration mechanism is exercised here: additive field-adds don't
51 # need one (see test_additive_field_adds_need_no_migration_entry below).
52 assert package["migrations"] == []
53
54
55def test_dry_run_app_contacts_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-contacts",
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_contacts_package_loads_schemas(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-contacts", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root],
78 )
79
80 for name in _SCHEMA_NAMES:
81 schema = object_schemas.get_schema(name, base_dir=data_dir)
82 assert schema["name"] == name
83
84 # contacts.py was deleted (0.2.0): the /contacts list page is now a
85 # seeded VIEW record over the generic `list` block.
86 assert not (object_root / "site" / "contacts.py").exists()
87
88
89def test_schema_json_files_are_valid():
90 for name in _SCHEMA_NAMES:
91 payload = _schema(name)
92 assert payload["name"] == name
93 assert isinstance(payload["version"], int)
94
95
96def test_contacts_schema_is_now_version_3_additive_only():
97 """contacts.json went 2 -> 3 adding job_title and lead_status. Every
98 field that existed at v2 is still present, unchanged in name/type --
99 this schema change is purely additive (live records with no value for
100 the new fields just read those fields back as empty, same as any other
101 optional field on a schemaless TSV collection).
102
103 v4 -> v5 added views.filter_fields (lead_status) for the generative
104 filter bar -- a views-only, additive change; no field was touched.
105 v5 -> v6 added full_name (computed formula over first/last -- the
106 formula-fields adopter; derived, never client-written).
107 """
108 schema = _schema("contacts")
109 # The history above is the claim; the number is a label nothing compares, so
110 # this asks for "at least the version that added all of it", not for an exact
111 # number that every later schema edit would have to chase (docs/package-authoring.md,
112 # "What A Schema's version Does").
113 assert schema["version"] >= 7
114 assert_includes_in_order(schema["views"]["filter_fields"], ["lead_status"])
115 by_name = {f["name"]: f for f in schema["fields"]}
116
117 # Fields present since v2, untouched.
118 for name in ("id", "first_name", "last_name", "email", "phone",
119 "organization_id", "project_id", "tags", "notes",
120 "created_at", "owner_id"):
121 assert name in by_name, f"v2 field {name!r} must not be removed"
122 assert by_name["first_name"]["required"] is True
123 assert by_name["organization_id"]["relation"]["collection"] == "organizations"
124 assert by_name["created_at"]["read_only"] is True
125
126 # New v3 fields.
127 assert by_name["job_title"]["type"] == "text"
128 assert "required" not in by_name["job_title"] or not by_name["job_title"]["required"]
129
130 lead_status = by_name["lead_status"]
131 assert lead_status["type"] == "enum"
132 assert_includes_in_order(lead_status["enum"], ["cold", "warm", "hot", "customer", "inactive"])
133 assert "required" not in lead_status or not lead_status["required"]
134 # No default is forced onto lead_status -- it's optional pipeline state.
135 assert "default" not in lead_status
136
137
138def test_contacts_has_no_redundant_free_text_organization_name():
139 """The source's create_contact also accepts a free-text `organization`
140 name alongside organization_id. This schema already has organization_id
141 as a relation into the organizations collection (display_field=name),
142 which covers the same need, so no separate organization_name field was
143 added -- adding one would just duplicate the relation.
144 """
145 by_name = {f["name"]: f for f in _schema("contacts")["fields"]}
146 assert "organization_name" not in by_name
147 assert by_name["organization_id"]["relation"]["display_field"] == "name"
148
149
150def test_contacts_form_and_list_wire_the_new_fields():
151 schema = _schema("contacts")
152 assert_includes_in_order(schema["forms"]["default"]["fields"], [
153 "first_name", "last_name", "email", "phone", "job_title",
154 "organization_id", "project_id", "lead_status", "tags", "notes",
155 ])
156 assert "lead_status" in schema["views"]["list_fields"]
157
158
159def test_interactions_schema_is_now_version_2_additive_only():
160 """interactions.json went 1 -> 2 adding "task" to kind's enum plus
161 subject/duration_minutes/outcome, then 2 -> 3 adding created_at (baseline
162 record metadata). occurred_on and summary are untouched.
163 """
164 schema = _schema("interactions")
165 assert schema["version"] >= 3
166 by_name = {f["name"]: f for f in schema["fields"]}
167
168 for name in ("id", "contact_id", "kind", "occurred_on", "summary", "created_at", "owner_id"):
169 assert name in by_name, f"v1 field {name!r} must not be removed"
170 assert by_name["contact_id"]["required"] is True
171 assert by_name["summary"]["required"] is True
172 assert by_name["occurred_on"]["type"] == "date"
173
174 kind = by_name["kind"]
175 assert_includes_in_order(kind["enum"], ["call", "email", "meeting", "note", "task"])
176 assert kind["default"] == "note"
177
178 assert by_name["subject"]["type"] == "text"
179
180 duration = by_name["duration_minutes"]
181 assert duration["type"] == "integer"
182
183 outcome = by_name["outcome"]
184 assert outcome["type"] == "enum"
185 assert_includes_in_order(outcome["enum"], ["positive", "neutral", "negative", "no_answer"])
186 assert "default" not in outcome
187
188
189def test_interactions_form_and_list_wire_the_new_fields():
190 schema = _schema("interactions")
191 assert_includes_in_order(schema["forms"]["default"]["fields"], [
192 "contact_id", "kind", "subject", "occurred_on",
193 "duration_minutes", "outcome", "summary",
194 ])
195 assert "subject" in schema["views"]["list_fields"]
196
197
198def test_organizations_and_tags_schemas_gain_only_created_at():
199 """Both got the baseline created_at metadata field (additive, v1 -> v2)
200 and nothing else -- every original field is still present, unchanged.
201 """
202 orgs = _schema("organizations")
203 assert orgs["version"] >= 2
204 assert {f["name"] for f in orgs["fields"]} == {
205 "id", "name", "website", "notes", "created_at", "owner_id",
206 }
207
208 tags = _schema("tags")
209 assert tags["version"] >= 2
210 assert {f["name"] for f in tags["fields"]} == {"id", "name", "created_at", "owner_id"}
211
212
213def test_additive_field_adds_need_no_migration_entry():
214 """This system has no migration *execution* at all yet -- every
215 package in the repo ships an empty "migrations": [] array, and
216 object_packages.py's own install-plan builder refuses to proceed if a
217 package declares any migration ("Package migration execution is not
218 implemented yet"). Records are schemaless TSV rows (object_records.py's
219 _project_record fills any field missing from a row with ""), so an
220 additive field-add is already fully handled by the schema change alone
221 -- there is nothing for a migration entry to do, and inventing one here
222 would be simulating a mechanism this codebase doesn't have yet.
223 """
224 package = object_packages.get_package("app-contacts", root=PACKAGES_ROOT)
225 assert package["migrations"] == []
226
227 source = Path(object_packages.__file__).read_text()
228 assert "Package migration execution is not implemented yet" in source
229
230
231def _app_contacts_policy():
232 payload = json.loads((APP_CONTACTS_DIR / "permissions" / "rules.json").read_text())
233 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
234
235
236def test_owner_can_crud_own_records_in_every_collection():
237 policy = _app_contacts_policy()
238 subject = object_permissions.PermissionSubject(user_id="7")
239 records = {
240 "contacts": {"owner_id": "7", "first_name": "Ada", "lead_status": "warm"},
241 "organizations": {"owner_id": "7", "name": "Acme"},
242 "interactions": {"owner_id": "7", "contact_id": "c_1", "kind": "task", "summary": "Follow up"},
243 "tags": {"owner_id": "7", "name": "vip"},
244 }
245 for collection, record in records.items():
246 for action in (
247 object_permissions.CREATE, object_permissions.READ,
248 object_permissions.UPDATE, object_permissions.DELETE,
249 ):
250 decision = object_permissions.check_permission(
251 subject, action, policy=policy, collection=collection, record=record,
252 )
253 assert decision.allowed is True, f"{collection}/{action} should be allowed for the owner"
254
255
256def test_others_cannot_touch_someone_elses_records():
257 policy = _app_contacts_policy()
258 subject = object_permissions.PermissionSubject(user_id="8")
259 records = {
260 "contacts": {"owner_id": "7", "first_name": "Ada"},
261 "organizations": {"owner_id": "7", "name": "Acme"},
262 "interactions": {"owner_id": "7", "contact_id": "c_1", "kind": "task", "summary": "Follow up"},
263 "tags": {"owner_id": "7", "name": "vip"},
264 }
265 for collection, record in records.items():
266 for action in (
267 object_permissions.READ, object_permissions.UPDATE, object_permissions.DELETE,
268 ):
269 decision = object_permissions.check_permission(
270 subject, action, policy=policy, collection=collection, record=record,
271 )
272 assert decision.allowed is False, f"{collection}/{action} should be denied for a non-owner"
273
274
275def test_anonymous_cannot_read_any_collection():
276 policy = _app_contacts_policy()
277 records = {
278 "contacts": {"owner_id": "7", "first_name": "Ada"},
279 "organizations": {"owner_id": "7", "name": "Acme"},
280 "interactions": {"owner_id": "7", "contact_id": "c_1", "kind": "task", "summary": "Follow up"},
281 "tags": {"owner_id": "7", "name": "vip"},
282 }
283 for collection, record in records.items():
284 decision = object_permissions.check_permission(
285 None, object_permissions.READ, policy=policy, collection=collection, record=record,
286 )
287 assert decision.allowed is False
288
289
290def test_no_public_execute_grant_survives_for_the_deleted_contacts_page():
291 """/contacts is a seeded view; no package ships site_contacts, so a
292 public grant for it would make any object later created under that id
293 public without anybody deciding so (bug-reports/2026-11-28-06-14-43)."""
294 policy = _app_contacts_policy()
295 decision = object_permissions.check_permission(
296 None, object_permissions.EXECUTE, policy=policy, object_id="site_contacts",
297 )
298 assert decision.allowed is False
299
300
301def test_no_disallowed_org_names_leak_into_the_package():
302 """Public repo hygiene: no internal org/codename references anywhere
303 in this package's source.
304 """
305 # Built from fragments so this guard file itself stays clean of the very
306 # internal names it forbids (otherwise the test would flag its own source).
307 banned = re.compile(
308 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
309 re.IGNORECASE,
310 )
311 for path in APP_CONTACTS_DIR.rglob("*"):
312 if "__pycache__" in path.parts:
313 continue # compiled bytes can match a name by chance
314 if path.is_dir():
315 continue
316 text = path.read_text(encoding="utf-8", errors="ignore")
317 assert not banned.search(text), f"disallowed reference found in {path}"
318
319
320def test_this_test_file_has_no_disallowed_org_names():
321 banned = re.compile(
322 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
323 re.IGNORECASE,
324 )
325 text = Path(__file__).read_text(encoding="utf-8", errors="ignore")
326 assert not banned.search(text), "disallowed reference found in this test file itself"