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_locked_checks.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, 19 minutes ago History
test_locked_checks.py · 25.4 KB · 564 lines
1"""Schema `locked_checks`: a read-only check object_records calls inside the
2write lock, for every writer, with the collections it reads held still.
3
4The platform half of the payments/refunds ceilings
5(tests/test_money_gates_locked_ceilings.py is the money half). Everything
6here runs against a toy package written into tmp_path, so what is pinned is
7the mechanism, not app-payments:
8
9 budgets (id, cap, spent = rollup sum of spends, tag_count = rollup count of tags)
10 spends (id, budget_id, amount) check "within_cap" reads budgets lock "budget"
11 budgets check "cap_covers" reads spends lock "budget"
12 tags (id, budget_id) check "few_tags" reads budgets lock "tagging"
13
14so a write to budgets takes two check locks (budget, tagging), a write to
15tags takes both as well (its own, plus its rollup parent's), and a spend
16takes one -- the shapes a lock order has to get right.
17
18What is claimed, each against the files:
19
20 * every writer meets the check: storage-level creates, updates, deletes,
21 selected by `on`, refused before anything is written or logged;
22 * a check fails closed: it raises, says 503, answers outside its contract,
23 is not installed, or tries to write or run an object -- nothing lands;
24 * what it reads cannot move under it: a write to a `reads` collection
25 waits for the check's write to finish;
26 * no deadlock: separate processes writing every collection in random
27 order, rollups included, all finish and leave every invariant true;
28 * the rest of the platform does not route around it: retention refuses
29 a covered collection, and a package's seed rows are each checked.
30"""
31
32import json
33import os
34import subprocess
35import sys
36import threading
37import time
38from pathlib import Path
39
40import pytest
41
42import object_packages
43import object_records
44import object_record_changes
45import object_schemas
46
47REPO_ROOT = Path(__file__).resolve().parents[1]
48
49CHECKS = '''\
50import time
51import object_records
52
53
54def _sum(base, collection, field, key, value):
55 return sum(int(row.get(field) or 0)
56 for row in object_records.read_collection_records(collection, base_dir=base)
57 if row.get(key) == value)
58
59
60def LOCKED_CHECK(request):
61 """spends: what a budget has spent stays within its cap."""
62 record, base = request["record"], request["base_dir"]
63 if request["action"] == "delete":
64 return None
65 budget = object_records.get_collection_record("budgets", record["budget_id"], base_dir=base)
66 others = sum(int(row.get("amount") or 0)
67 for row in object_records.read_collection_records("spends", base_dir=base)
68 if row.get("budget_id") == record["budget_id"] and row["id"] != record["id"])
69 if others + int(record["amount"]) > int(budget["cap"]):
70 return {"error": f"over the cap of {budget['cap']} ({others} already spent)"}
71 return None
72
73
74def CAP_COVERS(request):
75 """budgets: a cap is never lowered below what has been spent."""
76 if request["action"] == "delete":
77 return None
78 record, base = request["record"], request["base_dir"]
79 spent = _sum(base, "spends", "amount", "budget_id", record["id"])
80 if int(record.get("cap") or 0) < spent:
81 return {"error": f"{spent} is already spent", "status": 409}
82 return None
83
84
85def FEW_TAGS(request):
86 if request["action"] != "create":
87 return None
88 record, base = request["record"], request["base_dir"]
89 object_records.get_collection_record("budgets", record["budget_id"], base_dir=base)
90 count = sum(1 for row in object_records.read_collection_records("tags", base_dir=base)
91 if row.get("budget_id") == record["budget_id"])
92 if count >= 5:
93 return {"error": "five tags is enough"}
94 return None
95
96
97def RAISES(request):
98 raise OSError("simulated: budgets is unreadable")
99
100
101def SAYS_UNAVAILABLE(request):
102 return {"error": "budgets could not be read", "status": 503}
103
104
105def ANSWERS_NONSENSE(request):
106 return {"record": request["record"]}
107
108
109def SAYS_OK(request):
110 return {"ok": True}
111
112
113def WRITES(request):
114 object_records.create_collection_record(
115 "tags", {"id": "smuggled", "budget_id": request["record"]["budget_id"]},
116 base_dir=request["base_dir"])
117 return None
118
119
120def RUNS_AN_OBJECT(request):
121 import object_execution, python_object_runtime
122 object_execution.execute_object(python_object_runtime.PythonObjectRuntime(),
123 object_execution.ObjectExecutionRequest("hook_checks"))
124 return None
125
126
127def SLOW(request):
128 import pathlib
129 started = pathlib.Path(request["base_dir"]) / "check-started"
130 started.write_text("1")
131 time.sleep(0.4)
132 return LOCKED_CHECK(request)
133'''
134
135
136def _schema(name, fields, **extra):
137 return {"name": name, "version": 1, "storage": "append",
138 "fields": [{"name": "id"}, *fields], **extra}
139
140
141def toy(tmp_path, monkeypatch, *, spends_check=None):
142 """A data dir with the toy schemas and an object root with the checks."""
143 data = tmp_path / "data"
144 objects = tmp_path / "objects"
145 (objects / "hook").mkdir(parents=True)
146 (objects / "hook" / "checks.py").write_text(CHECKS)
147 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data))
148 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects))
149 monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False)
150 within_cap = {"name": "within_cap", "object": "hook_checks", "reads": ["budgets"],
151 "lock": "budget", "on": {"update": ["amount", "budget_id"], "delete": False},
152 **(spends_check or {})}
153 schemas = [
154 _schema("budgets", [
155 {"name": "cap", "type": "integer"},
156 {"name": "spent", "type": "computed",
157 "rollup": {"collection": "spends", "fk_field": "budget_id", "op": "sum",
158 "field": "amount"}},
159 {"name": "tag_count", "type": "computed",
160 "rollup": {"collection": "tags", "fk_field": "budget_id", "op": "count"}},
161 ], locked_checks=[{"name": "cap_covers", "object": "hook_checks", "function": "CAP_COVERS",
162 "reads": ["spends"], "lock": "budget", "on": {"update": ["cap"]}}]),
163 _schema("spends", [{"name": "budget_id"}, {"name": "amount", "type": "integer"}],
164 locked_checks=[within_cap]),
165 _schema("tags", [{"name": "budget_id"}],
166 locked_checks=[{"name": "few_tags", "object": "hook_checks",
167 "function": "FEW_TAGS", "reads": ["budgets"], "lock": "tagging"}]),
168 _schema("memos", [{"name": "text"}]),
169 ]
170 for schema in schemas:
171 object_schemas.replace_schema(schema["name"], schema, base_dir=data)
172 # Past the schema index's 50 ms "changed a moment ago" margin, so writes
173 # use the kept index (the path production takes) rather than the scan.
174 time.sleep(0.06)
175 for budget_id, cap in (("b1", 1000), ("b2", 500)):
176 object_records.create_collection_record("budgets", {"id": budget_id, "cap": str(cap)},
177 base_dir=data, actor="test")
178 return data, objects
179
180
181def spend(data, spend_id, amount, budget_id="b1"):
182 return object_records.create_collection_record(
183 "spends", {"id": spend_id, "budget_id": budget_id, "amount": str(amount)},
184 base_dir=data, actor="test")
185
186
187def spent(data, budget_id="b1"):
188 return sum(int(row["amount"]) for row in object_records.read_collection_records(
189 "spends", base_dir=data) if row["budget_id"] == budget_id)
190
191
192# --- the declaration --------------------------------------------------------------
193
194
195def test_a_declaration_normalizes_to_its_canonical_form():
196 normalized = object_schemas.normalize_schema("spends", {
197 "name": "spends", "fields": [{"name": "id"}],
198 "locked_checks": [{"object": "hook_checks", "reads": ["budgets", "budgets", "a"]}]})
199 assert normalized["locked_checks"] == [{
200 "name": "hook_checks", "object": "hook_checks", "function": "LOCKED_CHECK",
201 "reads": ["a", "budgets"], "lock": "spends",
202 "on": {"create": True, "delete": True, "update": True}}]
203 # A stored (normalized) schema normalizes to itself.
204 again = object_schemas.normalize_schema("spends", normalized)
205 assert again["locked_checks"] == normalized["locked_checks"]
206
207
208@pytest.mark.parametrize("entry,complaint", [
209 ("hook_checks", "must be an object"),
210 ({"object": "hook_checks", "read": ["x"]}, "unknown keys: read"),
211 ({"reads": ["x"]}, "'object'"),
212 ({"object": "hook_checks", "function": "BEFORE_WRITE"}, "may not be BEFORE_WRITE"),
213 ({"object": "hook_checks", "function": "POST"}, "may not be POST"),
214 ({"object": "hook_checks", "reads": "budgets"}, "'reads'"),
215 ({"object": "hook_checks", "reads": ["bad name"]}, "'reads'"),
216 ({"object": "hook_checks", "lock": "Ledger"}, "'lock'"),
217 ({"object": "hook_checks", "on": {"insert": True}}, "unknown keys: insert"),
218 ({"object": "hook_checks", "on": {"update": []}}, "'on.update'"),
219 ({"object": "hook_checks", "on": {"create": False, "update": False, "delete": False}},
220 "selects no write"),
221])
222def test_an_unenforceable_declaration_is_refused_rather_than_loaded_as_no_check(entry, complaint):
223 with pytest.raises(ValueError, match=complaint):
224 object_schemas.normalize_schema("spends", {"name": "spends", "fields": [{"name": "id"}],
225 "locked_checks": [entry]})
226
227
228def test_two_checks_may_not_share_a_name():
229 with pytest.raises(ValueError, match="two checks are named"):
230 object_schemas.normalize_schema("spends", {"name": "spends", "fields": [{"name": "id"}],
231 "locked_checks": [{"object": "hook_a"},
232 {"object": "hook_a"}]})
233
234
235# --- every writer meets it --------------------------------------------------------
236
237
238def test_a_storage_level_write_is_checked_and_a_refusal_writes_and_logs_nothing(
239 tmp_path, monkeypatch):
240 data, _ = toy(tmp_path, monkeypatch)
241 spend(data, "s1", 600)
242
243 with pytest.raises(object_records.CheckRefusedError) as refused:
244 spend(data, "s2", 500)
245 assert (refused.value.status, refused.value.code, refused.value.check) == (
246 409, "check_refused", "within_cap")
247 assert "over the cap of 1000 (600 already spent)" in str(refused.value)
248 assert [row["id"] for row in object_records.read_collection_records("spends", base_dir=data)] \
249 == ["s1"]
250 assert not object_record_changes.list_record_changes("spends", record_id="s2", base_dir=data)["changes"]
251 spend(data, "s3", 400)
252 assert spent(data) == 1000
253 assert object_records.get_collection_record("budgets", "b1", base_dir=data)["spent"] == "1000"
254
255
256def test_on_selects_which_writes_call_the_check(tmp_path, monkeypatch):
257 data, objects = toy(tmp_path, monkeypatch)
258 spend(data, "s1", 900)
259 calls = objects / "calls"
260 (objects / "hook" / "checks.py").write_text(CHECKS + f'''
261_real = LOCKED_CHECK
262def LOCKED_CHECK(request):
263 with open({str(calls)!r}, "a") as out:
264 out.write(request["action"] + "\\n")
265 return _real(request)
266''')
267
268 object_records.update_collection_record("spends", "s1", {"note": "x"}, base_dir=data)
269 object_records.delete_collection_record("spends", "s1", base_dir=data)
270 assert not calls.exists() # an unlisted field; on.delete false
271 spend(data, "s2", 100)
272 object_records.update_collection_record("spends", "s2", {"amount": "200"}, base_dir=data)
273 assert calls.read_text().split() == ["create", "update"]
274
275
276def test_an_update_is_judged_against_the_row_under_the_lock(tmp_path, monkeypatch):
277 data, _ = toy(tmp_path, monkeypatch)
278 spend(data, "s1", 400)
279 spend(data, "s2", 400)
280 with pytest.raises(object_records.CheckRefusedError):
281 object_records.update_collection_record("spends", "s1", {"amount": "700"}, base_dir=data)
282 object_records.update_collection_record("spends", "s1", {"amount": "600"}, base_dir=data)
283 assert spent(data) == 1000
284 # A check declared on a collection a check READS: the cap cannot be cut
285 # below what is spent, whoever writes it.
286 with pytest.raises(object_records.CheckRefusedError, match="1000 is already spent"):
287 object_records.update_collection_record("budgets", "b1", {"cap": "900"}, base_dir=data)
288
289
290# --- it fails closed ----------------------------------------------------------------
291
292
293@pytest.mark.parametrize("function,status,code", [
294 ("RAISES", 503, "check_unavailable"),
295 ("SAYS_UNAVAILABLE", 503, "check_unavailable"),
296 ("ANSWERS_NONSENSE", 500, "check_failed"),
297 ("SAYS_OK", 500, "check_failed"),
298 ("WRITES", 500, "check_failed"),
299 ("RUNS_AN_OBJECT", 500, "check_failed"),
300 ("NOT_THERE", 503, "check_unavailable"),
301])
302def test_a_check_that_cannot_decide_refuses(tmp_path, monkeypatch, function, status, code):
303 data, _ = toy(tmp_path, monkeypatch, spends_check={"function": function})
304 with pytest.raises(object_records.CheckRefusedError) as refused:
305 spend(data, "s1", 1)
306 assert (refused.value.status, refused.value.code) == (status, code), str(refused.value)
307 assert object_records.read_collection_records("spends", base_dir=data) == []
308 assert object_records.read_collection_records("tags", base_dir=data) == []
309 assert object_records.in_locked_check() is None
310
311
312def test_a_check_object_that_is_not_installed_refuses(tmp_path, monkeypatch):
313 data, objects = toy(tmp_path, monkeypatch)
314 (objects / "hook" / "checks.py").unlink()
315 with pytest.raises(object_records.CheckRefusedError) as refused:
316 spend(data, "s1", 1)
317 assert refused.value.status == 503 and "not installed" in str(refused.value)
318 assert object_records.read_collection_records("spends", base_dir=data) == []
319
320
321# --- what it reads cannot move under it ----------------------------------------------
322
323
324def test_a_write_to_a_collection_the_check_reads_waits_for_the_checked_write(
325 tmp_path, monkeypatch):
326 """A spend of 900 is checked (slowly) against a 1000 cap; while the
327 check runs, another thread cuts the cap to 500. The cut cannot land
328 between the check's read and the spend's append: it waits, and is then
329 judged against the spend that landed (and refused)."""
330 data, _ = toy(tmp_path, monkeypatch, spends_check={"function": "SLOW"})
331 started = data / "check-started"
332 outcome = {}
333
334 def cut():
335 deadline = time.monotonic() + 5
336 while not started.exists() and time.monotonic() < deadline:
337 time.sleep(0.005)
338 begun = time.monotonic()
339 try:
340 object_records.update_collection_record("budgets", "b1", {"cap": "500"}, base_dir=data)
341 outcome["cut"] = "landed"
342 except object_records.CheckRefusedError as exc:
343 outcome["cut"] = str(exc)
344 outcome["waited"] = time.monotonic() - begun
345
346 worker = threading.Thread(target=cut)
347 worker.start()
348 spend(data, "s1", 900)
349 worker.join(timeout=10)
350
351 assert outcome["waited"] > 0.2, outcome
352 assert "900 is already spent" in outcome["cut"], outcome
353 assert object_records.get_collection_record("budgets", "b1", base_dir=data)["cap"] == "1000"
354
355
356def test_a_busy_check_lock_is_a_503_after_its_timeout_not_a_hang(tmp_path, monkeypatch):
357 data, _ = toy(tmp_path, monkeypatch)
358 monkeypatch.setenv(object_records.CHECK_LOCK_TIMEOUT_ENV, "0.2")
359 result = {}
360 with object_records._check_locks(["budget"], base_dir=data, collection="test"):
361 worker = threading.Thread(target=lambda: result.update(
362 outcome=_attempt(lambda: spend(data, "s1", 1))))
363 worker.start()
364 worker.join(timeout=10)
365 assert result["outcome"] == (503, "check_unavailable"), result
366 spend(data, "s1", 1)
367
368
369def _attempt(write):
370 try:
371 write()
372 except object_records.CheckRefusedError as exc:
373 return exc.status, exc.code
374 return "landed"
375
376
377def test_a_check_lock_is_never_waited_for_under_a_file_lock(tmp_path, monkeypatch):
378 """The order rule, enforced: a thread that holds a collection's file
379 lock and asks for a check lock it does not hold is refused, never made
380 to wait (that wait is the half of a deadlock this design rules out)."""
381 data, _ = toy(tmp_path, monkeypatch)
382 path = object_records.collection_records_file("memos", base_dir=data)
383 with object_records._records_file_lock(path):
384 with pytest.raises(object_records.CheckLockOrderError):
385 with object_records._check_locks(["budget"], base_dir=data, collection="spends"):
386 pass
387 # Held already is fine (a rollup refresh nested in a write).
388 with object_records._check_locks(["budget"], base_dir=data, collection="spends"):
389 with object_records._records_file_lock(path):
390 with object_records._check_locks(["budget"], base_dir=data, collection="budgets"):
391 pass
392
393
394def test_a_rollup_refresh_runs_under_the_locks_its_write_planned(tmp_path, monkeypatch):
395 """tags is guarded by "tagging"; its rollup parent budgets by "budget"
396 and "tagging". A tag write takes both up front, so the refresh of
397 budgets.tag_count nested inside it finds them held -- the count is
398 right, which it would not be if the nested write had been refused."""
399 data, _ = toy(tmp_path, monkeypatch)
400 for n in range(3):
401 object_records.create_collection_record("tags", {"id": f"t{n}", "budget_id": "b1"},
402 base_dir=data)
403 budget = object_records.get_collection_record("budgets", "b1", base_dir=data)
404 assert budget["tag_count"] == "3"
405 locks, _parents = object_records._write_plan("tags", base_dir=data, roots=None)
406 assert locks == ("budget", "tagging")
407
408
409def test_an_unrelated_schema_that_does_not_load_keeps_the_plan_and_the_refresh(tmp_path, monkeypatch):
410 """With a broken schema file nothing is indexed and the write plans from
411 the scan. The scan skips the broken file (it used to raise after the
412 row had landed), so the plan still names budgets as the parent and
413 takes its "budget" lock, and the nested refresh runs under it."""
414 data, _ = toy(tmp_path, monkeypatch)
415 (data / "schemas" / "scratch_things.json").write_text("{ this is not json")
416 assert object_records._schema_write_indexes(data, None) is None
417 locks, parents = object_records._write_plan("tags", base_dir=data, roots=None)
418 assert locks == ("budget", "tagging")
419 assert [name for name, _specs in parents] == ["budgets"]
420 object_records.create_collection_record("tags", {"id": "t0", "budget_id": "b1"}, base_dir=data)
421 budget = object_records.get_collection_record("budgets", "b1", base_dir=data)
422 assert budget["tag_count"] == "1"
423
424
425_WORKER = """\
426import os, random, sys, time
427repo, data, objects, who, ops, barrier = sys.argv[1:7]
428sys.path.insert(0, repo)
429os.environ["DBBASIC_DATA_DIR"] = data
430os.environ["DBBASIC_OBJECTS_DIR"] = objects
431import object_records
432random.seed(who)
433while not os.path.exists(barrier):
434 time.sleep(0.001)
435done = refused = 0
436for n in range(int(ops)):
437 budget = random.choice(("b1", "b2"))
438 kind = random.choice(("spend", "spend", "respend", "cap", "tag", "memo", "unspend"))
439 try:
440 if kind == "spend":
441 object_records.create_collection_record(
442 "spends", {"id": f"{who}-{n}", "budget_id": budget,
443 "amount": str(random.choice((30, 70, 110)))}, base_dir=data)
444 elif kind == "respend":
445 mine = [r for r in object_records.read_collection_records("spends", base_dir=data)
446 if r["id"].startswith(who)]
447 if mine:
448 object_records.update_collection_record(
449 "spends", random.choice(mine)["id"],
450 {"amount": str(random.choice((10, 150)))}, base_dir=data)
451 elif kind == "unspend":
452 mine = [r for r in object_records.read_collection_records("spends", base_dir=data)
453 if r["id"].startswith(who)]
454 if mine:
455 object_records.delete_collection_record("spends", random.choice(mine)["id"],
456 base_dir=data)
457 elif kind == "cap":
458 object_records.update_collection_record(
459 "budgets", budget, {"cap": str(random.choice((300, 600, 900, 1200)))}, base_dir=data)
460 elif kind == "tag":
461 object_records.create_collection_record(
462 "tags", {"id": f"{who}-t{n}", "budget_id": budget}, base_dir=data)
463 else:
464 object_records.create_collection_record("memos", {"id": f"{who}-m{n}", "text": "x"},
465 base_dir=data)
466 done += 1
467 except object_records.CheckRefusedError as exc:
468 assert exc.status == 409, str(exc)
469 refused += 1
470print(done, refused)
471"""
472
473
474def test_processes_writing_every_collection_at_once_never_deadlock_and_keep_every_invariant(
475 tmp_path, monkeypatch):
476 """Six processes, eighty random writes each, over all four collections:
477 spends (lock budget; rollup into budgets), budgets (budget + tagging),
478 tags (tagging; rollup into budgets, so budget + tagging), memos (none).
479 Every process must finish -- a deadlock is a timeout here -- and the
480 files must say: no budget over its cap, no budget with more than five
481 tags, and the rollups equal to what they summarize."""
482 data, objects = toy(tmp_path, monkeypatch)
483 script = tmp_path / "_worker.py"
484 script.write_text(_WORKER)
485 barrier = tmp_path / "go"
486 running = [subprocess.Popen(
487 [sys.executable, str(script), str(REPO_ROOT), str(data), str(objects), f"w{p}", "80",
488 str(barrier)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
489 for p in range(6)]
490 time.sleep(0.5)
491 barrier.write_text("go")
492 totals = [0, 0]
493 try:
494 for process in running:
495 out, err = process.communicate(timeout=120)
496 assert process.returncode == 0, err
497 done, refused = map(int, out.split())
498 totals[0] += done
499 totals[1] += refused
500 finally:
501 for process in running:
502 if process.poll() is None:
503 process.kill()
504
505 assert totals[0] > 100 and totals[1] > 0, totals # it raced, and the checks said no
506 object_records._RECORDS_CACHE.clear()
507 spends = object_records.read_collection_records("spends", base_dir=data)
508 tags = object_records.read_collection_records("tags", base_dir=data)
509 for budget in object_records.read_collection_records("budgets", base_dir=data):
510 mine = sum(int(row["amount"]) for row in spends if row["budget_id"] == budget["id"])
511 count = sum(1 for row in tags if row["budget_id"] == budget["id"])
512 assert mine <= int(budget["cap"]), (budget, mine)
513 assert count <= 5, (budget, count)
514 assert budget["spent"] == str(mine) and budget["tag_count"] == str(count), budget
515
516
517# --- nothing routes around it ---------------------------------------------------------
518
519
520def test_retention_refuses_a_collection_a_check_guards_or_reads(tmp_path, monkeypatch):
521 data, _ = toy(tmp_path, monkeypatch)
522 spend(data, "s1", 1)
523 for collection in ("spends", "budgets", "tags"):
524 with pytest.raises(ValueError, match="locked check"):
525 object_records.prune_collection_records(collection, keep_newer_than="2999-01-01",
526 base_dir=data)
527 object_records.prune_collection_records("memos", keep_newer_than="2999-01-01", base_dir=data)
528
529
530def test_a_fresh_seed_of_a_checked_collection_is_written_row_by_row(tmp_path, monkeypatch):
531 """A seed file is normally copied whole into a collection that has no
532 records yet. Into a collection with locked checks, each row is a write
533 the checks decide: here the third seeded spend would take b1 past its
534 cap and is refused, and the install says so."""
535 data, objects = toy(tmp_path, monkeypatch)
536 package = tmp_path / "packages" / "toy-spends"
537 (package / "seed").mkdir(parents=True)
538 (package / "schemas").mkdir()
539 (package / "objects" / "hook").mkdir(parents=True)
540 (package / "objects" / "hook" / "checks.py").write_text(CHECKS)
541 spends_schema = object_schemas.get_schema("spends", base_dir=data)
542 # A stored schema carries what the normalizer adds (`source`,
543 # `field_count`); a package declaration is DRON, which has neither.
544 spends_schema = {k: v for k, v in spends_schema.items() if k not in ("source", "field_count")}
545 (package / "schemas" / "spends.json").write_text(json.dumps(spends_schema))
546 (package / "seed" / "spends.tsv").write_text(
547 "id\tbudget_id\tamount\nseed1\tb1\t600\nseed2\tb1\t300\nseed3\tb1\t200\n")
548 (package / "dbbasic-package.json").write_text(json.dumps({
549 "id": "toy-spends", "name": "Toy", "version": "0.1.0", "description": "test",
550 "compatibility": {"dbbasic_object_server": ">=0.1.0"}, "dependencies": [],
551 "objects": [{"id": "hook_checks", "path": "objects/hook/checks.py"}],
552 "schemas": [{"collection": "spends", "path": "schemas/spends.json"}],
553 "permissions": [], "seed": [{"collection": "spends", "path": "seed/spends.tsv"}],
554 "migrations": []}))
555 (data / "schemas" / "spends.json").unlink() # the package installs it fresh
556
557 result = object_packages.install_package("toy-spends", root=tmp_path / "packages",
558 base_dir=data, object_roots=[objects],
559 allow_replace=True, force=True)
560
561 (seed,) = result["seed"]
562 assert seed["added"] == 2 and [row["id"] for row in seed["rejected"]] == ["seed3"], seed
563 assert seed["rejected"][0]["code"] == "check_refused"
564 assert spent(data) == 900