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_timers_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, 19 minutes ago History
test_app_timers_package.py · 17.7 KB · 485 lines
1"""Behavior tests for packages/app-timers: 62 -- Timer.
2
3Covers packages/app-timers/objects/site/timer_actions.py's server-enforced
4start/stop over time_logs (single-running-timer-per-owner invariant, derived
5duration_seconds, owner scoping, the 409/403 error shapes, the
6timers_enabled kill switch) plus the MCP tool_route mapping for
7start_timer/stop_timer/get_running_timer (mirrors
8tests/test_object_concurrency.py's update_record tool_route tests).
9
10Structural/manifest/schema/permission shape isn't split into its own file
11here (unlike e.g. test_app_catalog_package.py) since this package is small
12enough that behavior and shape fit in one file without getting unwieldy.
13"""
14
15import json
16from datetime import datetime, timedelta, timezone
17from pathlib import Path
18
19import pytest
20
21import object_execution
22import object_mcp
23import object_packages
24import object_records
25import python_object_runtime
26
27PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
28OBJECT_ID = "site_timer_actions"
29
30
31def _install(tmp_path):
32 """Install app-timers into an isolated data dir/object root and return
33 (data_dir, object_root, runtime). Mirrors tests/test_app_orders_totals.py.
34 """
35 import os
36
37 data_dir = tmp_path / "data"
38 object_root = tmp_path / "objects"
39 object_root.mkdir()
40 os.environ["DBBASIC_DATA_DIR"] = str(data_dir)
41
42 object_packages.install_package(
43 "app-timers", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root]
44 )
45 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
46 return data_dir, object_root, runtime
47
48
49def _call(runtime, object_root, method, payload):
50 """Execute site_timer_actions and return (http_status, body_dict)."""
51 result = object_execution.execute_object(
52 runtime,
53 object_execution.ObjectExecutionRequest(OBJECT_ID, method=method, payload=payload),
54 roots=[object_root],
55 )
56 assert result.ok is True, result.error
57 response = result.result
58 status = response.get("status", 200)
59 body = json.loads(response["body"])
60 return status, body
61
62
63def _identity(user_id):
64 return {"_identity": {"user_id": user_id}}
65
66
67def _start(runtime, object_root, user_id, **fields):
68 payload = {"action": "start", **_identity(user_id), **fields}
69 return _call(runtime, object_root, "POST", payload)
70
71
72def _stop(runtime, object_root, user_id, **fields):
73 payload = {"action": "stop", **_identity(user_id), **fields}
74 return _call(runtime, object_root, "POST", payload)
75
76
77def _running(runtime, object_root, user_id):
78 payload = {"action": "running", **_identity(user_id)}
79 return _call(runtime, object_root, "GET", payload)
80
81
82def _write_feature_flag(data_dir, flag, value):
83 path = data_dir / "collections" / "feature_flags" / "records.tsv"
84 path.parent.mkdir(parents=True, exist_ok=True)
85 path.write_text(f"id\tflag\tvalue\nff1\t{flag}\t{value}\n")
86
87
88def _write_task(data_dir, *task_ids):
89 # app-tasks isn't installed in this package's own tests (app-timers'
90 # "dependencies": ["app-tasks"] is informational metadata, not an
91 # install-time requirement -- see object_packages.install_package).
92 # A raw records.tsv is enough to satisfy time_logs.task_id's relation
93 # existence check without pulling in the whole tasks schema.
94 #
95 # Owned by u1, the caller these tests start timers as: time_logs.task_id
96 # declares relation.requires read, and start asks it (object_access), so
97 # a timer points only at a task its owner may read.
98 path = data_dir / "collections" / "tasks" / "records.tsv"
99 path.parent.mkdir(parents=True, exist_ok=True)
100 rows = "\n".join(f"{task_id}\tTest Task\tu1" for task_id in task_ids)
101 path.write_text(f"id\ttitle\towner_id\n{rows}\n")
102
103
104# ---------------------------------------------------------------------------
105# Single-running-timer invariant
106# ---------------------------------------------------------------------------
107
108
109def test_start_creates_a_running_row(tmp_path):
110 data_dir, object_root, runtime = _install(tmp_path)
111 _write_task(data_dir, "t1")
112
113 status, body = _start(runtime, object_root, "u1", task_id="t1", notes="working")
114
115 assert status == 200
116 row = body["time_log"]
117 assert row["owner_id"] == "u1"
118 assert row["task_id"] == "t1"
119 assert row["notes"] == "working"
120 assert row["is_running"] == "true"
121 assert row["ended_at"] == ""
122
123
124def test_starting_a_second_timer_auto_stops_the_first(tmp_path):
125 data_dir, object_root, runtime = _install(tmp_path)
126 _write_task(data_dir, "t1", "t2")
127
128 _, first = _start(runtime, object_root, "u1", task_id="t1")
129 _, second = _start(runtime, object_root, "u1", task_id="t2")
130
131 assert first["time_log"]["id"] != second["time_log"]["id"]
132
133 rows = object_records.read_collection_records("time_logs", base_dir=data_dir)
134 mine = [row for row in rows if row["owner_id"] == "u1"]
135 running = [row for row in mine if row["is_running"] == "true"]
136 assert len(running) == 1
137 assert running[0]["id"] == second["time_log"]["id"]
138
139 stopped = [row for row in mine if row["id"] == first["time_log"]["id"]][0]
140 assert stopped["is_running"] == "false"
141 assert stopped["ended_at"] != ""
142 assert int(stopped["duration_seconds"]) >= 0
143
144
145def test_only_one_running_row_per_owner_after_several_starts(tmp_path):
146 data_dir, object_root, runtime = _install(tmp_path)
147
148 for _ in range(5):
149 _start(runtime, object_root, "u1")
150
151 rows = object_records.read_collection_records("time_logs", base_dir=data_dir)
152 running = [row for row in rows if row["owner_id"] == "u1" and row["is_running"] == "true"]
153 assert len(running) == 1
154
155
156def test_two_owners_may_each_have_their_own_running_timer(tmp_path):
157 data_dir, object_root, runtime = _install(tmp_path)
158
159 _start(runtime, object_root, "u1")
160 _start(runtime, object_root, "u2")
161
162 rows = object_records.read_collection_records("time_logs", base_dir=data_dir)
163 running_ids = {row["owner_id"] for row in rows if row["is_running"] == "true"}
164 assert running_ids == {"u1", "u2"}
165
166
167# ---------------------------------------------------------------------------
168# Duration derivation -- floor(ended_at - started_at)
169# ---------------------------------------------------------------------------
170
171
172def test_duration_seconds_is_floor_of_the_interval(tmp_path):
173 data_dir, object_root, runtime = _install(tmp_path)
174
175 # started_at is 5.7 real seconds in the past; if the verb rounded
176 # instead of flooring, duration_seconds would come back 6, not 5.
177 # Test overhead between here and the stop call below is expected to
178 # stay well under the remaining 0.3s margin.
179 started = datetime.now(timezone.utc) - timedelta(seconds=5, milliseconds=700)
180 row = object_records.create_collection_record(
181 "time_logs",
182 {
183 "owner_id": "u1",
184 "started_at": started.isoformat().replace("+00:00", "Z"),
185 "ended_at": "",
186 "is_running": "true",
187 },
188 base_dir=data_dir,
189 actor="test",
190 )
191
192 status, body = _stop(runtime, object_root, "u1", time_log_id=row["id"])
193
194 assert status == 200
195 assert body["time_log"]["duration_seconds"] == "5"
196
197
198# ---------------------------------------------------------------------------
199# Owner scoping / error shapes
200# ---------------------------------------------------------------------------
201
202
203def test_stop_with_no_id_stops_whichever_timer_is_running(tmp_path):
204 data_dir, object_root, runtime = _install(tmp_path)
205 _write_task(data_dir, "t1")
206 _, started = _start(runtime, object_root, "u1", task_id="t1")
207
208 status, body = _stop(runtime, object_root, "u1")
209
210 assert status == 200
211 assert body["time_log"]["id"] == started["time_log"]["id"]
212 assert body["time_log"]["is_running"] == "false"
213
214
215def test_stop_with_no_running_timer_is_409(tmp_path):
216 data_dir, object_root, runtime = _install(tmp_path)
217
218 status, body = _stop(runtime, object_root, "u1")
219
220 assert status == 409
221 assert body["status"] == "error"
222
223
224def test_stop_someone_elses_timer_is_403(tmp_path):
225 data_dir, object_root, runtime = _install(tmp_path)
226 _, started = _start(runtime, object_root, "owner_a")
227
228 status, body = _stop(runtime, object_root, "owner_b", time_log_id=started["time_log"]["id"])
229
230 assert status == 403
231 assert body["status"] == "error"
232
233 # And owner_a's timer is still running -- the refused stop touched nothing.
234 row = object_records.get_collection_record(
235 "time_logs", started["time_log"]["id"], base_dir=data_dir
236 )
237 assert row["is_running"] == "true"
238
239
240def test_stop_an_already_stopped_named_timer_is_409(tmp_path):
241 data_dir, object_root, runtime = _install(tmp_path)
242 _, started = _start(runtime, object_root, "u1")
243 time_log_id = started["time_log"]["id"]
244 _stop(runtime, object_root, "u1", time_log_id=time_log_id)
245
246 status, body = _stop(runtime, object_root, "u1", time_log_id=time_log_id)
247
248 assert status == 409
249
250
251def test_stop_unknown_time_log_id_is_404(tmp_path):
252 data_dir, object_root, runtime = _install(tmp_path)
253
254 status, body = _stop(runtime, object_root, "u1", time_log_id="does-not-exist")
255
256 assert status == 404
257
258
259def test_anonymous_caller_is_401(tmp_path):
260 data_dir, object_root, runtime = _install(tmp_path)
261
262 status, body = _call(runtime, object_root, "POST", {"action": "start"})
263
264 assert status == 401
265
266
267# ---------------------------------------------------------------------------
268# GET /timers/running
269# ---------------------------------------------------------------------------
270
271
272def test_running_is_null_when_no_timer_running(tmp_path):
273 data_dir, object_root, runtime = _install(tmp_path)
274
275 status, body = _running(runtime, object_root, "u1")
276
277 assert status == 200
278 assert body["time_log"] is None
279
280
281def test_running_returns_the_callers_own_row_only(tmp_path):
282 data_dir, object_root, runtime = _install(tmp_path)
283 _start(runtime, object_root, "owner_a")
284 _, started_b = _start(runtime, object_root, "owner_b")
285
286 status, body = _running(runtime, object_root, "owner_b")
287
288 assert status == 200
289 assert body["time_log"]["id"] == started_b["time_log"]["id"]
290
291
292# ---------------------------------------------------------------------------
293# timers_enabled kill switch
294# ---------------------------------------------------------------------------
295
296
297def test_flag_off_blocks_start_stop_and_running(tmp_path):
298 data_dir, object_root, runtime = _install(tmp_path)
299 _write_feature_flag(data_dir, "timers_enabled", "off")
300
301 start_status, start_body = _start(runtime, object_root, "u1")
302 running_status, running_body = _running(runtime, object_root, "u1")
303
304 assert start_status == 400
305 assert start_body["error_code"] == "timers_disabled"
306 assert running_status == 400
307 assert running_body["error_code"] == "timers_disabled"
308
309 # time_logs itself is untouched -- still plain CRUD (Degradation).
310 row = object_records.create_collection_record(
311 "time_logs",
312 {"owner_id": "u1", "started_at": "2026-01-01T00:00:00Z", "is_running": "false"},
313 base_dir=data_dir,
314 actor="test",
315 )
316 assert row["owner_id"] == "u1"
317
318
319def test_flag_missing_defaults_on(tmp_path):
320 data_dir, object_root, runtime = _install(tmp_path)
321 # No feature_flags collection at all -- 62's Parameterization/Degradation:
322 # missing/unreadable resolves to "on", same as object_rollups'
323 # rollup_pass_enabled.
324 status, _body = _start(runtime, object_root, "u1")
325 assert status == 200
326
327
328def test_flag_present_but_blank_value_defaults_on(tmp_path):
329 data_dir, object_root, runtime = _install(tmp_path)
330 _write_feature_flag(data_dir, "timers_enabled", "")
331
332 status, _body = _start(runtime, object_root, "u1")
333 assert status == 200
334
335
336# ---------------------------------------------------------------------------
337# MCP tool_route -- thin wrappers over site_timer_actions' own routes
338# ---------------------------------------------------------------------------
339
340
341def test_mcp_start_timer_routes_to_timer_actions_execute():
342 method, path, query, body = object_mcp.tool_route(
343 "start_timer", {"task_id": "t1", "notes": "hi"}
344 )
345
346 assert method == "POST"
347 assert path == "/admin/objects/site_timer_actions/execute"
348 assert query == ""
349 payload = json.loads(body)
350 assert payload["method"] == "POST"
351 assert payload["payload"] == {"action": "start", "task_id": "t1", "notes": "hi"}
352
353
354def test_mcp_start_timer_omits_absent_optional_args():
355 method, path, query, body = object_mcp.tool_route("start_timer", {})
356
357 payload = json.loads(body)
358 assert payload["payload"] == {"action": "start"}
359
360
361def test_mcp_stop_timer_routes_to_timer_actions_execute():
362 method, path, query, body = object_mcp.tool_route("stop_timer", {"time_log_id": "tl1"})
363
364 assert method == "POST"
365 assert path == "/admin/objects/site_timer_actions/execute"
366 payload = json.loads(body)
367 assert payload["method"] == "POST"
368 assert payload["payload"] == {"action": "stop", "time_log_id": "tl1"}
369
370
371def test_mcp_stop_timer_without_id_omits_it():
372 method, path, query, body = object_mcp.tool_route("stop_timer", {})
373
374 payload = json.loads(body)
375 assert payload["payload"] == {"action": "stop"}
376
377
378def test_mcp_get_running_timer_routes_to_timer_actions_execute_as_get():
379 method, path, query, body = object_mcp.tool_route("get_running_timer", {})
380
381 assert method == "POST" # outer transport is always POST; inner method carries GET
382 assert path == "/admin/objects/site_timer_actions/execute"
383 payload = json.loads(body)
384 assert payload["method"] == "GET"
385 assert payload["payload"] == {"action": "running"}
386
387
388def test_mcp_start_timer_rejects_non_string_task_id():
389 with pytest.raises(ValueError):
390 object_mcp.tool_route("start_timer", {"task_id": 5})
391
392
393def test_mcp_tools_registered_in_catalog():
394 names = {tool["name"] for tool in object_mcp.TOOLS}
395 assert {"start_timer", "stop_timer", "get_running_timer"} <= names
396
397
398# --- 0.5.0: the approval queue finally has a page ----------------------------
399#
400# "No page object" was true and also meant no page. The attention count
401# pointed at /time-logs?status=submitted and nothing on the box answered
402# /time-logs at all, so the only surface that tells an approver a queue
403# exists linked into thin air. The rule survives the fix: what got added
404# is DATA -- a `views` record and a site_routes row -- not a page object.
405
406APP_TIMERS_DIR = PACKAGES_ROOT / "app-timers"
407
408
409def _timers_seed_rows(name):
410 import csv
411
412 with open(APP_TIMERS_DIR / "seed" / f"{name}.tsv", newline="") as handle:
413 return list(csv.DictReader(handle, delimiter="\t"))
414
415
416def test_the_index_is_a_seeded_view_not_a_new_page_object():
417 package = object_packages.get_package("app-timers", root=PACKAGES_ROOT)
418
419 # Still exactly one site object, and it is the start/stop route, not a list.
420 assert [entry["id"] for entry in package["objects"] if entry["id"].startswith("site_")] == [
421 "site_timer_actions"]
422 assert {entry["collection"] for entry in package["seed"]} >= {
423 "time_logs", "rate_cards", "views", "site_routes"}
424 # Seeding into app-views' shared `views` collection is a real install-order
425 # dependency, not a soft reference: without the schema the rows have nowhere
426 # to land.
427 assert "app-views" in {entry["id"] for entry in package["dependencies"]}
428
429
430def test_the_time_logs_index_lists_time_logs_and_promises_no_search_it_cannot_do():
431 rows = [row for row in _timers_seed_rows("views") if row["id"] == "view_time_logs"]
432 assert len(rows) == 1
433 view = rows[0]
434 assert view["route"] == "/time-logs"
435 blocks = json.loads(view["blocks"])
436 assert len(blocks) == 1
437 block = blocks[0]
438 assert block["kind"] == "list"
439 assert block["collection"] == "time_logs"
440 # time_logs declares no `search` fields, so a search box would query
441 # nothing and report nothing found -- a lie about the collection.
442 schema = json.loads((APP_TIMERS_DIR / "schemas" / "time_logs.json").read_text())
443 assert schema.get("search") is None
444 assert "search" not in block
445 # Retroactive logging is ordinary and the schema was always meant to be
446 # form-managed, so Add stays.
447 assert block["add"] is True
448 # No /time-logs/{id} permalink is seeded, so rows must not pretend to link.
449 assert block["link"] is False
450
451
452def test_the_index_route_points_at_the_generic_renderer():
453 rows = [row for row in _timers_seed_rows("site_routes")
454 if row["id"] == "route_time_logs_index"]
455 assert len(rows) == 1
456 assert rows[0]["pattern"] == "/time-logs"
457 assert rows[0]["object_id"] == "site_view_render"
458
459
460def test_the_seed_headers_match_their_schemas_field_order():
461 for name in ("time_logs", "rate_cards"):
462 schema = json.loads((APP_TIMERS_DIR / "schemas" / f"{name}.json").read_text())
463 header = (APP_TIMERS_DIR / "seed" / f"{name}.tsv").read_text().splitlines()[0]
464 assert header.split("\t") == [field["name"] for field in schema["fields"]]
465
466
467def test_the_package_now_declares_a_door_instead_of_opting_out():
468 manifest = json.loads((APP_TIMERS_DIR / "dbbasic-package.json").read_text())
469
470 # nav_optional was the reviewable claim "this app has no front page".
471 # It ships one now, so the claim is retired rather than left lying around.
472 assert "nav_optional" not in manifest
473 assert manifest["nav"] == [{
474 "id": "time_logs", "label": "Time", "path": "/time-logs",
475 "blurb": "Hours logged against tasks, and the ones waiting for an approver",
476 "surface": "member", "group": "Work", "order": 45}]
477
478
479def test_the_count_opens_the_page_it_counted_and_claims_no_filter():
480 manifest = json.loads((APP_TIMERS_DIR / "dbbasic-package.json").read_text())
481 source = manifest["attention"][0]
482
483 assert source["path"] == "/time-logs"
484 assert "?" not in source["path"] # nothing reads a query param into a filter
485 assert source["nav_id"] == "time_logs"