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_object_notify.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_object_notify.py · 11.9 KB · 230 lines
1"""12 notify: record-change events -> notifications, declaratively.
2
3Covers object_notify's pure logic (event-pattern grammar, transition-aware
4match, the four recipient modes, template rendering, suppress_self) and the
5daemon pass end-to-end (assign a task -> notify the assignee; idempotent;
6change-log-driven, no event-handler dependency).
7"""
8
9import json
10from pathlib import Path
11
12import object_daemon
13import object_identity
14import object_notify
15import object_packages
16import object_records
17
18PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
19
20
21# ---- event-pattern grammar ------------------------------------------------
22
23def test_event_pattern_wildcards_and_action_mapping():
24 m = object_notify.event_pattern_matches
25 assert m("tasks.record.updated", "tasks", "updated")
26 assert m("tasks.record.*", "tasks", "created")
27 assert m("*.record.created", "invoices", "created")
28 assert m("*.record.*", "anything", "deleted")
29 assert not m("tasks.record.updated", "tasks", "created")
30 assert not m("tasks.record.updated", "orders", "updated")
31 assert not m("tasks.record.updated", "tasks", "update") # present tense is not an event action
32 assert not m("garbage", "tasks", "updated")
33
34
35def test_change_action_present_tense_maps_to_event_action():
36 """The change log stores create/update/delete; the grammar uses -ed. The
37 engine maps one to the other so a `tasks.record.updated` rule fires on a
38 stored `update` change."""
39 rule = {"event_pattern": "tasks.record.updated", "recipients": json.dumps({"mode": "owner"}),
40 "channels": json.dumps([{"channel": "in_app", "body_template": "hi"}])}
41 change = {"collection": "tasks", "action": "update", "record_id": "t1",
42 "changed_fields": ["status"], "after": {"owner_id": "9", "status": "x"}, "actor": "u"}
43 notes = object_notify.notifications_for_change(rule, change, base_dir="/nonexistent")
44 assert len(notes) == 1 and notes[0]["user_id"] == "9"
45
46
47# ---- transition-aware match ----------------------------------------------
48
49def _rule(**over):
50 base = {"enabled": "true", "event_pattern": "tasks.record.updated",
51 "match": json.dumps({"status": "assigned"}),
52 "recipients": json.dumps({"mode": "field", "field": "assigned_to"}),
53 "suppress_self": "true",
54 "channels": json.dumps([{"channel": "in_app", "body_template": "You got {title}"}])}
55 base.update(over)
56 return base
57
58
59def test_match_fires_only_on_the_transition_not_later_edits():
60 rule = _rule()
61 # status became assigned in THIS write -> matches
62 transition = {"collection": "tasks", "action": "update", "record_id": "t1",
63 "changed_fields": ["status", "assigned_to"],
64 "after": {"status": "assigned", "assigned_to": "7", "title": "A"}, "actor": "1"}
65 assert len(object_notify.notifications_for_change(rule, transition, base_dir="/x")) == 1
66 # a later title edit on an already-assigned task -> status NOT in changed_fields -> no re-fire
67 later = {"collection": "tasks", "action": "update", "record_id": "t1",
68 "changed_fields": ["title"],
69 "after": {"status": "assigned", "assigned_to": "7", "title": "B"}, "actor": "1"}
70 assert object_notify.notifications_for_change(rule, later, base_dir="/x") == []
71
72
73def test_suppress_self_skips_the_actor_only():
74 # actor assigns themselves -> suppressed
75 self_assign = {"collection": "tasks", "action": "update", "record_id": "t1",
76 "changed_fields": ["status", "assigned_to"],
77 "after": {"status": "assigned", "assigned_to": "7", "title": "A"}, "actor": "7"}
78 assert object_notify.notifications_for_change(_rule(), self_assign, base_dir="/x") == []
79 # someone else assigns 7 -> not suppressed
80 other = dict(self_assign, actor="1")
81 assert len(object_notify.notifications_for_change(_rule(), other, base_dir="/x")) == 1
82
83
84def test_no_in_app_channel_writes_no_in_app_notification():
85 # email-only rule: no in_app notification record...
86 rule = _rule(channels=json.dumps([{"channel": "email", "subject_template": "s {title}", "body_template": "b"}]))
87 change = {"collection": "tasks", "action": "update", "record_id": "t1", "changed_fields": ["status"],
88 "after": {"status": "assigned", "assigned_to": "7", "title": "T"}, "actor": "1"}
89 assert object_notify.notifications_for_change(rule, change, base_dir="/x") == []
90 # ...but the email channel DOES produce an intent
91 intents = object_notify.email_intents_for_change(rule, change, base_dir="/x")
92 assert intents == [{"user_id": "7", "subject": "s T", "body": "b", "target": "tasks/t1"}]
93
94
95def test_email_intents_render_per_recipient_and_gate_on_match():
96 rule = _rule(channels=json.dumps([
97 {"channel": "in_app", "body_template": "in-app {title}"},
98 {"channel": "email", "subject_template": "Task: {title}", "body_template": "You got {title} ({urgency})"},
99 ]))
100 fires = {"collection": "tasks", "action": "update", "record_id": "t1",
101 "changed_fields": ["status", "assigned_to"],
102 "after": {"status": "assigned", "assigned_to": "7", "title": "Fix bug", "urgency": "high"}, "actor": "1"}
103 intents = object_notify.email_intents_for_change(rule, fires, base_dir="/x")
104 assert intents[0]["user_id"] == "7" and intents[0]["subject"] == "Task: Fix bug"
105 assert intents[0]["body"] == "You got Fix bug (high)"
106 # a later edit that no longer satisfies the transition doesn't re-fire email
107 later = {"collection": "tasks", "action": "update", "record_id": "t1", "changed_fields": ["title"],
108 "after": {"status": "assigned", "assigned_to": "7", "title": "renamed"}, "actor": "1"}
109 assert object_notify.email_intents_for_change(rule, later, base_dir="/x") == []
110
111
112def test_email_intents_empty_without_email_channel():
113 change = {"collection": "tasks", "action": "update", "record_id": "t1", "changed_fields": ["status", "assigned_to"],
114 "after": {"status": "assigned", "assigned_to": "7", "title": "T"}, "actor": "1"}
115 assert object_notify.email_intents_for_change(_rule(), change, base_dir="/x") == [] # _rule() is in_app only
116
117
118def test_recipient_modes_users_and_owner_and_field():
119 change = {"collection": "tasks", "action": "create", "record_id": "t1", "changed_fields": [],
120 "after": {"owner_id": "3", "assigned_to": "7"}, "actor": "z"}
121 ch = dict(event_pattern="tasks.record.created",
122 channels=json.dumps([{"channel": "in_app", "body_template": "x"}]), match="", suppress_self="false")
123 owner = object_notify.notifications_for_change(dict(ch, recipients=json.dumps({"mode": "owner"})), change, base_dir="/x")
124 assert owner[0]["user_id"] == "3"
125 field = object_notify.notifications_for_change(dict(ch, recipients=json.dumps({"mode": "field", "field": "assigned_to"})), change, base_dir="/x")
126 assert field[0]["user_id"] == "7"
127 users = object_notify.notifications_for_change(dict(ch, recipients=json.dumps({"mode": "users", "user_ids": ["a", "b"]})), change, base_dir="/x")
128 assert {n["user_id"] for n in users} == {"a", "b"}
129
130
131def test_template_renders_fields_missing_is_blank_not_error():
132 assert object_notify.render_template("You got {title} ({urgency})", {"title": "T", "urgency": "hi"}) == "You got T (hi)"
133 assert object_notify.render_template("due {due_date}", {}) == "due " # missing -> blank, no KeyError
134
135
136# ---- daemon pass end-to-end ----------------------------------------------
137
138def _install(tmp_path):
139 data_dir = tmp_path / "data"
140 object_root = tmp_path / "objects"
141 object_root.mkdir()
142 for pkg in ("app-tasks", "app-collab", "app-notify", "app-projects"):
143 object_packages.install_package(pkg, root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root], allow_replace=True)
144 return data_dir
145
146
147def _notes(data_dir):
148 return object_records.read_collection_records("notifications", base_dir=data_dir)
149
150
151def test_daemon_pass_notifies_on_assignment_and_is_idempotent(tmp_path):
152 data_dir = _install(tmp_path)
153 # first run stamps the cursor at "now" -> never backfills history
154 assert object_daemon.process_notifications(base_dir=data_dir) is None
155 assert _notes(data_dir) == []
156
157 t = object_records.create_collection_record(
158 "tasks", {"title": "Fix bug", "status": "open", "owner_id": "1", "urgency": "high", "due_date": "2026-02-01"},
159 base_dir=data_dir, actor="user:1")
160 object_records.update_collection_record("tasks", t["id"], {"status": "assigned", "assigned_to": "7"}, base_dir=data_dir, actor="user:1")
161
162 result = object_daemon.process_notifications(base_dir=data_dir)
163 assert result["notifications"] == 1
164 notes = _notes(data_dir)
165 assert notes[0]["user_id"] == "7"
166 assert notes[0]["kind"] == "notify"
167 assert notes[0]["target"] == f"tasks/{t['id']}"
168 assert "Fix bug" in notes[0]["body"] and "high" in notes[0]["body"]
169
170 # re-run: cursor has advanced past the change -> nothing new, no duplicate
171 assert object_daemon.process_notifications(base_dir=data_dir)["notifications"] == 0
172 assert len(_notes(data_dir)) == 1
173
174
175def _install_with_email(tmp_path):
176 data_dir = tmp_path / "data"
177 object_root = tmp_path / "objects"
178 object_root.mkdir()
179 for pkg in ("app-tasks", "app-collab", "app-notify", "app-projects", "app-email"):
180 object_packages.install_package(pkg, root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root], allow_replace=True)
181 return data_dir
182
183
184def test_daemon_queues_email_via_generic_outbox(tmp_path):
185 data_dir = _install_with_email(tmp_path)
186 dan = object_identity.create_user(
187 {"user_id": "usr_dan", "email": "dan@example.com", "display_name": "Dan"}, base_dir=data_dir)
188 object_daemon.process_notifications(base_dir=data_dir) # stamp cursor at now
189
190 t = object_records.create_collection_record(
191 "tasks", {"title": "Fix bug", "status": "open", "owner_id": "1", "urgency": "high", "due_date": "2026-02-01"},
192 base_dir=data_dir, actor="user:1")
193 object_records.update_collection_record(
194 "tasks", t["id"], {"status": "assigned", "assigned_to": dan["user_id"]}, base_dir=data_dir, actor="user:1")
195
196 result = object_daemon.process_notifications(base_dir=data_dir)
197 assert result["notifications"] == 1 and result["emails"] == 1
198 # the seeded rule's email channel enqueued into the GENERIC outbox
199 outbox = object_records.read_collection_records("email_outbox", base_dir=data_dir)
200 assert len(outbox) == 1
201 row = outbox[0]
202 assert row["to"] == "dan@example.com" and row["status"] == "queued"
203 assert "Fix bug" in row["subject"] and row["source_object_id"] == "notify"
204
205
206def test_daemon_skips_email_when_recipient_has_no_address(tmp_path):
207 data_dir = _install_with_email(tmp_path)
208 ghost = object_identity.create_user(
209 {"user_id": "usr_ghost", "display_name": "No Email"}, base_dir=data_dir) # no email
210 object_daemon.process_notifications(base_dir=data_dir)
211
212 t = object_records.create_collection_record(
213 "tasks", {"title": "T", "status": "open", "owner_id": "1"}, base_dir=data_dir, actor="user:1")
214 object_records.update_collection_record(
215 "tasks", t["id"], {"status": "assigned", "assigned_to": ghost["user_id"]}, base_dir=data_dir, actor="user:1")
216
217 result = object_daemon.process_notifications(base_dir=data_dir)
218 # in_app still fires; email is skipped (no deliverable address)
219 assert result["notifications"] == 1 and result["emails"] == 0
220 assert object_records.read_collection_records("email_outbox", base_dir=data_dir) == []
221
222
223def test_daemon_pass_returns_none_when_no_rules(tmp_path):
224 data_dir = tmp_path / "data"
225 object_root = tmp_path / "objects"
226 object_root.mkdir()
227 # app-collab (notifications) + app-tasks, but NOT app-notify -> no notify_rules
228 for pkg in ("app-tasks", "app-collab", "app-projects"):
229 object_packages.install_package(pkg, root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root], allow_replace=True)
230 assert object_daemon.process_notifications(base_dir=data_dir) is None