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.
test_locked_when.py · 24.1 KB · 523 lines
| 1 | """Schema `locked_when`: a record in a settled state is frozen. |
| 2 | |
| 3 | docs/logic-decisions.md #5 named this before it existed: "fields X are |
| 4 | locked when status = Y" was to live in each module's pre-write hook until |
| 5 | the third module wrote the same hook. Three did (hook_time_logs, |
| 6 | hook_expenses, hook_scans each carry an `_ALLOWED_AFTER_...` set), and a |
| 7 | review then found what every one of them shares: |
| 8 | |
| 9 | * the hook never ran on DELETE, so the frozen record could be removed; |
| 10 | * the hook reads the record before the write lock, so an edit that |
| 11 | arrives while the record is being approved is checked against the |
| 12 | draft and lands on the approved row; |
| 13 | * storage-level writers never reach the hook. |
| 14 | |
| 15 | The declaration: |
| 16 | |
| 17 | "locked_when": [ |
| 18 | {"when": {"status": ["approved", "billed"]}, |
| 19 | "except": ["status", "invoice_id", "notes"]} |
| 20 | ] |
| 21 | |
| 22 | While the STORED record matches `when`, an update may change only the |
| 23 | `except` fields (and fields the server owns: computed and read-only), and |
| 24 | the record cannot be deleted unless the rule says `"allow_delete": true`. |
| 25 | It is checked by object_records inside the write lock, against the row as |
| 26 | it is at that moment, for every writer. Over HTTP a refusal is a 409 with |
| 27 | code "record_locked". |
| 28 | """ |
| 29 | |
| 30 | import json |
| 31 | import threading |
| 32 | |
| 33 | import pytest |
| 34 | |
| 35 | import object_record_changes |
| 36 | import object_records |
| 37 | import object_schemas |
| 38 | import object_server |
| 39 | from test_object_server import TEST_ADMIN_TOKEN, enable_admin_token, request |
| 40 | |
| 41 | AUTH = [("authorization", f"Token {TEST_ADMIN_TOKEN}")] |
| 42 | |
| 43 | FIELDS = [ |
| 44 | {"name": "id"}, |
| 45 | {"name": "status", "type": "enum", "enum": ["draft", "approved", "billed"], "default": "draft"}, |
| 46 | {"name": "hours", "type": "integer"}, |
| 47 | {"name": "notes", "type": "text"}, |
| 48 | {"name": "invoice_id", "type": "text"}, |
| 49 | {"name": "owner_id", "type": "text"}, |
| 50 | {"name": "double_hours", "type": "computed", "formula": "hours * 2"}, |
| 51 | {"name": "stamped_at", "type": "text", "read_only": True}, |
| 52 | {"name": "tag", "type": "text", "store": "extra"}, |
| 53 | ] |
| 54 | FROZEN = [{"when": {"status": ["approved", "billed"]}, "except": ["status", "invoice_id", "notes"]}] |
| 55 | |
| 56 | |
| 57 | def stage(tmp_path, locked_when, *, storage=None, fields=FIELDS): |
| 58 | data_dir = tmp_path / "data" |
| 59 | schema = {"name": "entries", "version": 1, "fields": fields, "locked_when": locked_when} |
| 60 | if storage: |
| 61 | schema["storage"] = storage |
| 62 | (data_dir / "schemas").mkdir(parents=True, exist_ok=True) |
| 63 | (data_dir / "schemas" / "entries.json").write_text(json.dumps(schema)) |
| 64 | return data_dir |
| 65 | |
| 66 | |
| 67 | def create(data_dir, record_id, **fields): |
| 68 | return object_records.create_collection_record( |
| 69 | "entries", {"id": record_id, **fields}, base_dir=data_dir, roots=[]) |
| 70 | |
| 71 | |
| 72 | def update(data_dir, record_id, **changes): |
| 73 | return object_records.update_collection_record( |
| 74 | "entries", record_id, changes, base_dir=data_dir, roots=[]) |
| 75 | |
| 76 | |
| 77 | def delete(data_dir, record_id): |
| 78 | return object_records.delete_collection_record("entries", record_id, base_dir=data_dir, roots=[]) |
| 79 | |
| 80 | |
| 81 | def get(data_dir, record_id): |
| 82 | return object_records.get_collection_record("entries", record_id, base_dir=data_dir, roots=[]) |
| 83 | |
| 84 | |
| 85 | @pytest.fixture(params=["classic", "append"]) |
| 86 | def storage(request): |
| 87 | return request.param |
| 88 | |
| 89 | |
| 90 | # --- the declaration ------------------------------------------------------------ |
| 91 | |
| 92 | |
| 93 | def test_the_schema_keeps_a_lock_declaration_in_canonical_form(): |
| 94 | schema = object_schemas.normalize_schema("entries", { |
| 95 | "name": "entries", "fields": FIELDS, |
| 96 | "locked_when": [ |
| 97 | {"when": {"status": "approved"}}, |
| 98 | {"when": {"status": ["approved", "billed"], "owner_id": "ann"}, |
| 99 | "except": ["notes"], "allow_delete": True, "message": "Settled."}, |
| 100 | ]}) |
| 101 | assert schema["locked_when"] == [ |
| 102 | {"when": {"status": ["approved"]}, "except": [], "allow_delete": False}, |
| 103 | {"when": {"status": ["approved", "billed"], "owner_id": ["ann"]}, |
| 104 | "except": ["notes"], "allow_delete": True, "message": "Settled."}, |
| 105 | ] |
| 106 | # A stored (already canonical) schema loads to the same thing. |
| 107 | assert object_schemas.normalize_schema("entries", schema)["locked_when"] == schema["locked_when"] |
| 108 | |
| 109 | |
| 110 | @pytest.mark.parametrize("locked_when", [ |
| 111 | {"when": {"status": "approved"}}, # not a list of rules |
| 112 | ["approved"], |
| 113 | [{}], # locked when... nothing? |
| 114 | [{"when": {}}], # an always-true rule is not a state |
| 115 | [{"when": "approved"}], |
| 116 | [{"when": {"status": []}}], |
| 117 | [{"when": {"status": 7}}], |
| 118 | [{"when": {"status": ["approved", 7]}}], |
| 119 | [{"when": {"not a name": "x"}}], |
| 120 | [{"when": {"status": "approved"}, "except": "notes"}], |
| 121 | [{"when": {"status": "approved"}, "except": ["not a name"]}], |
| 122 | [{"when": {"status": "approved"}, "allow_delete": "no"}], |
| 123 | [{"when": {"status": "approved"}, "message": ""}], |
| 124 | [{"when": {"status": "approved"}, "unless": ["notes"]}], # a typo must not load as "lock nothing less" |
| 125 | ], ids=lambda value: json.dumps(value)) |
| 126 | def test_a_malformed_lock_declaration_is_refused_not_ignored(locked_when): |
| 127 | with pytest.raises(ValueError): |
| 128 | object_schemas.normalize_schema( |
| 129 | "entries", {"name": "entries", "fields": FIELDS, "locked_when": locked_when}) |
| 130 | |
| 131 | |
| 132 | # --- update --------------------------------------------------------------------- |
| 133 | |
| 134 | |
| 135 | def test_a_locked_record_refuses_a_change_to_a_frozen_field(tmp_path, storage): |
| 136 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 137 | create(data_dir, "t1", status="approved", hours="2", notes="first") |
| 138 | |
| 139 | with pytest.raises(object_records.RecordLockedError) as refusal: |
| 140 | update(data_dir, "t1", hours="20", notes="and a note") |
| 141 | |
| 142 | error = refusal.value |
| 143 | assert isinstance(error, ValueError) |
| 144 | assert (error.collection, error.record_id, error.action) == ("entries", "t1", "update") |
| 145 | assert error.fields == ["hours"] # the frozen field, not the allowed one |
| 146 | assert error.when == {"status": ["approved", "billed"]} |
| 147 | assert "hours" in str(error) and "approved" in str(error) |
| 148 | stored = get(data_dir, "t1") |
| 149 | assert (stored["hours"], stored["notes"]) == ("2", "first") # nothing landed, not even notes |
| 150 | changes = object_record_changes.list_record_changes("entries", base_dir=data_dir)["changes"] |
| 151 | assert [c["action"] for c in changes] == ["create"] |
| 152 | |
| 153 | |
| 154 | def test_a_locked_record_still_takes_changes_to_the_excepted_fields(tmp_path, storage): |
| 155 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 156 | create(data_dir, "t1", status="approved", hours="2") |
| 157 | assert update(data_dir, "t1", notes="queried by client")["notes"] == "queried by client" |
| 158 | billed = update(data_dir, "t1", status="billed", invoice_id="inv-9") |
| 159 | assert (billed["status"], billed["invoice_id"], billed["hours"]) == ("billed", "inv-9", "2") |
| 160 | |
| 161 | |
| 162 | def test_sending_a_frozen_field_back_unchanged_is_not_a_change(tmp_path, storage): |
| 163 | """A form posts every field it shows. Refusing an unchanged value would |
| 164 | make a locked record's notes uneditable from the generated form.""" |
| 165 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 166 | create(data_dir, "t1", status="approved", hours="2", owner_id="ann") |
| 167 | saved = update(data_dir, "t1", hours="2", owner_id="ann", status="approved", notes="ok") |
| 168 | assert saved["notes"] == "ok" |
| 169 | |
| 170 | |
| 171 | def test_an_unlocked_record_is_unaffected_and_the_write_that_locks_it_is_free(tmp_path, storage): |
| 172 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 173 | create(data_dir, "t1", status="draft", hours="2") |
| 174 | assert update(data_dir, "t1", hours="3")["hours"] == "3" |
| 175 | # The approving write itself may change anything: the STORED row is a draft. |
| 176 | approved = update(data_dir, "t1", status="approved", hours="4") |
| 177 | assert (approved["status"], approved["hours"]) == ("approved", "4") |
| 178 | with pytest.raises(object_records.RecordLockedError): |
| 179 | update(data_dir, "t1", hours="5") |
| 180 | |
| 181 | |
| 182 | def test_leaving_the_locked_state_and_editing_take_two_writes(tmp_path, storage): |
| 183 | """One write that both unlocks and edits is judged against the stored, |
| 184 | locked row -- otherwise `status` in `except` would be a skeleton key.""" |
| 185 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 186 | create(data_dir, "t1", status="approved", hours="2") |
| 187 | with pytest.raises(object_records.RecordLockedError): |
| 188 | update(data_dir, "t1", status="draft", hours="9") |
| 189 | update(data_dir, "t1", status="draft") |
| 190 | assert update(data_dir, "t1", hours="9")["hours"] == "9" |
| 191 | |
| 192 | |
| 193 | def test_fields_the_server_owns_are_never_frozen(tmp_path, storage): |
| 194 | """A rollup or formula recomputed on a posted journal, a read-only stamp |
| 195 | written by a trusted writer: neither is a person editing settled data, |
| 196 | and a client cannot submit either.""" |
| 197 | data_dir = stage(tmp_path, [{"when": {"status": "approved"}, "except": ["status"]}], |
| 198 | storage=storage) |
| 199 | create(data_dir, "t1", status="draft", hours="2") |
| 200 | object_records.update_collection_record( |
| 201 | "entries", "t1", {"status": "approved"}, base_dir=data_dir, roots=[]) |
| 202 | stamped = object_records.update_collection_record( |
| 203 | "entries", "t1", {"stamped_at": "2026-07-01T00:00:00Z", "double_hours": "999"}, |
| 204 | base_dir=data_dir, roots=[], preserve_read_only=True, allow_computed_submission=True) |
| 205 | assert stamped["stamped_at"] == "2026-07-01T00:00:00Z" |
| 206 | |
| 207 | |
| 208 | def test_a_field_stored_in_extra_is_frozen_like_any_other(tmp_path, storage): |
| 209 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 210 | create(data_dir, "t1", status="approved", tag="blue") |
| 211 | with pytest.raises(object_records.RecordLockedError) as refusal: |
| 212 | update(data_dir, "t1", tag="red") |
| 213 | assert refusal.value.fields == ["tag"] |
| 214 | assert get(data_dir, "t1")["tag"] == "blue" |
| 215 | |
| 216 | |
| 217 | def test_a_field_the_schema_does_not_declare_is_frozen_too(tmp_path, storage): |
| 218 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 219 | create(data_dir, "t1", status="approved", hours="2") |
| 220 | with pytest.raises(object_records.RecordLockedError) as refusal: |
| 221 | update(data_dir, "t1", smuggled="value") |
| 222 | assert refusal.value.fields == ["smuggled"] |
| 223 | |
| 224 | |
| 225 | def test_every_condition_of_a_rule_must_hold_and_every_matching_rule_applies(tmp_path): |
| 226 | data_dir = stage(tmp_path, [ |
| 227 | {"when": {"status": "approved", "owner_id": "ann"}, "except": ["notes", "hours"]}, |
| 228 | {"when": {"status": ["approved", "billed"]}, "except": ["notes", "invoice_id"]}, |
| 229 | ]) |
| 230 | create(data_dir, "ann1", status="approved", owner_id="ann", hours="1") |
| 231 | create(data_dir, "bob1", status="approved", owner_id="bob", hours="1") |
| 232 | create(data_dir, "ann2", status="draft", owner_id="ann", hours="1") |
| 233 | |
| 234 | update(data_dir, "ann2", hours="2") # neither rule: a draft |
| 235 | update(data_dir, "ann1", notes="both rules allow notes") |
| 236 | with pytest.raises(object_records.RecordLockedError): # rule 2 does not allow hours |
| 237 | update(data_dir, "ann1", hours="2") |
| 238 | with pytest.raises(object_records.RecordLockedError): # rule 1 does not allow invoice_id |
| 239 | update(data_dir, "ann1", invoice_id="inv-1") |
| 240 | update(data_dir, "bob1", invoice_id="inv-1") # only rule 2 matches bob's |
| 241 | |
| 242 | |
| 243 | def test_the_schemas_own_message_is_used_when_it_gives_one(tmp_path): |
| 244 | data_dir = stage(tmp_path, [{"when": {"status": "approved"}, |
| 245 | "message": "Approved time is settled; add a correcting entry."}]) |
| 246 | create(data_dir, "t1", status="approved", hours="2") |
| 247 | with pytest.raises(object_records.RecordLockedError) as refusal: |
| 248 | update(data_dir, "t1", hours="3") |
| 249 | assert str(refusal.value) == "Approved time is settled; add a correcting entry." |
| 250 | |
| 251 | |
| 252 | # --- delete --------------------------------------------------------------------- |
| 253 | |
| 254 | |
| 255 | def test_a_locked_record_cannot_be_deleted(tmp_path, storage): |
| 256 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 257 | create(data_dir, "t1", status="billed", hours="2") |
| 258 | create(data_dir, "t2", status="draft", hours="2") |
| 259 | |
| 260 | with pytest.raises(object_records.RecordLockedError) as refusal: |
| 261 | delete(data_dir, "t1") |
| 262 | |
| 263 | assert (refusal.value.action, refusal.value.fields) == ("delete", []) |
| 264 | assert "deleted" in str(refusal.value) |
| 265 | assert get(data_dir, "t1")["status"] == "billed" |
| 266 | assert delete(data_dir, "t2")["id"] == "t2" # a draft goes as before |
| 267 | changes = object_record_changes.list_record_changes("entries", base_dir=data_dir)["changes"] |
| 268 | assert [(c["record_id"], c["action"]) for c in changes if c["action"] == "delete"] == [ |
| 269 | ("t2", "delete")] |
| 270 | |
| 271 | |
| 272 | def test_a_rule_may_freeze_fields_and_still_allow_deletion(tmp_path): |
| 273 | data_dir = stage(tmp_path, [{"when": {"status": "approved"}, "allow_delete": True}]) |
| 274 | create(data_dir, "t1", status="approved", hours="2") |
| 275 | with pytest.raises(object_records.RecordLockedError): |
| 276 | update(data_dir, "t1", hours="3") |
| 277 | assert delete(data_dir, "t1")["id"] == "t1" |
| 278 | |
| 279 | |
| 280 | def test_a_collection_without_the_key_is_untouched(tmp_path, storage): |
| 281 | data_dir = stage(tmp_path, [], storage=storage) |
| 282 | create(data_dir, "t1", status="approved", hours="2") |
| 283 | assert update(data_dir, "t1", hours="3")["hours"] == "3" |
| 284 | assert delete(data_dir, "t1")["id"] == "t1" |
| 285 | |
| 286 | |
| 287 | # --- the race a hook loses --------------------------------------------------------- |
| 288 | |
| 289 | |
| 290 | def test_an_edit_that_overlaps_the_approval_is_judged_against_the_approved_row( |
| 291 | tmp_path, storage, monkeypatch): |
| 292 | """The window: an editor's request has passed every pre-lock check |
| 293 | (permissions, hook) against the DRAFT. Before it reaches the lock, the |
| 294 | approval lands. A hook-based freeze lets the edit through -- it already |
| 295 | decided. The lock check reads the row again under the lock.""" |
| 296 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 297 | create(data_dir, "t1", status="draft", hours="2") |
| 298 | real_lock = object_records._records_file_lock |
| 299 | state = {"armed": True} |
| 300 | |
| 301 | def lock_after_the_approval(path): |
| 302 | if state["armed"]: |
| 303 | state["armed"] = False |
| 304 | update(data_dir, "t1", status="approved") # lands first |
| 305 | return real_lock(path) |
| 306 | |
| 307 | monkeypatch.setattr(object_records, "_records_file_lock", lock_after_the_approval) |
| 308 | |
| 309 | with pytest.raises(object_records.RecordLockedError): |
| 310 | update(data_dir, "t1", hours="200") # the editor's write |
| 311 | |
| 312 | stored = get(data_dir, "t1") |
| 313 | assert (stored["status"], stored["hours"]) == ("approved", "2") |
| 314 | |
| 315 | |
| 316 | def test_threads_racing_an_approval_against_edits_never_edit_the_approved_row(tmp_path, storage): |
| 317 | """Real overlap, no patching: one approver and many editors released |
| 318 | together, many rounds. Whatever order they land in, no edit may be |
| 319 | stored AFTER the approval -- so the hours the approval saw are the |
| 320 | hours on file.""" |
| 321 | data_dir = stage(tmp_path, FROZEN, storage=storage) |
| 322 | editors, rounds = 8, 12 |
| 323 | for round_number in range(rounds): |
| 324 | record_id = f"t{round_number}" |
| 325 | create(data_dir, record_id, status="draft", hours="1") |
| 326 | barrier = threading.Barrier(editors + 1) |
| 327 | crashed = [] |
| 328 | |
| 329 | def approve(record_id=record_id, barrier=barrier): |
| 330 | barrier.wait() |
| 331 | update(data_dir, record_id, status="approved") |
| 332 | |
| 333 | def edit(n, record_id=record_id, barrier=barrier): |
| 334 | barrier.wait() |
| 335 | try: |
| 336 | update(data_dir, record_id, hours=str(100 + n)) |
| 337 | except object_records.RecordLockedError: |
| 338 | pass |
| 339 | except Exception as exc: # noqa: BLE001 - reported below |
| 340 | crashed.append(repr(exc)) |
| 341 | |
| 342 | threads = [threading.Thread(target=approve)] |
| 343 | threads += [threading.Thread(target=edit, args=(n,)) for n in range(editors)] |
| 344 | for thread in threads: |
| 345 | thread.start() |
| 346 | for thread in threads: |
| 347 | thread.join(timeout=60) |
| 348 | assert crashed == [] |
| 349 | |
| 350 | history = list(reversed(object_record_changes.list_record_changes( |
| 351 | "entries", record_id=record_id, base_dir=data_dir)["changes"])) |
| 352 | approved_at = next(i for i, change in enumerate(history) |
| 353 | if change["action"] == "update" |
| 354 | and change["after"]["status"] == "approved" |
| 355 | and change["before"]["status"] == "draft") |
| 356 | assert history[approved_at + 1:] == [], ( |
| 357 | f"{record_id}: writes landed after the approval: " |
| 358 | f"{[c['changed_fields'] for c in history[approved_at + 1:]]}") |
| 359 | assert get(data_dir, record_id)["hours"] == history[approved_at]["after"]["hours"] |
| 360 | |
| 361 | |
| 362 | # --- over HTTP --------------------------------------------------------------------- |
| 363 | |
| 364 | |
| 365 | def http_site(tmp_path, monkeypatch, locked_when=FROZEN): |
| 366 | data_dir = stage(tmp_path, locked_when) |
| 367 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 368 | enable_admin_token(monkeypatch) |
| 369 | return data_dir |
| 370 | |
| 371 | |
| 372 | def put(record_id, changes): |
| 373 | return request(f"/collections/entries/records/{record_id}", method="PUT", |
| 374 | body=json.dumps(changes).encode("utf-8"), headers=AUTH) |
| 375 | |
| 376 | |
| 377 | def test_a_locked_update_over_http_is_a_409_that_names_the_frozen_fields(tmp_path, monkeypatch): |
| 378 | data_dir = http_site(tmp_path, monkeypatch) |
| 379 | create(data_dir, "t1", status="approved", hours="2") |
| 380 | |
| 381 | status, _, payload = put("t1", {"hours": "20", "notes": "x"}) |
| 382 | |
| 383 | assert status == 409 |
| 384 | assert payload["status"] == "error" |
| 385 | assert payload["code"] == "record_locked" |
| 386 | assert payload["fields"] == ["hours"] |
| 387 | assert "hours" in payload["error"] |
| 388 | assert get(data_dir, "t1")["hours"] == "2" |
| 389 | assert put("t1", {"notes": "x"})[0] == 200 |
| 390 | |
| 391 | |
| 392 | def test_a_locked_delete_over_http_is_a_409_and_admin_is_not_exempt(tmp_path, monkeypatch): |
| 393 | """The rule is about the record, not the caller. The admin token is the |
| 394 | most trusted HTTP caller there is, and it is refused.""" |
| 395 | data_dir = http_site(tmp_path, monkeypatch) |
| 396 | create(data_dir, "t1", status="billed", hours="2") |
| 397 | |
| 398 | status, _, payload = request( |
| 399 | "/collections/entries/records/t1", method="DELETE", headers=AUTH) |
| 400 | |
| 401 | assert (status, payload["code"], payload["fields"]) == (409, "record_locked", []) |
| 402 | assert get(data_dir, "t1")["status"] == "billed" |
| 403 | |
| 404 | |
| 405 | # --- the per-field form: `fields` freezes only what it names ------------------------- |
| 406 | |
| 407 | ONLY_HOURS = [{"when": {"status": ["approved"]}, "fields": ["hours", "invoice_id"]}] |
| 408 | |
| 409 | |
| 410 | def test_the_fields_form_is_kept_in_canonical_form_without_an_except_key(): |
| 411 | schema = object_schemas.normalize_schema("entries", { |
| 412 | "name": "entries", "fields": FIELDS, |
| 413 | "locked_when": [{"when": {"status": "approved"}, "fields": ["hours", "notes", "hours"], |
| 414 | "message": "Settled."}]}) |
| 415 | assert schema["locked_when"] == [ |
| 416 | {"when": {"status": ["approved"]}, "fields": ["hours", "notes"], |
| 417 | "allow_delete": False, "message": "Settled."}] |
| 418 | assert object_schemas.normalize_schema("entries", schema)["locked_when"] == schema["locked_when"] |
| 419 | |
| 420 | |
| 421 | @pytest.mark.parametrize("locked_when", [ |
| 422 | [{"when": {"status": "approved"}, "fields": ["hours"], "except": ["notes"]}], # both: ambiguous |
| 423 | [{"when": {"status": "approved"}, "fields": ["hours"], "except": []}], # still both |
| 424 | [{"when": {"status": "approved"}, "fields": []}], # freezes nothing |
| 425 | [{"when": {"status": "approved"}, "fields": "hours"}], |
| 426 | [{"when": {"status": "approved"}, "fields": ["not a name"]}], |
| 427 | [{"when": {"status": "approved"}, "fields": ["hourz"]}], # a typo leaves the field editable |
| 428 | [{"when": {"status": "approved"}, "fields": ["id"]}], |
| 429 | ], ids=lambda value: json.dumps(value)) |
| 430 | def test_a_malformed_fields_declaration_is_refused_not_ignored(locked_when): |
| 431 | with pytest.raises(ValueError): |
| 432 | object_schemas.normalize_schema( |
| 433 | "entries", {"name": "entries", "fields": FIELDS, "locked_when": locked_when}) |
| 434 | |
| 435 | |
| 436 | def test_with_fields_only_the_named_fields_are_frozen_and_new_ones_are_not(tmp_path, storage): |
| 437 | data_dir = stage(tmp_path, ONLY_HOURS, storage=storage) |
| 438 | create(data_dir, "t1", status="approved", hours="2", notes="a") |
| 439 | # Not named: free, including a field nobody thought of when the rule was written. |
| 440 | saved = update(data_dir, "t1", notes="b", owner_id="ann", status="billed") |
| 441 | assert (saved["notes"], saved["owner_id"], saved["status"]) == ("b", "ann", "billed") |
| 442 | # The rule is judged by the STORED row: billed no longer matches `approved`. |
| 443 | assert update(data_dir, "t1", hours="9")["hours"] == "9" |
| 444 | |
| 445 | |
| 446 | def test_with_fields_a_named_field_is_refused_while_the_record_is_in_the_state(tmp_path, storage): |
| 447 | data_dir = stage(tmp_path, ONLY_HOURS, storage=storage) |
| 448 | create(data_dir, "t1", status="approved", hours="2") |
| 449 | with pytest.raises(object_records.RecordLockedError) as refused: |
| 450 | update(data_dir, "t1", hours="3", invoice_id="i1", notes="fine") |
| 451 | assert refused.value.fields == ["hours", "invoice_id"] |
| 452 | assert get(data_dir, "t1")["hours"] == "2" |
| 453 | assert not get(data_dir, "t1").get("notes") |
| 454 | # Sending a frozen field back unchanged is not a change. |
| 455 | assert update(data_dir, "t1", hours="2", notes="ok")["notes"] == "ok" |
| 456 | |
| 457 | |
| 458 | def test_with_fields_the_record_still_cannot_be_deleted_unless_allowed(tmp_path, storage): |
| 459 | data_dir = stage(tmp_path, ONLY_HOURS, storage=storage) |
| 460 | create(data_dir, "t1", status="approved") |
| 461 | with pytest.raises(object_records.RecordLockedError) as refused: |
| 462 | delete(data_dir, "t1") |
| 463 | assert refused.value.action == "delete" |
| 464 | data_dir = stage(tmp_path / "again", [{**ONLY_HOURS[0], "allow_delete": True}], storage=storage) |
| 465 | create(data_dir, "t1", status="approved") |
| 466 | delete(data_dir, "t1") |
| 467 | |
| 468 | |
| 469 | def test_a_fields_rule_and_an_except_rule_compose_each_only_restricting(tmp_path, storage): |
| 470 | data_dir = stage(tmp_path, [ |
| 471 | {"when": {"status": "approved"}, "fields": ["hours"]}, |
| 472 | {"when": {"status": "approved"}, "except": ["hours", "notes"]}, |
| 473 | ], storage=storage) |
| 474 | create(data_dir, "t1", status="approved", hours="2") |
| 475 | assert update(data_dir, "t1", notes="n")["notes"] == "n" |
| 476 | for changes in ({"hours": "3"}, {"invoice_id": "i"}): |
| 477 | with pytest.raises(object_records.RecordLockedError): |
| 478 | update(data_dir, "t1", **changes) |
| 479 | |
| 480 | |
| 481 | def test_a_fields_refusal_over_http_is_the_same_409(tmp_path, monkeypatch): |
| 482 | data_dir = http_site(tmp_path, monkeypatch, locked_when=ONLY_HOURS) |
| 483 | create(data_dir, "t1", status="approved", hours="2") |
| 484 | status, _, payload = put("t1", {"hours": "20", "notes": "x"}) |
| 485 | assert (status, payload["code"], payload["fields"]) == (409, "record_locked", ["hours"]) |
| 486 | assert put("t1", {"notes": "x"})[0] == 200 |
| 487 | |
| 488 | |
| 489 | # --- retention --------------------------------------------------------------------- |
| 490 | |
| 491 | |
| 492 | def test_retention_refuses_a_collection_that_declares_settled_records(tmp_path): |
| 493 | """prune_collection_records rewrites the file to the rows it keeps, so |
| 494 | the delete check never ran: pointed at an append-mode collection it |
| 495 | aged an approved entry out like a page view. Its only caller is the |
| 496 | page_views retention pass, but the primitive took any collection. A |
| 497 | collection that declares locked_when is not a log, and is refused.""" |
| 498 | data_dir = stage(tmp_path, FROZEN, storage="append", |
| 499 | fields=FIELDS + [{"name": "created_at", "type": "datetime", "read_only": True}]) |
| 500 | object_records.create_collection_record( |
| 501 | "entries", {"id": "t1", "status": "approved", "hours": "2", |
| 502 | "created_at": "2020-01-01T00:00:00Z"}, |
| 503 | base_dir=data_dir, roots=[], preserve_read_only=True) |
| 504 | |
| 505 | with pytest.raises(ValueError, match="locked_when"): |
| 506 | object_records.prune_collection_records( |
| 507 | "entries", keep_newer_than="2026-01-01T00:00:00Z", base_dir=data_dir, roots=[]) |
| 508 | with pytest.raises(ValueError, match="locked_when"): |
| 509 | object_records.prune_collection_records( |
| 510 | "entries", keep_newer_than="2000-01-01T00:00:00Z", keep_last=0, |
| 511 | base_dir=data_dir, roots=[]) |
| 512 | assert get(data_dir, "t1")["status"] == "approved" |
| 513 | |
| 514 | |
| 515 | def test_retention_still_ages_out_a_collection_without_locked_when(tmp_path): |
| 516 | data_dir = stage(tmp_path, [], storage="append", |
| 517 | fields=FIELDS + [{"name": "created_at", "type": "datetime", "read_only": True}]) |
| 518 | object_records.create_collection_record( |
| 519 | "entries", {"id": "t1", "status": "approved", "created_at": "2020-01-01T00:00:00Z"}, |
| 520 | base_dir=data_dir, roots=[], preserve_read_only=True) |
| 521 | result = object_records.prune_collection_records( |
| 522 | "entries", keep_newer_than="2026-01-01T00:00:00Z", base_dir=data_dir, roots=[]) |
| 523 | assert result["removed"] == 1 |