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_handlers.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_handlers.py · 8.9 KB · 271 lines
1import json
2
3import pytest
4
5import object_handlers
6import object_server
7import object_state
8
9
10@pytest.fixture(autouse=True)
11def _reset_handler_index():
12 object_handlers.invalidate()
13 yield
14 object_handlers.invalidate()
15
16
17def write_source(path, content):
18 path.parent.mkdir(parents=True, exist_ok=True)
19 path.write_text(content)
20 return path
21
22
23# --- extract_handles -------------------------------------------------------
24
25
26def test_extract_handles_reads_list_literal():
27 code = 'HANDLES = ["notes.record.created", "notes.record.updated"]\n'
28 assert object_handlers.extract_handles(code) == [
29 "notes.record.created",
30 "notes.record.updated",
31 ]
32
33
34def test_extract_handles_reads_tuple_literal():
35 code = 'HANDLES = ("notes.record.created",)\n'
36 assert object_handlers.extract_handles(code) == ["notes.record.created"]
37
38
39def test_extract_handles_ignores_non_string_entries():
40 code = 'HANDLES = ["notes.record.created", 1, None, "notes.record.deleted"]\n'
41 assert object_handlers.extract_handles(code) == [
42 "notes.record.created",
43 "notes.record.deleted",
44 ]
45
46
47def test_extract_handles_absent_returns_empty():
48 code = "def GET(request):\n return {}\n"
49 assert object_handlers.extract_handles(code) == []
50
51
52def test_extract_handles_syntax_error_returns_empty():
53 code = "def GET(request:\n return {}\n"
54 assert object_handlers.extract_handles(code) == []
55
56
57def test_extract_handles_non_literal_returns_empty():
58 code = "HANDLES = some_function_call()\n"
59 assert object_handlers.extract_handles(code) == []
60
61
62def test_extract_handles_non_list_value_returns_empty():
63 code = 'HANDLES = "notes.record.created"\n'
64 assert object_handlers.extract_handles(code) == []
65
66
67# --- event_name --------------------------------------------------------
68
69
70def test_event_name_maps_actions_to_present_tense_events():
71 assert object_handlers.event_name("notes", "create") == "notes.record.created"
72 assert object_handlers.event_name("notes", "update") == "notes.record.updated"
73 assert object_handlers.event_name("notes", "delete") == "notes.record.deleted"
74
75
76def test_event_name_returns_none_for_unknown_action():
77 assert object_handlers.event_name("notes", "archive") is None
78
79
80def test_event_name_returns_none_for_empty_collection():
81 assert object_handlers.event_name("", "create") is None
82
83
84# --- build_index / get_handlers / invalidate --------------------------
85
86
87def test_build_index_indexes_system_objects_by_declared_event(tmp_path):
88 root = tmp_path / "objects"
89 write_source(
90 root / "notes" / "handler.py",
91 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n return {}\n',
92 )
93
94 index = object_handlers.build_index([root])
95
96 assert index == {"notes.record.created": ["notes_handler"]}
97
98
99def test_build_index_skips_user_objects(tmp_path):
100 root = tmp_path / "objects"
101 write_source(
102 root / "users" / "42" / "handler.py",
103 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n return {}\n',
104 )
105
106 index = object_handlers.build_index([root])
107
108 assert index == {}
109
110
111def test_build_index_multiple_handlers_sorted_for_same_event(tmp_path):
112 root = tmp_path / "objects"
113 write_source(
114 root / "notes" / "a_handler.py",
115 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n return {}\n',
116 )
117 write_source(
118 root / "notes" / "b_handler.py",
119 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n return {}\n',
120 )
121
122 index = object_handlers.build_index([root])
123
124 assert index["notes.record.created"] == ["notes_a_handler", "notes_b_handler"]
125
126
127def test_get_handlers_builds_and_caches_index(tmp_path):
128 root = tmp_path / "objects"
129 write_source(
130 root / "notes" / "handler.py",
131 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n return {}\n',
132 )
133
134 assert object_handlers.get_handlers("notes.record.created", [root]) == ["notes_handler"]
135 assert object_handlers.get_handlers("notes.record.updated", [root]) == []
136
137 # A second handler added after the first get_handlers() call is not
138 # picked up until invalidate() forces a rebuild.
139 write_source(
140 root / "notes" / "second.py",
141 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n return {}\n',
142 )
143 assert object_handlers.get_handlers("notes.record.created", [root]) == ["notes_handler"]
144
145 object_handlers.invalidate()
146 assert object_handlers.get_handlers("notes.record.created", [root]) == [
147 "notes_handler",
148 "notes_second",
149 ]
150
151
152# --- reentry guard ------------------------------------------------------
153
154
155def test_dispatch_guard_tracks_depth():
156 assert object_handlers.current_depth() == 0
157 with object_handlers.dispatch_guard():
158 assert object_handlers.current_depth() == 1
159 with object_handlers.dispatch_guard():
160 assert object_handlers.current_depth() == 2
161 assert object_handlers.current_depth() == 1
162 assert object_handlers.current_depth() == 0
163
164
165def test_dispatch_guard_can_reach_max_depth():
166 depths = []
167 guards = []
168 try:
169 for _ in range(object_handlers.MAX_DISPATCH_DEPTH):
170 guard = object_handlers.dispatch_guard()
171 guard.__enter__()
172 guards.append(guard)
173 depths.append(object_handlers.current_depth())
174 finally:
175 for guard in reversed(guards):
176 guard.__exit__(None, None, None)
177
178 assert depths == list(range(1, object_handlers.MAX_DISPATCH_DEPTH + 1))
179 assert object_handlers.current_depth() == 0
180
181
182# --- dispatch integration (direct call) --------------------------------
183
184
185HANDLER_SOURCE = (
186 'HANDLES = ["notes.record.created"]\n\n'
187 "import json\n\n\n"
188 "def EVENT(request):\n"
189 " _state_manager.set('last_event', json.dumps(request))\n"
190 " return {'status': 'ok'}\n"
191)
192
193RAISING_HANDLER_SOURCE = (
194 'HANDLES = ["notes.record.created"]\n\n\n'
195 "def EVENT(request):\n"
196 " raise RuntimeError('boom')\n"
197)
198
199
200def test_dispatch_event_handlers_fires_matching_handler(tmp_path, monkeypatch):
201 objects_root = tmp_path / "objects"
202 data_dir = tmp_path / "data"
203 write_source(objects_root / "notes" / "handler.py", HANDLER_SOURCE)
204
205 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
206 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
207 monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true")
208
209 object_server._dispatch_event_handlers("notes", "n1", "create", {"id": "n1"})
210
211 state = object_state.ObjectStateManager("notes_handler", base_dir=str(data_dir))
212 assert json.loads(state.get("last_event")) == {
213 "event": "notes.record.created",
214 "collection": "notes",
215 "record_id": "n1",
216 "action": "create",
217 }
218
219
220def test_dispatch_event_handlers_is_noop_when_disabled(tmp_path, monkeypatch):
221 objects_root = tmp_path / "objects"
222 data_dir = tmp_path / "data"
223 write_source(objects_root / "notes" / "handler.py", HANDLER_SOURCE)
224
225 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
226 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
227 monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV, raising=False)
228
229 object_server._dispatch_event_handlers("notes", "n1", "create", {"id": "n1"})
230
231 state = object_state.ObjectStateManager("notes_handler", base_dir=str(data_dir))
232 assert state.get("last_event") is None
233
234
235def test_dispatch_event_handlers_swallows_handler_exceptions(tmp_path, monkeypatch):
236 objects_root = tmp_path / "objects"
237 data_dir = tmp_path / "data"
238 write_source(objects_root / "notes" / "handler.py", RAISING_HANDLER_SOURCE)
239
240 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
241 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
242 monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true")
243
244 # Must not raise, even though the only handler for this event blows up.
245 object_server._dispatch_event_handlers("notes", "n1", "create", {"id": "n1"})
246
247
248def test_dispatch_event_handlers_respects_max_depth(tmp_path, monkeypatch):
249 objects_root = tmp_path / "objects"
250 data_dir = tmp_path / "data"
251 write_source(objects_root / "notes" / "handler.py", HANDLER_SOURCE)
252
253 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
254 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
255 monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true")
256
257 guards = []
258 try:
259 for _ in range(object_handlers.MAX_DISPATCH_DEPTH):
260 guard = object_handlers.dispatch_guard()
261 guard.__enter__()
262 guards.append(guard)
263
264 # At max depth, dispatch must skip rather than recurse further.
265 object_server._dispatch_event_handlers("notes", "n1", "create", {"id": "n1"})
266 finally:
267 for guard in reversed(guards):
268 guard.__exit__(None, None, None)
269
270 state = object_state.ObjectStateManager("notes_handler", base_dir=str(data_dir))
271 assert state.get("last_event") is None