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