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_document_intake.py · 17.0 KB · 438 lines
| 1 | """Document intake: a machine reads, a person decides. |
| 2 | |
| 3 | The property this whole package exists to hold is that nothing an |
| 4 | extractor produces ever reaches the books on its own. Everything else -- |
| 5 | dedup, engine choice, confidence -- is in service of that, and most of |
| 6 | these tests are checking that a BAD reading is merely inconvenient rather |
| 7 | than wrong. |
| 8 | """ |
| 9 | |
| 10 | import base64 |
| 11 | import json |
| 12 | import pathlib |
| 13 | |
| 14 | import pytest |
| 15 | |
| 16 | from conftest import stage_collection |
| 17 | |
| 18 | import object_execution |
| 19 | import object_intake |
| 20 | import object_records |
| 21 | import python_object_runtime |
| 22 | |
| 23 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 24 | PACKAGES = REPO_ROOT / "packages" |
| 25 | INTAKE_OBJECTS = PACKAGES / "app-intake" / "objects" |
| 26 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 27 | |
| 28 | RECEIPT = """BLUE BOTTLE COFFEE |
| 29 | 1234 Market St |
| 30 | 06/15/2026 |
| 31 | |
| 32 | Latte 4.50 |
| 33 | Croissant 3.75 |
| 34 | Subtotal 8.25 |
| 35 | Tax 0.74 |
| 36 | TOTAL 8.99 |
| 37 | |
| 38 | Suggested tip 20% 1.80 |
| 39 | """ |
| 40 | |
| 41 | |
| 42 | def setup_env(tmp_path, monkeypatch, *, settings=()): |
| 43 | data_dir = tmp_path / "data" |
| 44 | for pkg, name in (("app-intake", "scans"), ("app-finance", "expenses"), |
| 45 | ("app-projects", "projects")): |
| 46 | stage_collection(data_dir, pkg, name) |
| 47 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings)) |
| 48 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 49 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 50 | return data_dir |
| 51 | |
| 52 | |
| 53 | def run(object_id, payload=None, *, roots=None): |
| 54 | return object_execution.execute_object( |
| 55 | RUNTIME, |
| 56 | object_execution.ObjectExecutionRequest( |
| 57 | object_id, method="POST", payload=payload or {}), |
| 58 | roots=roots or [INTAKE_OBJECTS]).result |
| 59 | |
| 60 | |
| 61 | def confirm(payload): |
| 62 | """As dana, who owns the scans ingest() makes: the action refuses |
| 63 | anybody the permission engine would not let update the scan.""" |
| 64 | return run("action_confirm_scan", |
| 65 | {"_identity": {"user_id": "dana"}, **payload}) |
| 66 | |
| 67 | |
| 68 | def ingest(text=RECEIPT, **fields): |
| 69 | payload = {"text": text, "owner_id": "dana", "filename": "coffee.txt"} |
| 70 | payload.update(fields) |
| 71 | return run("action_scan_ingest", payload) |
| 72 | |
| 73 | |
| 74 | def ingest_bytes(content=b"\x89PNG fake image", **fields): |
| 75 | payload = {"content_base64": base64.b64encode(content).decode(), |
| 76 | "owner_id": "dana", "filename": "receipt.png"} |
| 77 | payload.update(fields) |
| 78 | return run("action_scan_ingest", payload) |
| 79 | |
| 80 | |
| 81 | def scan(data_dir, scan_id): |
| 82 | return object_records.get_collection_record("scans", scan_id, base_dir=data_dir) |
| 83 | |
| 84 | |
| 85 | def expenses(data_dir): |
| 86 | return object_records.read_collection_records("expenses", base_dir=data_dir) |
| 87 | |
| 88 | |
| 89 | # --- reading, with no model and no key ------------------------------------- |
| 90 | |
| 91 | def test_the_total_is_chosen_by_its_label_not_its_size(): |
| 92 | """Taking the biggest number on the page is how an intake system |
| 93 | bills a client for the suggested-tip line.""" |
| 94 | assert object_intake.find_total_cents(RECEIPT) == 899 |
| 95 | |
| 96 | |
| 97 | def test_a_date_and_a_vendor_come_off_the_page(): |
| 98 | assert object_intake.find_date(RECEIPT) == "2026-06-15" |
| 99 | assert object_intake.find_vendor(RECEIPT) == "BLUE BOTTLE COFFEE" |
| 100 | |
| 101 | |
| 102 | def test_confidence_reflects_what_was_found_not_what_was_claimed(): |
| 103 | full = object_intake.guess_from_text(RECEIPT) |
| 104 | empty = object_intake.guess_from_text("") |
| 105 | assert full["confidence"] > empty["confidence"] == 0.0 |
| 106 | assert full["total_cents"] == 899 |
| 107 | |
| 108 | |
| 109 | def test_an_unreadable_page_yields_an_empty_suggestion_not_a_crash(): |
| 110 | """Nothing found has to be an answer, because it is the answer a free |
| 111 | extractor gives most often.""" |
| 112 | guess = object_intake.guess_from_text("~~~ 8||| ~~~") |
| 113 | assert guess["total_cents"] == 0 and guess["confidence"] == 0.0 |
| 114 | |
| 115 | |
| 116 | def test_a_models_loose_json_is_clamped_into_the_same_shape(): |
| 117 | normalized = object_intake.normalize_extraction( |
| 118 | '{"kind": "RECEIPT", "vendor": "Blue Bottle", "total": "$8.99",' |
| 119 | ' "confidence": 87, "line_items": [{"description": "Latte",' |
| 120 | ' "amount": "4.50"}]}', engine="ai_vision") |
| 121 | assert normalized["kind"] == "receipt" |
| 122 | assert normalized["total_cents"] == 899 |
| 123 | assert normalized["confidence"] == 0.87 # percent understood as a ratio |
| 124 | assert normalized["line_items"][0]["amount_cents"] == 450 |
| 125 | |
| 126 | |
| 127 | def test_an_extractor_having_a_bad_day_returns_nothing_usable(tmp_path): |
| 128 | """It must leave a scan waiting for a human, never break the pass |
| 129 | reading a hundred other documents.""" |
| 130 | for junk in ("not json at all", None, 42, "[1,2,3]"): |
| 131 | normalized = object_intake.normalize_extraction(junk) |
| 132 | assert normalized["total_cents"] == 0 and normalized["confidence"] == 0.0 |
| 133 | |
| 134 | |
| 135 | # --- ingest ------------------------------------------------------------------- |
| 136 | |
| 137 | def test_ingest_stores_and_returns_without_reading_anything(tmp_path, monkeypatch): |
| 138 | """Capture happens at a till with a phone; anything slower is a |
| 139 | receipt that ends up in a coat pocket.""" |
| 140 | data_dir = setup_env(tmp_path, monkeypatch) |
| 141 | result = ingest() |
| 142 | assert result["ok"] and result["status_of_scan"] == "pending" |
| 143 | |
| 144 | row = scan(data_dir, result["scan_id"]) |
| 145 | assert row["status"] == "pending" |
| 146 | assert row["extracted"] == "" # nothing read yet, deliberately |
| 147 | assert row["content_sha256"] |
| 148 | |
| 149 | |
| 150 | def test_the_same_receipt_photographed_twice_is_one_scan(tmp_path, monkeypatch): |
| 151 | """The second photo of a crumpled receipt is the normal case.""" |
| 152 | data_dir = setup_env(tmp_path, monkeypatch) |
| 153 | first = ingest() |
| 154 | again = ingest() |
| 155 | assert again["duplicate"] is True |
| 156 | assert again["scan_id"] == first["scan_id"] |
| 157 | assert len(object_records.read_collection_records("scans", base_dir=data_dir)) == 1 |
| 158 | |
| 159 | |
| 160 | def test_the_schema_refuses_a_duplicate_written_any_other_way(tmp_path, monkeypatch): |
| 161 | """No hook any more: `unique` on content_sha256 per owner refuses it |
| 162 | inside the write lock, for every writer.""" |
| 163 | data_dir = setup_env(tmp_path, monkeypatch) |
| 164 | result = ingest() |
| 165 | digest = scan(data_dir, result["scan_id"])["content_sha256"] |
| 166 | with pytest.raises(object_records.UniqueConstraintError) as refused: |
| 167 | object_records.create_collection_record( |
| 168 | "scans", {"id": "again", "content_sha256": digest, "owner_id": "dana"}, |
| 169 | base_dir=data_dir) |
| 170 | assert "two expenses" in str(refused.value) |
| 171 | |
| 172 | |
| 173 | def test_two_businesses_may_receive_the_same_document(tmp_path, monkeypatch): |
| 174 | """The same invoice PDF reaching two companies is two genuine facts.""" |
| 175 | setup_env(tmp_path, monkeypatch) |
| 176 | ingest() |
| 177 | other = ingest(owner_id="sam") |
| 178 | assert other["ok"] and not other.get("duplicate") |
| 179 | |
| 180 | |
| 181 | def test_ingest_needs_an_owner_and_some_content(tmp_path, monkeypatch): |
| 182 | setup_env(tmp_path, monkeypatch) |
| 183 | assert run("action_scan_ingest", {"text": "x"})["status"] == 401 |
| 184 | assert run("action_scan_ingest", {"owner_id": "dana"})["status"] == 400 |
| 185 | assert run("action_scan_ingest", |
| 186 | {"owner_id": "dana", "content_base64": "!!not base64!!"})["status"] == 400 |
| 187 | |
| 188 | |
| 189 | # --- the reading pass ----------------------------------------------------------- |
| 190 | |
| 191 | def test_the_free_engine_reads_text_that_arrived_as_text(tmp_path, monkeypatch): |
| 192 | data_dir = setup_env(tmp_path, monkeypatch) |
| 193 | scan_id = ingest()["scan_id"] |
| 194 | result = run("system_scan_processor") |
| 195 | assert result["extracted"] == 1 and result["engine"] == "text_rules" |
| 196 | |
| 197 | row = scan(data_dir, scan_id) |
| 198 | assert row["status"] == "extracted" |
| 199 | assert json.loads(row["extracted"])["total_cents"] == 899 |
| 200 | assert row["confirmed_record"] == "" # read, not posted |
| 201 | |
| 202 | |
| 203 | def test_an_image_with_no_ocr_engine_still_becomes_confirmable(tmp_path, monkeypatch): |
| 204 | """The honest free path: no text found, image attached, type the |
| 205 | total. Never a wrong number.""" |
| 206 | data_dir = setup_env(tmp_path, monkeypatch) |
| 207 | scan_id = ingest_bytes()["scan_id"] |
| 208 | run("system_scan_processor") |
| 209 | |
| 210 | row = scan(data_dir, scan_id) |
| 211 | assert row["status"] == "extracted" |
| 212 | assert json.loads(row["extracted"])["total_cents"] == 0 |
| 213 | |
| 214 | |
| 215 | def test_a_missing_host_engine_leaves_the_document_pending(tmp_path, monkeypatch): |
| 216 | """A host that is not set up is an operator's problem to fix, not a |
| 217 | document to give up on -- so it stays pending and the backlog drains |
| 218 | the moment the engine appears.""" |
| 219 | data_dir = setup_env(tmp_path, monkeypatch, |
| 220 | settings=(("intake.ocr_engine", "ai_vision"),)) |
| 221 | scan_id = ingest_bytes()["scan_id"] |
| 222 | result = run("system_scan_processor") |
| 223 | |
| 224 | row = scan(data_dir, scan_id) |
| 225 | assert result["failed"] == 1 |
| 226 | assert row["status"] == "pending" # retried when the host is fixed |
| 227 | assert "ai_vision" in row["error"] |
| 228 | |
| 229 | |
| 230 | def test_a_document_that_keeps_failing_stops_being_retried(tmp_path, monkeypatch): |
| 231 | """Churning a paid extractor forever against a corrupt file is how an |
| 232 | intake queue silently spends money.""" |
| 233 | data_dir = setup_env(tmp_path, monkeypatch) |
| 234 | scan_id = ingest_bytes()["scan_id"] |
| 235 | object_records.update_collection_record( |
| 236 | "scans", scan_id, {"status": "error", "attempts": "3"}, |
| 237 | base_dir=data_dir, actor="test") |
| 238 | result = run("system_scan_processor") |
| 239 | assert result["considered"] == 0 |
| 240 | assert scan_id in result["needing_a_human"] |
| 241 | |
| 242 | |
| 243 | def test_reading_twice_does_not_re_read(tmp_path, monkeypatch): |
| 244 | setup_env(tmp_path, monkeypatch) |
| 245 | ingest() |
| 246 | run("system_scan_processor") |
| 247 | assert run("system_scan_processor")["extracted"] == 0 |
| 248 | |
| 249 | |
| 250 | def test_intake_absent_is_a_graceful_skip(tmp_path, monkeypatch): |
| 251 | data_dir = tmp_path / "data" |
| 252 | data_dir.mkdir() |
| 253 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 254 | assert run("system_scan_processor")["skipped"].startswith("intake not installed") |
| 255 | |
| 256 | |
| 257 | # --- confirmation ---------------------------------------------------------------- |
| 258 | |
| 259 | def test_confirming_creates_a_draft_expense_with_its_provenance( |
| 260 | tmp_path, monkeypatch): |
| 261 | data_dir = setup_env(tmp_path, monkeypatch) |
| 262 | scan_id = ingest()["scan_id"] |
| 263 | run("system_scan_processor") |
| 264 | |
| 265 | result = confirm({"scan_id": scan_id, "project_id": ""}) |
| 266 | assert result["ok"] and result["status_of_expense"] == "draft" |
| 267 | |
| 268 | row = expenses(data_dir)[0] |
| 269 | assert row["description"] == "BLUE BOTTLE COFFEE" |
| 270 | assert row["incurred_on"] == "2026-06-15" |
| 271 | assert row["amount_cents"] == "899" |
| 272 | assert row["receipt_ref"] == f"scans/{scan_id}" |
| 273 | assert row["status"] == "draft" # still faces the approval gate |
| 274 | assert scan(data_dir, scan_id)["confirmed_record"] == f"expenses/{row['id']}" |
| 275 | |
| 276 | |
| 277 | def test_one_scan_one_record_however_many_clicks(tmp_path, monkeypatch): |
| 278 | data_dir = setup_env(tmp_path, monkeypatch) |
| 279 | scan_id = ingest()["scan_id"] |
| 280 | run("system_scan_processor") |
| 281 | confirm({"scan_id": scan_id}) |
| 282 | again = confirm({"scan_id": scan_id}) |
| 283 | assert again["duplicate"] is True |
| 284 | assert len(expenses(data_dir)) == 1 |
| 285 | |
| 286 | |
| 287 | def test_what_a_person_types_beats_what_the_machine_read(tmp_path, monkeypatch): |
| 288 | """The point of confirmation is that somebody is looking at the image |
| 289 | while they do it.""" |
| 290 | data_dir = setup_env(tmp_path, monkeypatch) |
| 291 | scan_id = ingest()["scan_id"] |
| 292 | run("system_scan_processor") |
| 293 | confirm({"scan_id": scan_id, "amount_cents": "1079", |
| 294 | "description": "Coffee with the Acme team"}) |
| 295 | |
| 296 | row = expenses(data_dir)[0] |
| 297 | assert row["amount_cents"] == "1079" |
| 298 | assert row["description"] == "Coffee with the Acme team" |
| 299 | |
| 300 | |
| 301 | def test_an_unread_document_asks_for_the_amount_rather_than_posting_zero( |
| 302 | tmp_path, monkeypatch): |
| 303 | data_dir = setup_env(tmp_path, monkeypatch) |
| 304 | scan_id = ingest_bytes()["scan_id"] |
| 305 | run("system_scan_processor") |
| 306 | |
| 307 | result = confirm({"scan_id": scan_id}) |
| 308 | assert result["status"] == 400 and "type it in from the image" in result["error"] |
| 309 | assert expenses(data_dir) == [] |
| 310 | |
| 311 | |
| 312 | def test_preview_shows_the_draft_without_writing_it(tmp_path, monkeypatch): |
| 313 | data_dir = setup_env(tmp_path, monkeypatch) |
| 314 | scan_id = ingest()["scan_id"] |
| 315 | run("system_scan_processor") |
| 316 | |
| 317 | result = confirm({"scan_id": scan_id, "preview": "true"}) |
| 318 | assert result["would_create"]["amount_cents"] == "899" |
| 319 | assert expenses(data_dir) == [] |
| 320 | assert scan(data_dir, scan_id)["status"] == "extracted" |
| 321 | |
| 322 | |
| 323 | def test_confirmed_evidence_is_closed(tmp_path, monkeypatch): |
| 324 | """Correct the expense, not the record of what arrived.""" |
| 325 | data_dir = setup_env(tmp_path, monkeypatch) |
| 326 | scan_id = ingest()["scan_id"] |
| 327 | run("system_scan_processor") |
| 328 | confirm({"scan_id": scan_id}) |
| 329 | |
| 330 | # `locked_when` on status=confirmed, not a hook: every writer, and delete. |
| 331 | with pytest.raises(object_records.RecordLockedError) as refused: |
| 332 | object_records.update_collection_record( |
| 333 | "scans", scan_id, {"ocr_text": "something else"}, base_dir=data_dir) |
| 334 | assert "not the evidence" in str(refused.value) |
| 335 | with pytest.raises(object_records.RecordLockedError): |
| 336 | object_records.delete_collection_record("scans", scan_id, base_dir=data_dir) |
| 337 | object_records.update_collection_record( |
| 338 | "scans", scan_id, {"notes": "still fine"}, base_dir=data_dir) |
| 339 | |
| 340 | |
| 341 | def test_confirming_a_scan_that_does_not_exist_says_so(tmp_path, monkeypatch): |
| 342 | setup_env(tmp_path, monkeypatch) |
| 343 | assert confirm({"scan_id": "nope"})["status"] == 404 |
| 344 | assert confirm({})["status"] == 400 |
| 345 | |
| 346 | |
| 347 | # --- the door (0.3.0) -------------------------------------------------------- |
| 348 | # |
| 349 | # system_scan_processor has returned a key called `needing_a_human` since |
| 350 | # the day it was written, and 0.2.0 finally put that number on the home |
| 351 | # page -- pointing at /scans?status=extracted, which nothing on the box |
| 352 | # served. The most valuable queue here was a dead link for a whole |
| 353 | # version. These tests are about the page, not the reading: that the |
| 354 | # count opens something, that what it opens lists scans, and that the |
| 355 | # page makes no promise the generic renderer cannot keep. |
| 356 | |
| 357 | import csv # noqa: E402 (structural tests below; the behavior tests above need none) |
| 358 | |
| 359 | import object_packages # noqa: E402 |
| 360 | import object_site_routes # noqa: E402 |
| 361 | |
| 362 | APP_INTAKE_DIR = PACKAGES / "app-intake" |
| 363 | |
| 364 | |
| 365 | def _intake_seed_rows(name): |
| 366 | with open(APP_INTAKE_DIR / "seed" / f"{name}.tsv", newline="") as handle: |
| 367 | return list(csv.DictReader(handle, delimiter="\t")) |
| 368 | |
| 369 | |
| 370 | def test_the_scans_index_is_a_seeded_view_and_not_a_page_object(): |
| 371 | package = object_packages.get_package("app-intake", root=PACKAGES) |
| 372 | |
| 373 | assert [entry["id"] for entry in package["objects"] |
| 374 | if entry["id"].startswith("site_")] == [] |
| 375 | assert {entry["collection"] for entry in package["seed"]} == { |
| 376 | "scans", "views", "site_routes"} |
| 377 | # Rows seeded into app-views' shared collections need app-views' schema |
| 378 | # to have landed first -- a real install-order dependency. |
| 379 | assert "app-views" in {entry["id"] for entry in package["dependencies"]} |
| 380 | |
| 381 | |
| 382 | def test_the_index_lists_scans_and_offers_no_form_that_could_not_work(): |
| 383 | rows = [row for row in _intake_seed_rows("views") if row["id"] == "view_scans"] |
| 384 | assert len(rows) == 1 |
| 385 | view = rows[0] |
| 386 | assert view["route"] == "/scans" |
| 387 | blocks = json.loads(view["blocks"]) |
| 388 | assert len(blocks) == 1 |
| 389 | block = blocks[0] |
| 390 | assert block["kind"] == "list" |
| 391 | assert block["collection"] == "scans" |
| 392 | # No Add button: a scan is bytes plus a hash raised by action_scan_ingest. |
| 393 | # A form that let somebody type a filename would create a row with no |
| 394 | # document behind it, which the processor would then try to read. |
| 395 | assert "add" not in block |
| 396 | # No /scans/{id} permalink is seeded, so a row must not behave like a link |
| 397 | # to one. |
| 398 | assert block["link"] is False |
| 399 | |
| 400 | |
| 401 | def test_the_index_route_resolves_to_the_generic_renderer(): |
| 402 | rows = _intake_seed_rows("site_routes") |
| 403 | assert len(rows) == 1 |
| 404 | assert rows[0]["pattern"] == "/scans" |
| 405 | assert rows[0]["object_id"] == "site_view_render" |
| 406 | # Convention routing wins over seeded records, so a site_scans object |
| 407 | # would silently shadow this page. There isn't one, and this is where |
| 408 | # somebody finds out if that changes. |
| 409 | assert object_site_routes.convention_object_id("/scans") == "site_scans" |
| 410 | |
| 411 | |
| 412 | def test_the_receipts_queue_now_has_a_door_of_its_own(): |
| 413 | """The manifest used to say, in as many words, that this package ships |
| 414 | no door and the count files under Money anyway. It ships one now.""" |
| 415 | package = object_packages.get_package("app-intake", root=PACKAGES) |
| 416 | entry = package["nav"][0] |
| 417 | |
| 418 | assert entry["id"] == "scans" |
| 419 | assert entry["path"] == "/scans" |
| 420 | assert entry["group"] == "Money" |
| 421 | assert entry["surface"] == "member" |
| 422 | assert entry["blurb"] |
| 423 | |
| 424 | |
| 425 | def test_the_count_opens_the_index_rather_than_a_filter_nothing_honours(): |
| 426 | package = object_packages.get_package("app-intake", root=PACKAGES) |
| 427 | source = package["attention"][0] |
| 428 | |
| 429 | assert source["path"] == "/scans" |
| 430 | assert "?" not in source["path"] |
| 431 | assert source["nav_id"] == "scans" |
| 432 | # The status filter is real, it just lives on the page: the generic list |
| 433 | # builds its filter bar from the schema, and `extracted` -- the exact |
| 434 | # status the declared count counts -- is one pick away in it. |
| 435 | schema = json.loads((APP_INTAKE_DIR / "schemas" / "scans.json").read_text()) |
| 436 | assert "status" in schema["views"]["filter_fields"] |
| 437 | assert source["collection"] == "scans" |
| 438 | assert json.loads(source["where"]) == {"status": "extracted"} |