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_document_intake.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, 18 minutes ago History
test_document_intake.py · 17.0 KB · 438 lines
1"""Document intake: a machine reads, a person decides.
2
3The property this whole package exists to hold is that nothing an
4extractor produces ever reaches the books on its own. Everything else --
5dedup, engine choice, confidence -- is in service of that, and most of
6these tests are checking that a BAD reading is merely inconvenient rather
7than wrong.
8"""
9
10import base64
11import json
12import pathlib
13
14import pytest
15
16from conftest import stage_collection
17
18import object_execution
19import object_intake
20import object_records
21import python_object_runtime
22
23REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
24PACKAGES = REPO_ROOT / "packages"
25INTAKE_OBJECTS = PACKAGES / "app-intake" / "objects"
26RUNTIME = python_object_runtime.PythonObjectRuntime()
27
28RECEIPT = """BLUE BOTTLE COFFEE
291234 Market St
3006/15/2026
31
32Latte 4.50
33Croissant 3.75
34Subtotal 8.25
35Tax 0.74
36TOTAL 8.99
37
38Suggested tip 20% 1.80
39"""
40
41
42def 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
53def 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
61def 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
68def 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
74def 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
81def scan(data_dir, scan_id):
82 return object_records.get_collection_record("scans", scan_id, base_dir=data_dir)
83
84
85def 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
91def 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
97def 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
102def 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
109def 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
116def 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
127def 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
137def 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
150def 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
160def 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
173def 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
181def 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
191def 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
203def 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
215def 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
230def 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
243def 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
250def 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
259def 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
277def 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
287def 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
301def 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
312def 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
323def 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
341def 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
357import csv # noqa: E402 (structural tests below; the behavior tests above need none)
358
359import object_packages # noqa: E402
360import object_site_routes # noqa: E402
361
362APP_INTAKE_DIR = PACKAGES / "app-intake"
363
364
365def _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
370def 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
382def 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
401def 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
412def 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
425def 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"}