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_attention_declared_differential.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_attention_declared_differential.py · 18.8 KB · 395 lines
1"""Old provider vs declaration, same data, same viewer.
2
3The attention providers below were deleted in favour of a `collection` +
4`where` declaration (object_attention). The claim this file proves is that
5nothing a person is shown changed except what the permission rules say
6they may not see:
7
8- the label, link, door, group and severity of every migrated queue are
9 the ones the old manifest declared;
10- for every viewer, the declared count and detail equal what the DELETED
11 provider (loaded from the commit before its migration: 3e3240c for the
12 first eight, b014147 for invoices, parcels and mailboxes) answers when
13 it is shown only the rows that viewer may read. For an admin that is the
14 provider's answer over everything, i.e. exactly the old number;
15- the one intended difference, stated rather than hidden: the old number
16 was computed with no viewer and shown to every signed-in user, so a
17 member with no grant used to see the whole queue and now sees nothing.
18 The providers that stay code keep their one number, now shown only to a
19 viewer who may read every row it was folded from (the last test).
20
21The data is the real packages' schemas and permission rules (installed,
22not copied), with rows for an admin, a manager, two members and a
23signed-in user who owns nothing.
24"""
25
26from __future__ import annotations
27
28import importlib.util
29import json
30import subprocess
31import sys
32from datetime import date, datetime, timedelta, timezone
33from pathlib import Path
34
35import pytest
36
37import object_access
38import object_attention
39import object_packages
40import object_records
41
42ROOT = Path(__file__).resolve().parents[1]
43PACKAGES_ROOT = ROOT / "packages"
44# The commit before each migration: the first eight queues were declared
45# after 3e3240c, the next three (which needed a threshold read from a
46# setting and a fixed-sentence detail) after b014147.
47FIRST, SECOND = "3e3240c", "b014147"
48
49# attention id -> (package, deleted provider path, the commit it is read from)
50MIGRATED = {
51 "expenses_to_approve": ("app-finance", "objects/system/expense_attention.py", FIRST),
52 "time_to_approve": ("app-timers", "objects/system/time_attention.py", FIRST),
53 "backorders_waiting": ("app-catalog", "objects/system/backorder_attention.py", FIRST),
54 "disputes_open": ("app-disputes", "objects/system/dispute_attention.py", FIRST),
55 "scans_to_confirm": ("app-intake", "objects/system/scan_attention.py", FIRST),
56 "returns_to_disposition": ("app-returns", "objects/system/return_attention.py", FIRST),
57 "runs_needing_review": ("app-runner", "objects/system/review_attention.py", FIRST),
58 "bank_lines_unmatched": ("app-banking", "objects/system/bank_attention.py", FIRST),
59 "invoices_overdue": ("app-invoices", "objects/system/invoice_attention.py", SECOND),
60 "shipments_stuck_in_transit": ("app-shipping", "objects/system/shipment_attention.py", SECOND),
61 "mail_accounts_failing": ("app-mail-sync", "objects/system/mail_sync_attention.py", SECOND),
62}
63
64VIEWERS = {
65 "admin": {"user_id": "ops", "roles": ["admin"]},
66 "manager": {"user_id": "meg", "roles": ["manager"]},
67 "ann": {"user_id": "ann"},
68 "bob": {"user_id": "bob"},
69 "nobody": {"user_id": "zed"},
70}
71
72
73def _git_show(before: str, path: str) -> str | None:
74 try:
75 return subprocess.run(["git", "show", f"{before}:{path}"], cwd=ROOT, check=True,
76 capture_output=True, text=True).stdout
77 except (subprocess.CalledProcessError, FileNotFoundError):
78 return None
79
80
81def _old_provider(package: str, path: str, before: str):
82 source = _git_show(before, f"packages/{package}/{path}")
83 if source is None:
84 pytest.skip(f"{before} is not in this checkout's history")
85 spec = importlib.util.spec_from_loader(f"old_{package}_{Path(path).stem}", loader=None)
86 module = importlib.util.module_from_spec(spec)
87 exec(compile(source, path, "exec"), module.__dict__)
88 return module
89
90
91def _old_manifest_entry(package: str, attention_id: str, before: str) -> dict:
92 source = _git_show(before, f"packages/{package}/dbbasic-package.json")
93 if source is None:
94 pytest.skip(f"{before} is not in this checkout's history")
95 manifest = json.loads(source)
96 return next(entry for entry in manifest["attention"] if entry["id"] == attention_id)
97
98
99def _closure(names):
100 ordered = []
101
102 def visit(name):
103 if name in ordered:
104 return
105 manifest = json.loads((PACKAGES_ROOT / name / "dbbasic-package.json").read_text())
106 for dep in manifest.get("dependencies", []):
107 visit(dep if isinstance(dep, str) else dep["id"])
108 ordered.append(name)
109
110 for name in names:
111 visit(name)
112 return ordered
113
114
115def _ago(days=0, hours=0):
116 return (datetime.now(timezone.utc) - timedelta(days=days, hours=hours)).strftime(
117 "%Y-%m-%dT%H:%M:%SZ")
118
119
120def _day(days):
121 return (date.today() - timedelta(days=days)).isoformat()
122
123
124# Owners rotate through ann, bob and nobody-in-particular ("" -- an unowned
125# row only an admin or a collection grant reaches).
126OWNERS = ("ann", "bob", "", "ann")
127
128
129def _rows():
130 """{collection: [rows]}: waiting and not-waiting rows, every owner,
131 dates either side of each threshold, and the hand-edited cells the old
132 providers tolerated (an amount that will not parse, a blank date)."""
133 out = {}
134 out["expenses"] = [
135 {"status": status, "amount_cents": amount, "description": "x", "incurred_on": _day(1)}
136 for status, amount in (("submitted", "12345"), ("submitted", "99"),
137 ("submitted", "250000"), ("draft", "500"),
138 # 1, not 0: expenses now declare validation.min 1
139 ("approved", "700"), ("submitted", "1"))]
140 out["time_logs"] = [
141 {"status": status, "duration_seconds": seconds, "started_at": _ago(1)}
142 for status, seconds in (("submitted", "5400"), ("submitted", "1800"),
143 ("draft", "3600"), ("submitted", "17"), ("billed", "60"))]
144 out["backorders"] = [
145 {"status": status, "requested_on": requested, "product_id": "p1", "kind": "backorder"}
146 for status, requested in (("open", _day(21)), ("open", _day(0)), ("open", ""),
147 ("filled", _day(40)), ("open", _day(3)))]
148 out["disputes"] = [
149 {"status": status, "created_at": created, "kind": "shipment", "summary": "s"}
150 for status, created in (("open", _ago(15, 2)), ("open", _ago(0, 3)),
151 ("investigating", _ago(30)), ("open", _ago(4, 1)),
152 ("resolved", _ago(2)))]
153 out["scans"] = [
154 {"status": status, "created_at": created}
155 for status, created in (("extracted", _ago(8)), ("extracted", _ago(6, 20)),
156 ("pending", _ago(30)), ("extracted", _ago(12)),
157 ("confirmed", _ago(9)))]
158 out["shipments"] = [
159 {"direction": direction, "status": status, "created_at": created, "order_id": "o1"}
160 for direction, status, created in (
161 ("inbound", "received", _ago(9)), ("inbound", "received", _ago(2)),
162 ("outbound", "received", _ago(20)), ("inbound", "authorized", _ago(10)),
163 ("inbound", "received", _ago(7, 2)))]
164 # Parcels on the road, either side of the stuck threshold (the setting
165 # below says 7; the provider's default was 10), one with no handover
166 # date, one inbound and one merely shipped.
167 out["shipments"] += [
168 {"direction": direction, "status": status, "shipped_on": shipped, "order_id": "o1"}
169 for direction, status, shipped in (
170 ("outbound", "in_transit", _day(30)), ("outbound", "in_transit", _day(7)),
171 ("outbound", "in_transit", _day(6)), ("outbound", "in_transit", ""),
172 ("inbound", "in_transit", _day(20)), ("outbound", "shipped", _day(40)),
173 ("outbound", "in_transit", _day(12)), ("outbound", "in_transit", _day(8)))]
174 out["invoices"] = [
175 {"doc_type": doc_type, "status": status, "due_date": due, "number": f"INV-{index}",
176 "customer_name": "C"}
177 for index, (doc_type, status, due) in enumerate((
178 ("invoice", "sent", _day(10)), ("invoice", "overdue", _day(45)),
179 ("invoice", "paid", _day(30)), ("invoice", "draft", _day(60)),
180 ("quote", "sent", _day(20)), ("invoice", "partial", _day(1)),
181 ("invoice", "sent", _day(0)), ("invoice", "sent", ""),
182 ("credit_note", "sent", _day(5)), ("invoice", "void", _day(9)),
183 ("invoice", "overdue", _day(3)), ("invoice", "sent", _day(-4))))]
184 out["mail_accounts"] = [
185 {"enabled": enabled, "sync_attempts": attempts, "email_address": f"m{index}@x.test",
186 "host": "imap.x.test"}
187 for index, (enabled, attempts) in enumerate((
188 ("true", "3"), ("true", "7"), ("false", "4"), ("true", "2"),
189 ("true", "0"), ("", "3"), ("true", "3"), ("false", "9")))]
190 out["template_runs"] = [
191 {"status": status, "price_cents": price, "template_id": "t1", "handler": "h"}
192 for status, price in (("needs_review", "1250"), ("needs_review", "0"),
193 ("succeeded", "999"), ("needs_review", "100075"),
194 ("needs_review", ""))]
195 out["bank_lines"] = [
196 {"match_status": status, "posted_on": posted, "amount_cents": "100",
197 "bank_account_id": "va1",
198 # A matched line names its target (bank_lines.matched_to required_when).
199 "matched_to": "payments/p1" if status == "matched" else ""}
200 for status, posted in (("unmatched", _day(8)), ("", _day(30)), ("matched", _day(40)),
201 ("unmatched", _day(1)), ("suggested", _day(9)),
202 ("unmatched", _day(7)))]
203 for rows in out.values():
204 for index, row in enumerate(rows):
205 row["owner_id"] = OWNERS[index % len(OWNERS)]
206 return out
207
208
209PARENTS = [
210 ("products", {"id": "p1", "name": "Widget", "sku": "W-1"}),
211 ("orders", {"id": "o1", "number": "SO-1", "customer_name": "C"}),
212 ("value_accounts", {"id": "va1", "name": "Current account", "kind": "bank"}),
213 ("templates", {"id": "t1", "name": "A template", "body": "b"}),
214]
215
216
217@pytest.fixture(scope="module")
218def site(tmp_path_factory):
219 data = tmp_path_factory.mktemp("differential") / "data"
220 objects = data.parent / "objects"
221 objects.mkdir(parents=True)
222 # app-nav first: a package installed before the registry exists has its
223 # attention entries skipped, exactly as on a real box.
224 packages = ["app-nav", "app-settings"] + sorted(
225 {package for package, _, _ in MIGRATED.values()})
226 for package in _closure(packages):
227 object_packages.install_package(
228 package, root=PACKAGES_ROOT, base_dir=data, object_roots=[objects])
229 def present(collection):
230 return (data / "schemas" / f"{collection}.json").is_file()
231
232 # The parents the rows' relations must resolve to, then the rows, for
233 # whichever of the counted collections the installed packages ship.
234 for collection, row in PARENTS:
235 if present(collection):
236 object_records.create_collection_record(
237 collection, row, base_dir=data, preserve_read_only=True)
238 for collection, rows in _rows().items():
239 if not present(collection):
240 continue
241 for row in rows:
242 # roots: expenses declares a locked check (app-finance 0.19.0),
243 # and the record layer finds its object where it was installed.
244 object_records.create_collection_record(
245 collection, row, base_dir=data, preserve_read_only=True, roots=[objects])
246 object_records.create_collection_record(
247 "app_settings", {"id": "stuck", "key": "carrier.stuck_days", "value": "7"}, base_dir=data)
248 return data
249
250
251def _old_answer(module, data, identity, monkeypatch):
252 """The deleted provider's COUNT, shown only what `identity` may read.
253
254 Except app_settings: a threshold is the box's configuration, the same
255 for every viewer, and not one of the rows being counted. (A member may
256 not read app_settings; filtering it would have the old provider judge
257 their parcels against the default while the box says otherwise.)"""
258 access = object_access.Access(identity, base_dir=data)
259 real = object_records.read_collection_records
260
261 def visible_only(collection, **kwargs):
262 rows = real(collection, **kwargs)
263 return rows if collection == "app_settings" else access.visible(collection, rows)
264
265 with monkeypatch.context() as patch:
266 patch.setenv("DBBASIC_DATA_DIR", str(data))
267 patch.setattr(object_records, "read_collection_records", visible_only)
268 answer = module.COUNT({})
269 return {"count": answer["count"], "detail": answer.get("detail", "")}
270
271
272def _new_rows(data, identity):
273 return {row["id"]: row for row in object_attention.rows_for(identity, base_dir=data)}
274
275
276def test_every_migrated_queue_is_now_a_declaration_and_its_provider_is_gone():
277 for attention_id, (package, path, _before) in MIGRATED.items():
278 manifest = json.loads((PACKAGES_ROOT / package / "dbbasic-package.json").read_text())
279 entry = next(e for e in manifest["attention"] if e["id"] == attention_id)
280 assert "object_id" not in entry and entry["collection"], attention_id
281 assert not (PACKAGES_ROOT / package / path).exists(), path
282 assert all(o["path"] != path for o in manifest["objects"]), path
283
284
285@pytest.mark.parametrize("attention_id", sorted(MIGRATED))
286def test_label_link_door_group_and_severity_are_unchanged(site, attention_id):
287 package, _, before = MIGRATED[attention_id]
288 old = _old_manifest_entry(package, attention_id, before)
289 row = object_records.get_collection_record("attention_sources", attention_id, base_dir=site)
290 for field in ("label", "path", "nav_id", "group", "severity"):
291 assert row[field] == (old.get(field) or {"group": "Apps", "severity": "normal"}.get(field, "")), field
292 shown = _new_rows(site, VIEWERS["admin"])[attention_id]
293 for field in ("label", "path", "nav_id", "group", "severity"):
294 assert shown[field] == row[field]
295
296
297@pytest.mark.parametrize("viewer", sorted(VIEWERS))
298@pytest.mark.parametrize("attention_id", sorted(MIGRATED))
299def test_the_declared_count_is_the_old_providers_over_what_the_viewer_may_read(
300 site, attention_id, viewer, monkeypatch):
301 package, path, before = MIGRATED[attention_id]
302 identity = VIEWERS[viewer]
303 old = _old_answer(_old_provider(package, path, before), site, identity, monkeypatch)
304 new = _new_rows(site, identity)[attention_id]
305 assert (int(new["count"]), new["detail"]) == (old["count"], old["detail"])
306
307
308@pytest.mark.parametrize("attention_id", sorted(MIGRATED))
309def test_an_admin_sees_exactly_the_number_the_provider_used_to_report(
310 site, attention_id, monkeypatch):
311 package, path, before = MIGRATED[attention_id]
312 with monkeypatch.context() as patch:
313 patch.setenv("DBBASIC_DATA_DIR", str(site))
314 old = _old_provider(package, path, before).COUNT({})
315 new = _new_rows(site, VIEWERS["admin"])[attention_id]
316 assert old["count"] > 0, "the seed must give every queue something to count"
317 assert (int(new["count"]), new["detail"]) == (old["count"], old.get("detail", ""))
318
319
320def test_enforcement_changes_no_shipped_count_for_a_viewer_who_reads_everything(
321 site, monkeypatch):
322 """With enforcement on a count is taken over the fields the viewer may
323 read (tests/test_attention_hidden_fields.py). An admin reads every field
324 of every shipped collection, so every shipped queue -- count and
325 sentence -- is what it is with enforcement off."""
326 def shown():
327 return {key: (row["count"], row["detail"])
328 for key, row in _new_rows(site, VIEWERS["admin"]).items()}
329
330 monkeypatch.delenv(object_access.PERMISSION_ENFORCEMENT_ENV, raising=False)
331 off = shown()
332 monkeypatch.setenv(object_access.PERMISSION_ENFORCEMENT_ENV, "true")
333 on = shown()
334 assert set(MIGRATED) <= set(on)
335 assert all(int(on[attention_id][0]) > 0 for attention_id in MIGRATED)
336 assert on == off
337
338
339@pytest.mark.parametrize("attention_id", sorted(MIGRATED))
340def test_the_intended_difference_a_user_with_no_grant_no_longer_sees_the_queue(
341 site, attention_id, monkeypatch):
342 """Before: computed with no viewer, shown to every signed-in user. After:
343 the rows this user may read, which is none."""
344 package, path, before = MIGRATED[attention_id]
345 with monkeypatch.context() as patch:
346 patch.setenv("DBBASIC_DATA_DIR", str(site))
347 old = _old_provider(package, path, before).COUNT({})
348 assert old["count"] > 0
349 assert _new_rows(site, VIEWERS["nobody"])[attention_id]["count"] == "0"
350
351
352def _nav_entries(site, monkeypatch):
353 spec = importlib.util.spec_from_file_location(
354 "nav_entries_under_test", PACKAGES_ROOT / "app-nav" / "objects" / "action" / "nav_entries.py")
355 module = importlib.util.module_from_spec(spec)
356 spec.loader.exec_module(module)
357 monkeypatch.setenv("DBBASIC_DATA_DIR", str(site))
358 return module
359
360
361def test_the_menu_shows_an_admin_every_queue_and_a_member_only_their_own(site, monkeypatch):
362 nav = _nav_entries(site, monkeypatch)
363 admin = {row["id"]: row for row in nav.POST({"_identity": VIEWERS["admin"]})["attention"]}
364 assert set(MIGRATED) <= set(admin)
365 nobody = {row["id"] for row in nav.POST({"_identity": VIEWERS["nobody"]})["attention"]}
366 assert not nobody & set(MIGRATED)
367 ann = {row["id"]: row for row in nav.POST({"_identity": VIEWERS["ann"]})["attention"]}
368 assert ann["expenses_to_approve"]["count"] < admin["expenses_to_approve"]["count"]
369 assert nav.POST({"_identity": {}})["attention"] == []
370
371
372# The providers that stay code (orders_to_pick, products_to_reorder, ... --
373# docs/package-authoring.md says why) still compute one number over every
374# row. The intended difference for them: it reaches only viewers who may
375# read all of those rows, which on the shipped rules is admins.
376STAYED_CODE = ("orders_to_pick", "products_to_reorder")
377
378
379def test_a_providers_global_number_reaches_only_viewers_who_read_every_row(site, monkeypatch):
380 for source_id in STAYED_CODE:
381 source = object_records.get_collection_record("attention_sources", source_id, base_dir=site)
382 assert json.loads(source["reads"]), source_id
383 object_records.create_collection_record("attention_counts", {
384 "id": source_id, "source_id": source_id, "label": source["label"],
385 "path": source["path"], "count": "3", "detail": "everybody's"}, base_dir=site)
386 try:
387 nav = _nav_entries(site, monkeypatch)
388 shown = {viewer: {row["id"] for row in nav.POST({"_identity": identity})["attention"]}
389 for viewer, identity in VIEWERS.items()}
390 assert set(STAYED_CODE) <= shown["admin"]
391 for viewer in ("manager", "ann", "bob", "nobody"):
392 assert not set(STAYED_CODE) & shown[viewer], viewer
393 finally:
394 for source_id in STAYED_CODE:
395 object_records.delete_collection_record("attention_counts", source_id, base_dir=site)