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_worker_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_worker_package.py · 14.1 KB · 362 lines
1"""Structural tests for packages/app-worker (profiles, follows,
2profile_comments).
3
4Mirrors the package/schema/permission testing conventions used for
5packages/app-forum in tests/test_app_forum_package.py. app-worker has no
6HANDLES handler and no behavior module, so this is the whole suite.
7"""
8
9import json
10import re
11from pathlib import Path
12
13import object_packages
14import object_permissions
15import object_schemas
16from package_pins import assert_includes_in_order
17
18PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
19APP_WORKER_DIR = PACKAGES_ROOT / "app-worker"
20
21
22def _profiles_schema():
23 return json.loads((APP_WORKER_DIR / "schemas" / "profiles.json").read_text())
24
25
26def _follows_schema():
27 return json.loads((APP_WORKER_DIR / "schemas" / "follows.json").read_text())
28
29
30def _comments_schema():
31 return json.loads((APP_WORKER_DIR / "schemas" / "profile_comments.json").read_text())
32
33
34def test_get_package_normalizes_app_worker_manifest():
35 package = object_packages.get_package("app-worker", root=PACKAGES_ROOT)
36
37 assert package["id"] == "app-worker"
38 assert package["name"] == "Worker"
39 assert {schema["collection"] for schema in package["schemas"]} >= {
40 "profiles",
41 "follows",
42 "profile_comments",
43 }
44 assert {obj["id"] for obj in package["objects"]} >= {
45 "site_profile",
46 "site_profile_edit",
47 }
48 assert {"path": "permissions/rules.json"} in package["permissions"]
49 assert {entry["collection"] for entry in package["seed"]} >= {
50 "profiles",
51 "follows",
52 "profile_comments",
53 }
54 # Since 0.2.0: an attention count (app-nav) that opens a seeded view (app-views).
55 assert [dep["id"] for dep in package["dependencies"]] == ["app-nav", "app-views"]
56
57
58def test_dry_run_app_worker_package_is_safe(tmp_path):
59 object_root = tmp_path / "objects"
60 object_root.mkdir()
61
62 plan = object_packages.dry_run_package(
63 "app-worker",
64 root=PACKAGES_ROOT,
65 base_dir=tmp_path / "data",
66 object_roots=[object_root],
67 )
68
69 assert plan["safe_to_install"] is True
70 assert plan["warnings"] == []
71 assert {schema["collection"] for schema in plan["schemas"]} >= {
72 "profiles",
73 "follows",
74 "profile_comments",
75 }
76
77
78def test_install_app_worker_package_loads_schemas(tmp_path):
79 data_dir = tmp_path / "data"
80 object_root = tmp_path / "objects"
81 object_root.mkdir()
82
83 object_packages.install_package(
84 "app-worker",
85 root=PACKAGES_ROOT,
86 base_dir=data_dir,
87 object_roots=[object_root],
88 )
89
90 profiles_schema = object_schemas.get_schema("profiles", base_dir=data_dir)
91 follows_schema = object_schemas.get_schema("follows", base_dir=data_dir)
92 comments_schema = object_schemas.get_schema("profile_comments", base_dir=data_dir)
93
94 assert profiles_schema["name"] == "profiles"
95 assert follows_schema["name"] == "follows"
96 assert comments_schema["name"] == "profile_comments"
97 assert (object_root / "site" / "profile.py").is_file()
98 assert (object_root / "site" / "profile_edit.py").is_file()
99
100
101def test_schema_json_files_are_valid_and_versioned():
102 for name in ("profiles", "follows", "profile_comments"):
103 payload = json.loads((APP_WORKER_DIR / "schemas" / f"{name}.json").read_text())
104 assert payload["name"] == name
105 assert payload["version"] >= 1
106
107
108def test_three_collections_present_with_expected_field_names():
109 profile_fields = [f["name"] for f in _profiles_schema()["fields"]]
110 assert_includes_in_order(profile_fields, [
111 "id", "display_name", "bio", "skills", "experience", "location",
112 "education", "website", "social_links", "is_active", "owner_id",
113 "created_at",
114 ])
115
116 follow_fields = [f["name"] for f in _follows_schema()["fields"]]
117 assert_includes_in_order(follow_fields, [
118 "id", "follower_id", "following_id", "created_at", "owner_id",
119 ])
120
121 comment_fields = [f["name"] for f in _comments_schema()["fields"]]
122 assert_includes_in_order(comment_fields, [
123 "id", "profile_id", "author_name", "author_email", "author_url",
124 "content", "status", "ip_address", "created_at", "owner_id",
125 ])
126
127
128def test_skills_is_free_text_not_a_relation():
129 """SCOPE RULE: the source model's skills field is free text, not a
130 skills-matching taxonomy or relation. No skills collection, no
131 availability field, exists anywhere in this package.
132 """
133 by_name = {f["name"]: f for f in _profiles_schema()["fields"]}
134 assert by_name["skills"]["type"] == "text"
135 assert "relation" not in by_name["skills"]
136
137 field_names = {f["name"] for f in _profiles_schema()["fields"]}
138 assert "availability" not in field_names
139 assert "rating" not in field_names
140 assert "reviews" not in field_names
141
142
143def test_profiles_forms_and_views_match_the_brief():
144 schema = _profiles_schema()
145 assert_includes_in_order(schema["forms"]["default"]["fields"], [
146 "display_name", "bio", "skills", "experience", "location",
147 "education", "website", "social_links", "is_active",
148 ])
149 assert_includes_in_order(schema["search"]["fields"], ["display_name", "skills", "bio"])
150
151
152def test_profiles_is_active_defaults_true():
153 by_name = {f["name"]: f for f in _profiles_schema()["fields"]}
154 assert by_name["is_active"]["type"] == "boolean"
155 assert by_name["is_active"]["default"] == "true"
156
157
158def test_follows_storage_is_append_and_edge_is_directed():
159 schema = _follows_schema()
160 assert schema["storage"] == "append"
161
162 by_name = {f["name"]: f for f in schema["fields"]}
163 assert by_name["follower_id"]["type"] == "text"
164 assert by_name["follower_id"]["required"] is True
165 assert by_name["following_id"]["type"] == "text"
166 assert by_name["following_id"]["required"] is True
167
168
169def test_follows_has_no_search_block():
170 assert "search" not in _follows_schema()
171
172
173def test_profile_comments_status_enum_and_defaults():
174 by_name = {f["name"]: f for f in _comments_schema()["fields"]}
175 status_field = by_name["status"]
176 assert_includes_in_order(status_field["enum"], ["pending", "approved", "rejected"])
177 assert status_field["default"] == "pending"
178
179
180def test_profile_comments_transitions_match_the_brief():
181 by_name = {f["name"]: f for f in _comments_schema()["fields"]}
182 transitions = by_name["status"]["transitions"]
183 # Unguarded since 0.2.0: the guard was owner_id == $user_id (only the
184 # commenter could move it), which since status became `owner: read`
185 # nobody could use. Who moves status is the field permission's call
186 # (role:moderator, not on their own comment): tests/test_comment_moderation.py.
187 assert transitions == {"pending": ["approved", "rejected"], "approved": ["rejected"]}
188 # rejected is terminal: no entry in the transitions map at all.
189 assert "rejected" not in transitions
190
191
192def test_profile_comments_hidden_fields():
193 by_name = {f["name"]: f for f in _comments_schema()["fields"]}
194 assert by_name["author_email"]["permissions"] == {"public": "hidden"}
195 assert by_name["ip_address"]["permissions"] == {"public": "hidden"}
196 # Not `public: hidden`: `public` matches every caller, so the author,
197 # moderators and the admin token could not read or set it either. The
198 # same grant as thread_comments.status.
199 assert by_name["status"]["permissions"] == {
200 "owner": "read", "role:moderator": "edit", "default": "hidden",
201 }
202
203
204def test_profile_comments_content_and_profile_id_required():
205 by_name = {f["name"]: f for f in _comments_schema()["fields"]}
206 assert by_name["profile_id"]["required"] is True
207 assert by_name["profile_id"]["relation"]["collection"] == "profiles"
208 assert by_name["content"]["required"] is True
209
210
211def test_profile_comments_has_no_search_block():
212 assert "search" not in _comments_schema()
213
214
215def _app_worker_policy():
216 payload = json.loads((APP_WORKER_DIR / "permissions" / "rules.json").read_text())
217 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
218
219
220def test_anonymous_can_read_any_profile_and_follow_edge():
221 policy = _app_worker_policy()
222 someone_elses_profile = {"owner_id": "7", "display_name": "Ada"}
223 someone_elses_follow = {"owner_id": "7", "follower_id": "7", "following_id": "8"}
224
225 for collection, record in (
226 ("profiles", someone_elses_profile),
227 ("follows", someone_elses_follow),
228 ):
229 decision = object_permissions.check_permission(
230 None, object_permissions.READ, policy=policy, collection=collection, record=record
231 )
232 assert decision.allowed is True, f"anonymous read should be allowed on {collection}"
233
234
235def test_anonymous_can_read_only_approved_profile_comments():
236 policy = _app_worker_policy()
237 approved = {"owner_id": "9", "profile_id": "p1", "content": "hi", "status": "approved"}
238 pending = {"owner_id": "9", "profile_id": "p1", "content": "hi", "status": "pending"}
239 rejected = {"owner_id": "9", "profile_id": "p1", "content": "spam", "status": "rejected"}
240
241 approved_decision = object_permissions.check_permission(
242 None, object_permissions.READ, policy=policy, collection="profile_comments", record=approved
243 )
244 assert approved_decision.allowed is True
245
246 for record in (pending, rejected):
247 decision = object_permissions.check_permission(
248 None, object_permissions.READ, policy=policy, collection="profile_comments", record=record
249 )
250 assert decision.allowed is False
251
252
253def test_owner_can_crud_own_profile_follow_and_comment():
254 policy = _app_worker_policy()
255 subject = object_permissions.PermissionSubject(user_id="7")
256 records = {
257 "profiles": {"owner_id": "7", "display_name": "Ada"},
258 "follows": {"owner_id": "7", "follower_id": "7", "following_id": "8"},
259 "profile_comments": {"owner_id": "7", "profile_id": "p1", "content": "hi", "status": "pending"},
260 }
261
262 for collection, record in records.items():
263 for action in (
264 object_permissions.CREATE,
265 object_permissions.READ,
266 object_permissions.UPDATE,
267 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 True, f"owner {action} should be allowed on {collection}"
273
274
275def test_others_cannot_write_someone_elses_profile_follow_or_comment():
276 policy = _app_worker_policy()
277 subject = object_permissions.PermissionSubject(user_id="8")
278 records = {
279 "profiles": {"owner_id": "7", "display_name": "Ada"},
280 "follows": {"owner_id": "7", "follower_id": "7", "following_id": "9"},
281 "profile_comments": {"owner_id": "7", "profile_id": "p1", "content": "hi", "status": "pending"},
282 }
283
284 for collection, record in records.items():
285 for action in (object_permissions.UPDATE, object_permissions.DELETE):
286 decision = object_permissions.check_permission(
287 subject, action, policy=policy, collection=collection, record=record
288 )
289 assert decision.allowed is False, f"non-owner {action} should be denied on {collection}"
290
291
292def test_anonymous_cannot_create_a_profile_comment():
293 """v1 guestbook posting is signed-in only -- no public create rule is
294 granted on profile_comments (see schemas/profile_comments.json and
295 dbbasic-package.json's deferred list for the anonymous path).
296 """
297 policy = _app_worker_policy()
298 record = {"profile_id": "p1", "content": "hi", "status": "pending"}
299
300 decision = object_permissions.check_permission(
301 None, object_permissions.CREATE, policy=policy, collection="profile_comments", record=record
302 )
303 assert decision.allowed is False
304
305
306def test_worker_pages_are_publicly_executable():
307 policy = _app_worker_policy()
308
309 for object_id in ("site_profile", "site_profile_edit"):
310 decision = object_permissions.check_permission(
311 None, object_permissions.EXECUTE, policy=policy, object_id=object_id
312 )
313 assert decision.allowed is True
314
315
316def test_seed_tsvs_have_no_data_rows_and_match_schema_field_order():
317 """Header-only seeds, matching the established precedent (app-tasks,
318 app-notes, app-invoices, app-forum all ship header-only seeds).
319 """
320 for name, schema in (
321 ("profiles", _profiles_schema()),
322 ("follows", _follows_schema()),
323 ("profile_comments", _comments_schema()),
324 ):
325 path = APP_WORKER_DIR / "seed" / f"{name}.tsv"
326 lines = path.read_text().splitlines()
327 assert len(lines) == 1, f"{name}.tsv should be header-only"
328 header = lines[0].split("\t")
329 assert header == [f["name"] for f in schema["fields"]]
330
331
332def test_no_disallowed_org_names_leak_into_the_package():
333 """Public repo hygiene: no internal org/codename references anywhere
334 in this package's source, including in any source-doc path reference
335 (this package describes its source only as "a private
336 predecessor-system audit, not part of this repo").
337 """
338 # Built from fragments so this guard file itself stays clean of the
339 # very internal names it forbids.
340 banned = re.compile(
341 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
342 re.IGNORECASE,
343 )
344 for path in APP_WORKER_DIR.rglob("*"):
345 if "__pycache__" in path.parts:
346 continue # compiled bytes can match a name by chance
347 if path.is_dir():
348 continue
349 text = path.read_text(encoding="utf-8", errors="ignore")
350 assert not banned.search(text), f"disallowed reference found in {path}"
351
352
353def test_package_does_not_touch_app_shell_or_app_theme():
354 """This package's brief explicitly forbids editing packages/app-shell
355 or packages/app-theme (nav/home wiring is the main loop's job). This
356 test only asserts app-worker's own manifest declares no dependency on
357 them; it cannot detect a stray edit elsewhere in the repo, but keeps
358 the intent on record.
359 """
360 manifest = json.loads((APP_WORKER_DIR / "dbbasic-package.json").read_text())
361 assert "app-shell" not in manifest.get("dependencies", [])
362 assert "app-theme" not in manifest.get("dependencies", [])