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_mail_sync_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_mail_sync_package.py · 7.2 KB · 155 lines
1"""packages/app-mail-sync: what it declares, and the lines it must not cross.
2
3The declarations are the product here as much as the code: a schedule that
4lives only on a running box vanishes with the box, a password field on a
5schema ends up in every backup, and a transport field on app-messaging's
6schemas is the scope creep app-messaging's own tests refuse. Each is held
7by a test, asserted on the manifest and schemas themselves.
8"""
9
10import json
11import re
12from pathlib import Path
13
14import object_mail
15import object_packages
16import object_permissions
17import object_schemas
18import object_state
19from package_pins import assert_includes_in_order
20
21PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
22PACKAGE_DIR = PACKAGES_ROOT / "app-mail-sync"
23COLLECTIONS = ("mail_accounts", "mail_sync_state", "mail_synced_messages")
24
25
26def _manifest():
27 return json.loads((PACKAGE_DIR / "dbbasic-package.json").read_text())
28
29
30def _schema(name):
31 return json.loads((PACKAGE_DIR / "schemas" / f"{name}.json").read_text())
32
33
34def _policy():
35 rules = json.loads((PACKAGE_DIR / "permissions" / "rules.json").read_text())["rules"]
36 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": rules})
37
38
39def test_the_manifest_normalizes_and_depends_on_app_messaging():
40 package = object_packages.get_package("app-mail-sync", root=PACKAGES_ROOT)
41 assert {s["collection"] for s in package["schemas"]} >= set(COLLECTIONS)
42 # 0.1.0 shipped system_mail_sync_attention; 0.2.0 declares that count.
43 assert {o["id"] for o in package["objects"]} >= {"system_mail_sync", "site_mail_accounts"}
44 assert {"id": "app-messaging", "version": None} in package["dependencies"]
45
46
47def test_the_sync_is_a_declared_schedule_so_a_rebuilt_box_keeps_it():
48 schedules = _manifest()["schedules"]
49 assert_includes_in_order([(s["id"], s["object_id"], s["schedule"]) for s in schedules], [
50 ("mail_sync_every_two_minutes", "system_mail_sync", "*/2 * * * *")])
51
52
53def test_failing_accounts_are_a_declared_attention_queue():
54 attention = _manifest()["attention"]
55 assert_includes_in_order([(a["id"], a["collection"], a["path"], a["severity"]) for a in attention], [
56 ("mail_accounts_failing", "mail_accounts", "/mail/accounts", "warning")])
57 assert "object_id" not in attention[0]
58
59
60def test_the_declared_threshold_is_object_mail_attention_after():
61 """The manifest cannot import a constant, so it states the number; this
62 is what keeps the two from drifting apart."""
63 [entry] = _manifest()["attention"]
64 assert entry["where"]["sync_attempts"] == {"op": "gte", "value": object_mail.ATTENTION_AFTER}
65 assert entry["detail"]["text"] == (
66 f"failed {object_mail.ATTENTION_AFTER} or more syncs in a row")
67
68
69def test_install_registers_schemas_objects_and_the_schedule(tmp_path):
70 data_dir = tmp_path / "data"
71 objects = tmp_path / "objects"
72 objects.mkdir()
73 for dependency in ("app-views", "app-messaging"):
74 object_packages.install_package(dependency, root=PACKAGES_ROOT, base_dir=data_dir,
75 object_roots=[objects])
76 plan = object_packages.dry_run_package("app-mail-sync", root=PACKAGES_ROOT,
77 base_dir=data_dir, object_roots=[objects])
78 assert plan["safe_to_install"] is True, plan
79 object_packages.install_package("app-mail-sync", root=PACKAGES_ROOT, base_dir=data_dir,
80 object_roots=[objects])
81 for name in COLLECTIONS:
82 assert object_schemas.get_schema(name, base_dir=data_dir)["name"] == name
83 assert (objects / "system" / "mail_sync.py").is_file()
84 assert (objects / "site" / "mail_accounts.py").is_file()
85 state = object_state.get_object_state("scheduler", base_dir=data_dir)
86 task = json.loads(state["task_mail_sync_every_two_minutes"])
87 assert task["object_id"] == "system_mail_sync" and task["status"] == "active"
88
89
90def test_no_schema_has_a_field_that_could_hold_a_secret():
91 """The password lives in the owner's write-only vault. A field here
92 would put it in exports, backups and every API read."""
93 for name in COLLECTIONS:
94 fields = {f["name"] for f in _schema(name)["fields"]}
95 assert not {f for f in fields if re.search(r"pass|secret|token|credential|api_key", f)}, name
96
97
98def test_sync_rows_are_append_and_the_cursor_is_classic():
99 assert _schema("mail_synced_messages").get("storage") == "append"
100 assert "storage" not in _schema("mail_sync_state")
101
102
103def test_seeds_are_header_only_and_match_the_schemas():
104 for name in COLLECTIONS:
105 lines = (PACKAGE_DIR / "seed" / f"{name}.tsv").read_text().splitlines()
106 assert lines == ["\t".join(f["name"] for f in _schema(name)["fields"])]
107
108
109def test_the_transport_facts_live_here_not_on_app_messaging():
110 """app-messaging's schemas stay a mailbox; its own test bans imap_uid
111 and friends there. This package is where they go instead."""
112 fields = {f["name"] for f in _schema("mail_synced_messages")["fields"]}
113 assert {"account_id", "folder", "uid", "message_id", "dedupe_key", "references",
114 "list_unsubscribe", "list_unsubscribe_post", "list_id", "precedence"} <= fields
115 for schema_path in (PACKAGES_ROOT / "app-messaging" / "schemas").glob("*.json"):
116 names = {f["name"] for f in json.loads(schema_path.read_text())["fields"]}
117 assert not names & {"uid", "folder", "account_id", "dedupe_key", "list_unsubscribe"}
118
119
120def test_each_person_sees_only_their_own_accounts_and_sync_rows():
121 policy = _policy()
122 me = object_permissions.PermissionSubject(user_id="7")
123 other = object_permissions.PermissionSubject(user_id="8")
124 for name in COLLECTIONS:
125 mine = {"owner_id": "7", "account_id": "a1", "message_id": "m1"}
126 assert object_permissions.check_permission(
127 me, object_permissions.READ, policy=policy, collection=name, record=mine).allowed
128 assert not object_permissions.check_permission(
129 other, object_permissions.READ, policy=policy, collection=name, record=mine).allowed
130 assert not object_permissions.check_permission(
131 None, object_permissions.READ, policy=policy, collection=name, record=mine).allowed
132
133
134def test_only_the_sync_writes_the_cursor_and_the_transport_rows():
135 """A hand-edited cursor skips or repeats mail."""
136 policy = _policy()
137 me = object_permissions.PermissionSubject(user_id="7")
138 for name in ("mail_sync_state", "mail_synced_messages"):
139 for action in (object_permissions.CREATE, object_permissions.UPDATE,
140 object_permissions.DELETE):
141 assert not object_permissions.check_permission(
142 me, action, policy=policy, collection=name,
143 record={"owner_id": "7"}).allowed, (name, action)
144 assert object_permissions.check_permission(
145 me, object_permissions.UPDATE, policy=policy, collection="mail_accounts",
146 record={"owner_id": "7"}).allowed
147
148
149def test_no_internal_names_leak_into_the_package():
150 banned = re.compile("|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots"]), re.IGNORECASE)
151 for path in PACKAGE_DIR.rglob("*"):
152 if "__pycache__" in path.parts:
153 continue # compiled bytes can match a name by chance
154 if path.is_file():
155 assert not banned.search(path.read_text(errors="ignore")), path