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_object_schedule.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_object_schedule.py · 11.5 KB · 297 lines
1"""``_schedule`` / ``_unschedule``: objects keep themselves fresh (object_schedule).
2
3Objects ported from the askrobots server (weather and RSS caches, a scan
4processor) schedule their own methods. Without these helpers they load,
5answer once and never refresh again -- silently, because every one of
6them guards with ``if not _schedule: return``. These tests pin that the
7helpers exist in every execution mode, write exactly one daemon task per
8(object, method), and that the daemon then actually runs the method.
9"""
10from __future__ import annotations
11
12import json
13import textwrap
14
15import pytest
16
17import object_daemon
18import object_schedule
19import object_state
20from python_object_runtime import PythonObjectRuntime
21from runtime_modes import MODES, configure, run_object, write_object
22
23SCHEDULER_SOURCE = "def POST(request):\n return {'ok': True}\n"
24
25SELF_SCHEDULING = textwrap.dedent('''
26 _schedule = None
27 _unschedule = None
28
29 def tick():
30 _state_manager.increment("ticks")
31 return {"ticked": True}
32
33 def GET(request):
34 return {"scheduled": _schedule(request.get("every", 30), request.get("method", "tick"))["id"]}
35
36 def DELETE(request):
37 return {"removed": _unschedule(request.get("method"))}
38''')
39
40
41def tasks(data_dir):
42 state = object_state.get_object_state("scheduler", data_dir)
43 return {key: json.loads(value) for key, value in state.items() if key.startswith("task_")}
44
45
46def install_scheduler(root):
47 (root / "triggers").mkdir(parents=True, exist_ok=True)
48 (root / "triggers" / "scheduler.py").write_text(SCHEDULER_SOURCE)
49
50
51def make_due(data_dir, key):
52 manager = object_state.ObjectStateManager("scheduler", base_dir=data_dir)
53 row = json.loads(manager.get(key))
54 row["next_run"] = 1
55 manager.set(key, json.dumps(row))
56
57
58def tick(data_dir):
59 object_daemon.process_scheduler(PythonObjectRuntime())
60
61
62@pytest.mark.parametrize("mode", MODES)
63def test_schedule_writes_one_task_and_reschedule_updates_it_in_every_mode(mode, tmp_path, monkeypatch):
64 data_dir, root = configure(monkeypatch, tmp_path)
65 write_object(root, "tools_weather", SELF_SCHEDULING)
66
67 first = run_object(mode, root, "tools_weather", "GET", {"every": 30})
68 assert first.ok, first.error
69 again = run_object(mode, root, "tools_weather", "GET", {"every": 30})
70 assert again.ok, again.error
71 rows = tasks(data_dir)
72 assert list(rows) == ["task_obj.tools_weather.tick"]
73 row = rows["task_obj.tools_weather.tick"]
74 assert (row["kind"], row["type"], row["schedule"], row["method"]) == (
75 "object_method", "interval", "30", "tick")
76
77 run_object(mode, root, "tools_weather", "GET", {"every": 90})
78 rows = tasks(data_dir)
79 assert len(rows) == 1
80 assert rows["task_obj.tools_weather.tick"]["interval_seconds"] == 90
81
82
83@pytest.mark.parametrize("mode", MODES)
84def test_unschedule_one_method_or_all_in_every_mode(mode, tmp_path, monkeypatch):
85 data_dir, root = configure(monkeypatch, tmp_path)
86 write_object(root, "tools_weather", SELF_SCHEDULING + "\ndef refresh():\n return 1\n")
87 run_object(mode, root, "tools_weather", "GET", {"method": "tick"})
88 run_object(mode, root, "tools_weather", "GET", {"method": "refresh"})
89 assert len(tasks(data_dir)) == 2
90
91 removed = run_object(mode, root, "tools_weather", "DELETE", {"method": "tick"})
92 assert removed.result == {"removed": 1}
93 assert list(tasks(data_dir)) == ["task_obj.tools_weather.refresh"]
94
95 run_object(mode, root, "tools_weather", "GET", {"method": "tick"})
96 removed = run_object(mode, root, "tools_weather", "DELETE", {})
97 assert removed.result == {"removed": 2}
98 assert tasks(data_dir) == {}
99
100
101def test_rescheduling_the_same_interval_keeps_next_run(tmp_path, monkeypatch):
102 """Ported objects call _schedule on every GET in a fresh process; if that
103 pushed next_run forward each time, a busy object would never refresh."""
104 data_dir, root = configure(monkeypatch, tmp_path)
105 object_schedule.schedule("tools_weather", "tick", 30, base_dir=data_dir, now=1000)
106 object_schedule.schedule("tools_weather", "tick", 30, base_dir=data_dir, now=1020)
107 assert tasks(data_dir)["task_obj.tools_weather.tick"]["next_run"] == 1030
108 object_schedule.schedule("tools_weather", "tick", 60, base_dir=data_dir, now=1020)
109 assert tasks(data_dir)["task_obj.tools_weather.tick"]["next_run"] == 1080
110
111
112def test_registered_guard_pattern_sees_a_truthy_schedule(tmp_path, monkeypatch):
113 data_dir, root = configure(monkeypatch, tmp_path)
114 write_object(root, "tools_rss", textwrap.dedent('''
115 _schedule = None
116 _scheduler_registered = False
117
118 def _ensure_scheduler():
119 global _scheduler_registered
120 if _scheduler_registered or not _schedule:
121 return False
122 _schedule(1200, 'refresh')
123 _scheduler_registered = True
124 return True
125
126 def refresh():
127 return {}
128
129 def GET(request):
130 return {"registered": _ensure_scheduler()}
131 '''))
132 assert run_object("in_process", root, "tools_rss", "GET").result == {"registered": True}
133 assert list(tasks(data_dir)) == ["task_obj.tools_rss.refresh"]
134
135
136def test_system_object_minimum_interval_and_missing_method_are_refused(tmp_path, monkeypatch):
137 data_dir, root = configure(monkeypatch, tmp_path)
138 write_object(root, "tools_weather", SELF_SCHEDULING)
139 too_fast = run_object("in_process", root, "tools_weather", "GET", {"every": 1})
140 assert not too_fast.ok and "at least 5" in too_fast.error.message
141 missing = run_object("in_process", root, "tools_weather", "GET", {"method": "nope"})
142 assert not missing.ok and "no function 'nope'" in missing.error.message
143 private = run_object("in_process", root, "tools_weather", "GET", {"method": "_helper"})
144 assert not private.ok
145 assert tasks(data_dir) == {}
146
147 monkeypatch.setenv(object_schedule.MIN_INTERVAL_ENV, "1")
148 assert run_object("in_process", root, "tools_weather", "GET", {"every": 1}).ok
149
150
151def test_daemon_tick_runs_a_due_scheduled_method_once(tmp_path, monkeypatch):
152 data_dir, root = configure(monkeypatch, tmp_path)
153 install_scheduler(root)
154 write_object(root, "tools_weather", SELF_SCHEDULING)
155 run_object("in_process", root, "tools_weather", "GET", {"every": 30})
156 key = "task_obj.tools_weather.tick"
157
158 tick(data_dir) # not due yet
159 assert object_state.get_object_state("tools_weather", data_dir).get("ticks") is None
160
161 make_due(data_dir, key)
162 tick(data_dir)
163 tick(data_dir) # next_run moved 30s on: no second run
164 assert object_state.get_object_state("tools_weather", data_dir)["ticks"] == 1
165 row = tasks(data_dir)[key]
166 assert row["run_count"] == 1
167 assert row["next_run"] == row["last_run"] + 30
168
169
170def test_a_method_that_unschedules_itself_stays_unscheduled(tmp_path, monkeypatch):
171 """The daemon writes run bookkeeping back after the method returns; it
172 must not resurrect a row the method just deleted."""
173 data_dir, root = configure(monkeypatch, tmp_path)
174 install_scheduler(root)
175 write_object(root, "tools_once", textwrap.dedent('''
176 def finish():
177 _unschedule('finish')
178 return {}
179
180 def GET(request):
181 return _schedule(30, 'finish')
182 '''))
183 run_object("in_process", root, "tools_once", "GET")
184 make_due(data_dir, "task_obj.tools_once.finish")
185 tick(data_dir)
186 assert tasks(data_dir) == {}
187
188
189def test_daemon_skips_and_logs_a_task_whose_object_or_method_is_gone(tmp_path, monkeypatch, capsys):
190 data_dir, root = configure(monkeypatch, tmp_path)
191 install_scheduler(root)
192 object_daemon._REPORTED_GONE.clear()
193 path = write_object(root, "tools_weather", SELF_SCHEDULING + "\ndef refresh():\n return 1\n")
194 run_object("in_process", root, "tools_weather", "GET", {"method": "refresh"})
195 make_due(data_dir, "task_obj.tools_weather.refresh")
196 path.write_text(SELF_SCHEDULING) # refresh() removed
197 tick(data_dir)
198 out = capsys.readouterr().out
199 assert "tools_weather has no method 'refresh' any more; skipped" in out
200 row = tasks(data_dir)["task_obj.tools_weather.refresh"]
201 assert row["run_count"] == 0 and "skipped" in row["error"] and row["next_run"] > 1
202
203 object_schedule.schedule("tools_gone", "tick", 30, base_dir=data_dir)
204 make_due(data_dir, "task_obj.tools_gone.tick")
205 tick(data_dir)
206 assert "object tools_gone no longer exists; skipped" in capsys.readouterr().out
207
208
209def test_destroying_an_object_removes_its_scheduled_tasks(tmp_path, monkeypatch):
210 from test_destroy_object import destroy
211 from test_object_server import auth_headers, enable_source_writes, write_source
212
213 root = tmp_path / "objects"
214 data_dir = tmp_path / "data"
215 write_source(root / "tools" / "weather.py", SELF_SCHEDULING)
216 enable_source_writes(monkeypatch, root, data_dir)
217 object_schedule.schedule("tools_weather", "tick", 30, base_dir=data_dir)
218 object_schedule.schedule("tools_other", "tick", 30, base_dir=data_dir)
219
220 status, _, payload = destroy("tools_weather", headers=auth_headers())
221
222 assert status == 200 and payload["unscheduled"] == 1
223 assert list(tasks(data_dir)) == ["task_obj.tools_other.tick"]
224
225
226# A port of the askrobots examples/basics/ticker.py pattern, unchanged in
227# shape: module-level None placeholders the runtime overwrites, start()
228# schedules tick() which takes NO arguments, stop() unschedules it.
229TICKER = textwrap.dedent('''
230 import time
231
232 _logger = None
233 _state_manager = None
234 _schedule = None
235 _unschedule = None
236
237 def start(request=None):
238 interval = 5
239 if _state_manager:
240 _state_manager.set('ticks', 0)
241 _state_manager.set('running', True)
242 if _schedule:
243 _schedule(interval, 'tick')
244 return {'status': 'ok', 'interval': interval}
245
246 def tick():
247 if not _state_manager:
248 return
249 ticks = _state_manager.get('ticks', 0)
250 ticks += 1
251 _state_manager.set('ticks', ticks)
252 _state_manager.set('last_tick', time.time())
253 return {'ticks': ticks}
254
255 def stop(request=None):
256 if _unschedule:
257 _unschedule('tick')
258 if _state_manager:
259 _state_manager.set('running', False)
260 return {'status': 'ok'}
261
262 def POST(request):
263 action = request.get('action')
264 if action == 'start':
265 return start()
266 if action == 'stop':
267 return stop()
268 return {'status': 'error'}
269
270 def GET(request):
271 return {'ticks': _state_manager.get('ticks', 0), 'running': _state_manager.get('running', False)}
272''')
273
274
275def test_ported_ticker_ticks_on_schedule_in_a_daemon_pass(tmp_path, monkeypatch):
276 data_dir, root = configure(monkeypatch, tmp_path)
277 install_scheduler(root)
278 write_object(root, "basics_ticker", TICKER)
279
280 assert run_object("pool", root, "basics_ticker", "POST", {"action": "start"}).ok
281 key = "task_obj.basics_ticker.tick"
282 for _ in range(3):
283 make_due(data_dir, key)
284 tick(data_dir)
285 assert run_object("in_process", root, "basics_ticker", "GET").result["ticks"] == 3
286
287 assert run_object("spawn", root, "basics_ticker", "POST", {"action": "stop"}).ok
288 assert tasks(data_dir) == {}
289
290
291def test_http_cannot_call_a_lowercase_function_as_a_method(tmp_path, monkeypatch):
292 """Scheduling by function name must not open a door for HTTP: only the
293 daemon's named-method request reaches tick()."""
294 data_dir, root = configure(monkeypatch, tmp_path)
295 write_object(root, "basics_ticker", TICKER)
296 result = run_object("in_process", root, "basics_ticker", "tick")
297 assert not result.ok and result.error.type == "MethodNotSupportedError"