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_gate_reads_fail_closed.py · 8.0 KB · 178 lines
| 1 | """The shared read helpers gates lean on can be told to fail closed. |
| 2 | |
| 3 | A gate that reads other records to decide ("is this bank line already on |
| 4 | file?", "does this date fall in a closed period?") has to do something when |
| 5 | the read itself fails. Five helpers in object_banking and object_finance |
| 6 | answered "nothing found" -- so with the ledger unreadable the duplicate gate |
| 7 | passed the duplicate, and with fin_closed_periods unreadable the period |
| 8 | lock let a journal into settled books. A gate that passes because it could |
| 9 | not look is not a gate. |
| 10 | |
| 11 | Each helper now takes `strict=True`: |
| 12 | |
| 13 | * a real read failure RAISES (whatever the read raised), so the caller |
| 14 | refuses -- a hook that lets it propagate is a 500 and no write; |
| 15 | * a collection that is simply NOT INSTALLED is still "no rows", because |
| 16 | that is a true answer, not an unknown one: nothing can be on file in a |
| 17 | collection that does not exist. |
| 18 | |
| 19 | The default (`strict=False`) is unchanged, deliberately: three of these are |
| 20 | called by importer actions after they have already written an import row, |
| 21 | where an exception today would leave exactly the half-written state another |
| 22 | finding describes. Each caller has to be moved to strict with its own |
| 23 | error handling; this file pins both behaviours so that move is a one-word |
| 24 | change per call site. |
| 25 | |
| 26 | The failure is injected the way tests/test_findings_money_gates.py does it |
| 27 | -- the helper's own call to object_records.read_collection_records raises -- |
| 28 | which also pins that each helper still makes that call ITSELF: those tests |
| 29 | identify the caller by stack frame. |
| 30 | """ |
| 31 | |
| 32 | import sys |
| 33 | |
| 34 | import pytest |
| 35 | from conftest import schema_header, stage_collection |
| 36 | |
| 37 | import object_banking |
| 38 | import object_finance |
| 39 | import object_records |
| 40 | |
| 41 | |
| 42 | def add_rows(records_path, package, collection, *rows): |
| 43 | names = schema_header(package, collection).rstrip("\n").split("\t") |
| 44 | with records_path.open("a") as handle: |
| 45 | for row in rows: |
| 46 | handle.write("\t".join(row.get(name, "") for name in names) + "\n") |
| 47 | |
| 48 | |
| 49 | @pytest.fixture |
| 50 | def data_dir(tmp_path): |
| 51 | data = tmp_path / "data" |
| 52 | lines = stage_collection(data, "app-banking", "bank_lines") |
| 53 | add_rows(lines, "app-banking", "bank_lines", |
| 54 | {"id": "l1", "bank_account_id": "bank-1", "posted_on": "2026-07-02", |
| 55 | "amount_cents": "150000", "external_id": "FIT-1", "line_hash": "hash-1"}) |
| 56 | imports = stage_collection(data, "app-banking", "bank_statement_imports") |
| 57 | add_rows(imports, "app-banking", "bank_statement_imports", |
| 58 | {"id": "i1", "bank_account_id": "bank-1", "file_hash": "digest-1", |
| 59 | "period_end": "2026-07-31", "status": "accepted"}) |
| 60 | periods = stage_collection(data, "app-finance", "fin_closed_periods") |
| 61 | add_rows(periods, "app-finance", "fin_closed_periods", |
| 62 | {"id": "p1", "start_date": "2025-01-01", "end_date": "2025-12-31", |
| 63 | "owner_id": "ann"}) |
| 64 | return data |
| 65 | |
| 66 | |
| 67 | @pytest.fixture |
| 68 | def unreadable(monkeypatch): |
| 69 | """Make reads of the named collections raise, and record who asked.""" |
| 70 | real = object_records.read_collection_records |
| 71 | state = {"collections": set(), "callers": []} |
| 72 | |
| 73 | def read(name, *args, **kwargs): |
| 74 | if name in state["collections"]: |
| 75 | frame = sys._getframe(1) |
| 76 | state["callers"].append((frame.f_code.co_filename.rsplit("/", 1)[-1], |
| 77 | frame.f_code.co_name)) |
| 78 | raise OSError(f"simulated: {name} is unreadable") |
| 79 | return real(name, *args, **kwargs) |
| 80 | |
| 81 | monkeypatch.setattr(object_records, "read_collection_records", read) |
| 82 | return state |
| 83 | |
| 84 | |
| 85 | # (the helper, how to call it, the collection it reads, what "found" looks like, |
| 86 | # what the lenient answer is when the read fails) |
| 87 | CASES = [ |
| 88 | ("existing_line_keys", |
| 89 | lambda base, **kw: object_banking.existing_line_keys("bank-1", base_dir=base, **kw), |
| 90 | "bank_lines", ({"FIT-1"}, {"hash-1"}), (set(), set())), |
| 91 | ("is_duplicate_line", |
| 92 | lambda base, **kw: object_banking.is_duplicate_line( |
| 93 | {"bank_account_id": "bank-1", "line_hash": "hash-1"}, base_dir=base, **kw), |
| 94 | "bank_lines", True, False), |
| 95 | ("find_import_by_file_hash", |
| 96 | lambda base, **kw: (object_banking.find_import_by_file_hash( |
| 97 | "bank-1", "digest-1", base_dir=base, **kw) or {}).get("id"), |
| 98 | "bank_statement_imports", "i1", None), |
| 99 | ("previous_import", |
| 100 | lambda base, **kw: (object_banking.previous_import( |
| 101 | "bank-1", base_dir=base, **kw) or {}).get("id"), |
| 102 | "bank_statement_imports", "i1", None), |
| 103 | ("closed_period_for", |
| 104 | lambda base, **kw: (object_finance.closed_period_for( |
| 105 | "2025-06-30", base_dir=base, owner_id="ann", **kw) or {}).get("id"), |
| 106 | "fin_closed_periods", "p1", None), |
| 107 | ] |
| 108 | IDS = [case[0] for case in CASES] |
| 109 | |
| 110 | |
| 111 | @pytest.mark.parametrize("name,call,collection,found,lenient", CASES, ids=IDS) |
| 112 | def test_with_a_readable_collection_strict_and_lenient_agree( |
| 113 | data_dir, name, call, collection, found, lenient): |
| 114 | assert call(data_dir) == found |
| 115 | assert call(data_dir, strict=True) == found |
| 116 | |
| 117 | |
| 118 | @pytest.mark.parametrize("name,call,collection,found,lenient", CASES, ids=IDS) |
| 119 | def test_strict_raises_when_the_read_fails( |
| 120 | data_dir, unreadable, name, call, collection, found, lenient): |
| 121 | """Fail closed: the caller gets the failure, not "nothing found".""" |
| 122 | unreadable["collections"].add(collection) |
| 123 | with pytest.raises(OSError, match="unreadable"): |
| 124 | call(data_dir, strict=True) |
| 125 | # ...and the read that failed was the helper's own, made from its own |
| 126 | # module (is_duplicate_line reads through existing_line_keys). |
| 127 | module = "object_finance.py" if name == "closed_period_for" else "object_banking.py" |
| 128 | reader = "existing_line_keys" if name == "is_duplicate_line" else name |
| 129 | assert unreadable["callers"] == [(module, reader)] |
| 130 | |
| 131 | |
| 132 | @pytest.mark.parametrize("name,call,collection,found,lenient", CASES, ids=IDS) |
| 133 | def test_the_default_is_unchanged_and_still_answers_nothing_found( |
| 134 | data_dir, unreadable, name, call, collection, found, lenient): |
| 135 | """Pinned so nobody mistakes the default for the safe one: this is the |
| 136 | fail-open answer the callers still get until each is moved to strict.""" |
| 137 | unreadable["collections"].add(collection) |
| 138 | assert call(data_dir) == lenient |
| 139 | assert lenient != found |
| 140 | |
| 141 | |
| 142 | @pytest.mark.parametrize("name,call,collection,found,lenient", CASES, ids=IDS) |
| 143 | def test_strict_still_answers_nothing_found_for_a_collection_that_is_not_installed( |
| 144 | tmp_path, name, call, collection, found, lenient): |
| 145 | """Not installed is a fact, not a fault: app-finance without closed |
| 146 | periods ever having been set up has no closed periods.""" |
| 147 | empty = tmp_path / "nothing-installed" |
| 148 | empty.mkdir() |
| 149 | assert call(empty, strict=True) == lenient |
| 150 | |
| 151 | |
| 152 | def test_the_continuity_check_does_not_record_a_false_reason_under_strict(data_dir, unreadable): |
| 153 | """run_gates writes its result onto the import as evidence. Lenient, an |
| 154 | unreadable import history is recorded as "no prior statement for this |
| 155 | account" -- which is not what happened.""" |
| 156 | unreadable["collections"].add("bank_statement_imports") |
| 157 | lines = [{"amount_cents": "150000"}] |
| 158 | balances = {"bank_account_id": "bank-1", "opening_balance_cents": "0", |
| 159 | "closing_balance_cents": "150000", "base_dir": data_dir} |
| 160 | |
| 161 | lenient = object_banking.run_gates(lines, **balances) |
| 162 | assert lenient["checks"]["continuity"] == { |
| 163 | "ran": False, "reason": "no prior statement for this account"} |
| 164 | with pytest.raises(OSError, match="unreadable"): |
| 165 | object_banking.run_gates(lines, strict=True, **balances) |
| 166 | |
| 167 | |
| 168 | def test_a_corrupt_file_is_a_failure_not_an_empty_collection(data_dir): |
| 169 | """The real thing rather than a patched reader: a records file whose |
| 170 | header has lost its id column cannot be read.""" |
| 171 | path = object_records.collection_records_file("fin_closed_periods", base_dir=data_dir) |
| 172 | path.write_text("start_date\tend_date\n2025-01-01\t2025-12-31\n") |
| 173 | |
| 174 | assert object_finance.closed_period_for( |
| 175 | "2025-06-30", base_dir=data_dir, owner_id="ann") is None # lenient: open |
| 176 | with pytest.raises(ValueError): |
| 177 | object_finance.closed_period_for( |
| 178 | "2025-06-30", base_dir=data_dir, owner_id="ann", strict=True) |