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_package_recipes.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_package_recipes.py · 27.2 KB · 505 lines
1"""The worked recipes in docs/package-authoring.md run, and answer what the page says.
2
3The page builds a small `deals` package from JSON blocks marked
4`<!-- recipe: NAME -->` and then says what each recipe returns for ann, bob and
5carol. A recipe nobody ran is a recipe that rots, and these were written
6because a trial of the docs found people guessing. This test builds the package
7from those exact blocks (not from copies of them here), applies each recipe and
8checks the table the page prints: if a block stops working, or a stated answer
9stops being true, this fails and the page gets fixed with it.
10"""
11
12import json
13import re
14import shutil
15from pathlib import Path
16
17import pytest
18
19import object_packages
20from scripts.try_package import Sandbox
21
22ROOT = Path(__file__).resolve().parents[1]
23DOC = (ROOT / "docs" / "package-authoring.md").read_text(encoding="utf-8")
24BLOCK = re.compile(r"<!-- recipe: ([a-z-]+) -->\n```json\n(.*?)\n```", re.DOTALL)
25RECIPES = {name: json.loads(body) for name, body in BLOCK.findall(DOC)}
26PYTHON_BLOCK = re.compile(r"<!-- recipe: ([a-z-]+) -->\n```python\n(.*?)\n```", re.DOTALL)
27PYTHON_RECIPES = dict(PYTHON_BLOCK.findall(DOC))
28
29RECORDS = "/collections/deals/records"
30
31
32def test_every_recipe_block_the_page_promises_is_there():
33 assert set(RECIPES) == {
34 "deals-manifest", "deals-schema", "deals-rules", "deals-auditor-rule",
35 "deals-attention", "deals-assignee-rule", "deals-locked-when",
36 "deals-nav", "deals-close-date-manifest", "deals-close-date-field",
37 "deals-close-date-checks", "deals-follow-up-field", "deals-follow-up-check-entry",
38 "deals-type-schema", "deals-type-manifest", "deals-type-rule", "deals-type-fields",
39 "deals-type-keys",
40 }
41 assert set(PYTHON_RECIPES) == {"deals-close-check", "deals-follow-up-check", "upgrade-test",
42 "deals-type-hook"}
43
44
45def test_the_upgrade_test_recipe_runs_as_printed(tmp_path, monkeypatch):
46 """The page tells a newcomer to save this block as a pytest file and run it
47 from the repository root: run it exactly so."""
48 monkeypatch.chdir(ROOT)
49 namespace = {}
50 exec(compile(PYTHON_RECIPES["upgrade-test"], "upgrade-test", "exec"), namespace)
51 namespace["test_the_upgrade_keeps_old_rows_and_gives_new_rows_the_default"](tmp_path)
52
53
54def test_a_fragment_says_where_it_goes():
55 """The page promises that each fragment's sentence names its file and place."""
56 assert "**Append this object to the `rules` array** in `permissions/rules.json`" in DOC
57 assert "**Merge both keys into the top level of `dbbasic-package.json`**" in DOC
58 assert "**Merge that key into the top level of `schemas/deals.json`**" in DOC
59 assert "**1. `dbbasic-package.json`**" in DOC and "**2. `schemas/deals.json`**" in DOC
60
61
62def build(tmp_path, *, auditor=False, attention=False, locked=False, nav=False, close_check=False,
63 follow_up=False):
64 """The deals package as the page assembles it, with the chosen recipes applied."""
65 root = tmp_path / "packages"
66 shutil.copytree(ROOT / "packages" / "app-nav", root / "app-nav")
67 package = root / "deals"
68 (package / "schemas").mkdir(parents=True)
69 (package / "permissions").mkdir()
70 manifest = dict(RECIPES["deals-manifest"])
71 schema = json.loads(json.dumps(RECIPES["deals-schema"]))
72 rules = json.loads(json.dumps(RECIPES["deals-rules"]))
73 if auditor:
74 rules["rules"].append(RECIPES["deals-auditor-rule"])
75 if attention:
76 manifest.update(RECIPES["deals-attention"])
77 rules["rules"].append(RECIPES["deals-assignee-rule"])
78 if locked:
79 schema.update(RECIPES["deals-locked-when"])
80 if nav:
81 manifest.update(RECIPES["deals-nav"])
82 for entry in manifest["attention"]:
83 entry["nav_id"] = "deals" # the page says: add this to both entries
84 if close_check or follow_up:
85 manifest.update(RECIPES["deals-close-date-manifest"]) # merge into the top level
86 schema["fields"].append(RECIPES["deals-close-date-field"]) # append to `fields`
87 schema.update(json.loads(json.dumps(RECIPES["deals-close-date-checks"]))) # merge into the top level
88 source = PYTHON_RECIPES["deals-close-check"]
89 if follow_up:
90 schema["fields"].append(RECIPES["deals-follow-up-field"])
91 schema["locked_checks"].append(RECIPES["deals-follow-up-check-entry"])
92 source += "\n\n" + PYTHON_RECIPES["deals-follow-up-check"]
93 (package / "objects" / "hook").mkdir(parents=True)
94 (package / "objects" / "hook" / "deals.py").write_text(source + "\n")
95 (package / "dbbasic-package.json").write_text(json.dumps(manifest))
96 (package / "schemas" / "deals.json").write_text(json.dumps(schema))
97 (package / "permissions" / "rules.json").write_text(json.dumps(rules))
98 return root
99
100
101def create(box, who, title, **more):
102 status, body = box.call(who, "POST", RECORDS, {"title": title, "owner_id": who, **more})
103 assert status == 201, body
104 return body["record"]["id"]
105
106
107def test_the_base_package_lets_each_person_see_only_their_own_deals(tmp_path):
108 with Sandbox(["deals"], packages_dir=build(tmp_path)) as box:
109 box.add_user("ann")
110 box.add_user("bob")
111 create(box, "ann", "Ann one")
112 assert box.call("ann", "GET", RECORDS)[1]["total"] == 1
113 assert box.call("bob", "GET", RECORDS)[1]["total"] == 0
114
115
116def test_recipe_a_a_role_reads_every_row_while_only_owners_write(tmp_path):
117 with Sandbox(["deals"], packages_dir=build(tmp_path, auditor=True)) as box:
118 box.add_user("ann")
119 box.add_user("bob")
120 box.add_user("carol", roles=["auditor"])
121 ann_one = create(box, "ann", "Ann one")
122 create(box, "ann", "Ann two")
123 create(box, "bob", "Bob one")
124
125 assert box.call("ann", "GET", RECORDS)[1]["total"] == 2
126 assert box.call("bob", "GET", RECORDS)[1]["total"] == 1
127 status, body = box.call("carol", "GET", RECORDS)
128 assert (status, body["total"]) == (200, 3)
129
130 status, body = box.call("carol", "GET", RECORDS + "?limit=2&offset=2")
131 assert (status, body["count"], body["total"], body["has_more"]) == (200, 1, 3, False)
132 status, body = box.call("carol", "GET", RECORDS + "?owner_id=ann")
133 assert (status, body["total"]) == (200, 2)
134 status, body = box.call("carol", "GET", "/api/search?q=Ann&collections=deals")
135 assert status == 200 and len(body["results"]["deals"]) == 2
136
137 for who, method, payload in (("carol", "PUT", {"title": "x"}), ("carol", "DELETE", None),
138 ("bob", "PUT", {"title": "x"})):
139 status, body = box.call(who, method, f"{RECORDS}/{ann_one}", payload)
140 assert (status, body["error"]) == (403, "no matching role rule"), (who, method)
141
142 assert box.call("ann", "POST", RECORDS, {"title": "x", "owner_id": "ann"})[0] == 201
143 # Left out, owner_id is the caller's (stamped before the rule is asked).
144 status, body = box.call("ann", "POST", RECORDS, {"title": "x"})
145 assert (status, body["record"]["owner_id"]) == (201, "ann")
146 assert box.call("ann", "POST", RECORDS, {"title": "x", "owner_id": "bob"})[0] == 403
147
148
149def attention_for(box, who):
150 status, body = box.call(who, "GET", "/objects/action_nav_entries")
151 assert status == 200, body
152 return {row["id"]: row["count"] for row in body["attention"]}
153
154
155def test_recipe_b_a_count_over_rows_i_own_or_am_assigned_is_two_entries(tmp_path):
156 with Sandbox(["deals"], packages_dir=build(tmp_path, attention=True)) as box:
157 box.add_user("ann")
158 box.add_user("bob")
159 box.add_user("carol", roles=["auditor"])
160 create(box, "ann", "Ann one", assigned_to="bob")
161 create(box, "ann", "Ann two", assigned_to="bob")
162 create(box, "bob", "Bob one")
163
164 assert attention_for(box, "ann") == {"deals_i_own": 2}
165 assert attention_for(box, "bob") == {"deals_assigned_to_me": 2, "deals_i_own": 1}
166 assert attention_for(box, "carol") == {} # both queues are 0, and a zero is never shown
167
168
169def test_recipe_b_a_deal_owned_and_assigned_to_the_same_person_counts_once(tmp_path):
170 with Sandbox(["deals"], packages_dir=build(tmp_path, attention=True)) as box:
171 box.add_user("ann")
172 box.add_user("bob")
173 create(box, "bob", "Bob to himself", assigned_to="bob")
174 create(box, "ann", "Ann to bob", assigned_to="bob")
175 create(box, "bob", "Bob unassigned")
176 assert attention_for(box, "bob") == {"deals_assigned_to_me": 1, "deals_i_own": 2} # 3 deals, 3 counted
177 assert attention_for(box, "ann") == {"deals_i_own": 1}
178
179
180def test_recipe_b_without_the_assignee_read_rule_the_assignee_sees_zero(tmp_path):
181 """The page says the second queue needs its own read grant. Prove the
182 sentence by taking the grant away."""
183 root = build(tmp_path, attention=True)
184 rules_path = root / "deals" / "permissions" / "rules.json"
185 rules = json.loads(rules_path.read_text())
186 rules["rules"] = [rule for rule in rules["rules"] if "assigned_to" not in rule.get("row_filter", {})]
187 rules_path.write_text(json.dumps(rules))
188 with Sandbox(["deals"], packages_dir=root) as box:
189 box.add_user("ann")
190 box.add_user("bob")
191 create(box, "ann", "Ann one", assigned_to="bob")
192 assert attention_for(box, "bob") == {}
193
194
195def test_recipe_c_freeze_some_fields_once_settled(tmp_path):
196 with Sandbox(["deals"], packages_dir=build(tmp_path, locked=True)) as box:
197 box.add_user("ann")
198 deal = create(box, "ann", "Ann one", description="d", amount_cents="500")
199 path = f"{RECORDS}/{deal}"
200 assert box.call("ann", "PUT", path, {"title": "Ann 1"})[0] == 200 # open: nothing is frozen
201 assert box.call("ann", "PUT", path, {"status": "won"})[0] == 200
202
203 status, body = box.call("ann", "PUT", path, {"assigned_to": "carol"})
204 assert status == 200 # not a frozen field
205 status, body = box.call("ann", "PUT", path, {"title": "late"})
206 assert (status, body["code"], body["fields"]) == (409, "record_locked", ["title"])
207 assert body["error"].startswith("A settled deal's")
208 assert box.call("ann", "PUT", path, {"title": "Ann 1"})[0] == 200 # unchanged is not a change
209 status, body = box.call("ann", "DELETE", path)
210 assert (status, body["code"], body["fields"]) == (409, "record_locked", [])
211 assert box.call("admin", "PUT", path, {"title": "admin"})[0] == 409 # nobody is exempt
212 status, body = box.call("ann", "PUT", path, {"status": "open"})
213 assert status == 400 and "cannot move from 'won' to 'open' (allowed: none)" in body["error"]
214
215
216def test_recipe_c_a_field_added_later_is_free_under_fields_and_frozen_under_except(tmp_path):
217 root = build(tmp_path, locked=True)
218 schema_path = root / "deals" / "schemas" / "deals.json"
219 schema = json.loads(schema_path.read_text())
220 schema["fields"].append({"name": "region", "type": "text"})
221 schema["locked_when"][0]["fields"] = ["title"]
222 schema_path.write_text(json.dumps(schema))
223 with Sandbox(["deals"], packages_dir=root) as box:
224 box.add_user("ann")
225 deal = create(box, "ann", "x")
226 box.call("ann", "PUT", f"{RECORDS}/{deal}", {"status": "won"})
227 assert box.call("ann", "PUT", f"{RECORDS}/{deal}", {"region": "emea"})[0] == 200
228
229 schema["locked_when"] = [{"when": {"status": ["won", "lost"]}, "except": ["assigned_to"]}]
230 schema_path.write_text(json.dumps(schema))
231 with Sandbox(["deals"], packages_dir=root) as box:
232 box.add_user("ann")
233 deal = create(box, "ann", "x")
234 box.call("ann", "PUT", f"{RECORDS}/{deal}", {"status": "won"})
235 status, body = box.call("ann", "PUT", f"{RECORDS}/{deal}", {"region": "emea"})
236 assert (status, body["fields"]) == (409, ["region"])
237
238
239def test_recipe_d_add_a_field_and_show_it_in_the_list(tmp_path):
240 root = build(tmp_path)
241 with Sandbox(["deals"], packages_dir=root) as box:
242 box.add_user("ann")
243 old = create(box, "ann", "old")
244
245 schema_path = root / "deals" / "schemas" / "deals.json"
246 schema = json.loads(schema_path.read_text())
247 schema["fields"].append({"name": "priority", "type": "enum", "enum": ["low", "normal", "high"],
248 "default": "normal", "label": "Priority"})
249 schema["forms"]["default"]["fields"].append("priority")
250 schema["views"]["list_fields"].append("priority")
251 schema["version"] = 2
252 schema_path.write_text(json.dumps(schema))
253
254 with pytest.raises(object_packages.PackageInstallError, match="allow_replace"):
255 object_packages.install_package("deals", root=root, base_dir=box.data_dir,
256 object_roots=[box.objects_dir])
257 result = object_packages.install_package("deals", root=root, base_dir=box.data_dir,
258 object_roots=[box.objects_dir], allow_replace=True)
259 assert [(s["collection"], s["status"]) for s in result["schemas"]] == [("deals", "updated")]
260
261 status, body = box.call("ann", "GET", "/api/schema/deals")
262 names = [field["name"] for field in body["schema"]["fields"]]
263 assert "priority" in names and "priority" in body["schema"]["views"]["list_fields"]
264 assert "priority" in body["schema"]["forms"]["default"]["fields"]
265 assert "version" not in body["schema"] # the public view omits it
266 assert box.call("admin", "GET", "/schemas/deals")[1]["schema"]["version"] == 2
267
268 new = create(box, "ann", "new")
269 assert box.call("ann", "GET", f"{RECORDS}/{new}")[1]["record"]["priority"] == "normal"
270 assert not box.call("ann", "GET", f"{RECORDS}/{old}")[1]["record"].get("priority") # no backfill
271 status, body = box.call("ann", "GET", RECORDS + "?priority=normal")
272 assert [row["title"] for row in body["records"]] == ["new"]
273 status, body = box.call("ann", "POST", RECORDS, {"title": "x", "owner_id": "ann", "priority": "urgent"})
274 assert (status, body["error"]) == (400, "Record field 'priority' must be one of: low, normal, high")
275
276
277def doc_text_blocks():
278 return re.findall(r"```text\n(.*?)\n```", DOC, re.DOTALL)
279
280
281def test_the_seeded_view_and_route_examples_install_and_serve(tmp_path, monkeypatch):
282 """The "Seeded Views And Site Routes" section prints a views.tsv and a
283 site_routes.tsv for `deals`. They must pass the DRON checks, merge in on
284 install, and answer at their URLs once site routes are on."""
285 import csv
286 import io
287
288 from test_dron_schema import ROUTE_COLUMNS, _view_row_problems
289
290 routes_tsv, views_tsv = [b for b in doc_text_blocks() if b.startswith(("id\tpattern", "id\ttitle"))]
291 assert routes_tsv.startswith("id\tpattern") and views_tsv.startswith("id\ttitle")
292 views = list(csv.DictReader(io.StringIO(views_tsv), delimiter="\t"))
293 routes = list(csv.DictReader(io.StringIO(routes_tsv), delimiter="\t"))
294 assert [v["id"] for v in views] == ["view_deals", "view_deals_detail"]
295 for row in views:
296 assert not _view_row_problems(row), row["id"]
297 for row in routes:
298 assert set(row) <= ROUTE_COLUMNS
299 assert {r["pattern"] for r in routes} == {v["route"] for v in views} # the pairing the page demands
300
301 root = build(tmp_path)
302 shutil.copytree(ROOT / "packages" / "app-views", root / "app-views")
303 package = root / "deals"
304 (package / "seed").mkdir()
305 (package / "seed" / "views.tsv").write_text(views_tsv + "\n")
306 (package / "seed" / "site_routes.tsv").write_text(routes_tsv + "\n")
307 manifest = json.loads((package / "dbbasic-package.json").read_text())
308 manifest["dependencies"] = ["app-views"]
309 manifest["seed"] = [{"collection": "views", "path": "seed/views.tsv"},
310 {"collection": "site_routes", "path": "seed/site_routes.tsv"}]
311 (package / "dbbasic-package.json").write_text(json.dumps(manifest))
312
313 monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true")
314 with Sandbox(["deals"], packages_dir=root) as box:
315 assert box.installed == ["app-views", "deals"]
316 box.add_user("ann")
317 assert box.call("admin", "GET", "/collections/views/records")[1]["total"] == 2
318 route_ids = {r["id"] for r in box.call("admin", "GET", "/collections/site_routes/records")[1]["records"]}
319 assert {"route_deals", "route_deals_detail"} <= route_ids # beside the two app-views ships
320 status, body = box.call("ann", "GET", "/deals")
321 assert status == 200 and "const VIEW_ID = 'view_deals';" in body
322 status, body = box.call("ann", "GET", "/deals/some-deal-id")
323 assert status == 200 and "const VIEW_ID = 'view_deals_detail';" in body
324 assert "RECORD_ID = 'some-deal-id'" in body
325
326
327def test_recipe_b_two_queues_on_one_nav_entry_are_summed_into_its_badge(tmp_path):
328 """The page says a door's badge is the total of every queue naming it."""
329 with Sandbox(["deals"], packages_dir=build(tmp_path, attention=True, nav=True)) as box:
330 box.add_user("ann")
331 box.add_user("bob")
332 create(box, "ann", "Ann one", assigned_to="bob")
333 create(box, "ann", "Ann two", assigned_to="bob")
334 create(box, "bob", "Bob one")
335 for who, expected in (("ann", 2), ("bob", 3)):
336 status, body = box.call(who, "GET", "/objects/action_nav_entries")
337 door = {entry["id"]: entry for entry in body["entries"]}["deals"]
338 assert (status, door["count"]) == (200, expected), who
339
340
341def test_recipe_e_a_check_can_read_the_record_and_the_clock(tmp_path):
342 from datetime import date, timedelta
343 yesterday = (date.today() - timedelta(days=1)).isoformat()
344 tomorrow = (date.today() + timedelta(days=1)).isoformat()
345 with Sandbox(["deals"], packages_dir=build(tmp_path, close_check=True)) as box:
346 box.add_user("ann")
347 status, body = box.call("ann", "POST", RECORDS,
348 {"title": "late", "owner_id": "ann", "close_on": yesterday})
349 assert (status, body["code"], body["check"]) == (409, "check_refused", "close_date")
350 assert body["error"] == "A deal cannot close in the past."
351 deal = create(box, "ann", "ok", close_on=tomorrow)
352 assert box.call("ann", "PUT", f"{RECORDS}/{deal}", {"title": "renamed"})[0] == 200
353 status, body = box.call("ann", "PUT", f"{RECORDS}/{deal}", {"close_on": yesterday})
354 assert (status, body["code"]) == (409, "check_refused")
355 assert box.call("ann", "PUT", f"{RECORDS}/{deal}", {"close_on": tomorrow})[0] == 200
356 assert box.call("ann", "POST", RECORDS, {"title": "none", "owner_id": "ann"})[0] == 201
357
358
359def test_recipe_e_a_datetime_check_compares_aware_and_naive_values_in_utc(tmp_path):
360 from datetime import datetime, timedelta, timezone
361 now = datetime.now(timezone.utc)
362 past, future = now - timedelta(hours=1), now + timedelta(hours=1)
363 fmt = "%Y-%m-%dT%H:%M:%S"
364 with Sandbox(["deals"], packages_dir=build(tmp_path, follow_up=True)) as box:
365 box.add_user("ann")
366 for sent in (future.strftime(fmt) + "Z", # what the form sends
367 future.strftime(fmt), # naive: read as UTC
368 future.astimezone(timezone(timedelta(hours=2))).isoformat(), # aware, +02:00
369 future.isoformat().replace("+00:00", "Z")): # microseconds, Z
370 status, body = box.call("ann", "POST", RECORDS,
371 {"title": "ok", "owner_id": "ann", "follow_up_at": sent})
372 assert status == 201, (sent, body)
373 for sent in (past.strftime(fmt) + "Z", past.strftime(fmt),
374 past.astimezone(timezone(timedelta(hours=-5))).isoformat()):
375 status, body = box.call("ann", "POST", RECORDS,
376 {"title": "late", "owner_id": "ann", "follow_up_at": sent})
377 assert (status, body["code"], body["check"]) == (409, "check_refused", "follow_up"), sent
378 assert box.call("ann", "POST", RECORDS, {"title": "x", "owner_id": "ann"})[0] == 201 # optional
379 assert box.call("ann", "POST", RECORDS,
380 {"title": "x", "owner_id": "ann", "follow_up_at": "soon"})[0] == 400 # the platform's own check
381
382
383def test_recipe_e_a_stored_value_the_check_cannot_read_raises_so_the_write_fails_closed(tmp_path):
384 """The write validator keeps unparseable text out of the API, so an old row or an
385 import is how one reaches a check. The recipe lets the ValueError out; the platform
386 answers any exception from a check with 503 check_unavailable (tests/test_locked_checks.py,
387 the RAISES case)."""
388 root = build(tmp_path, follow_up=True)
389 hook = root / "deals" / "objects" / "hook" / "deals.py"
390 namespace = {}
391 exec(compile(hook.read_text(), str(hook), "exec"), namespace)
392 with pytest.raises(ValueError):
393 namespace["FOLLOW_UP_CHECK"]({"record": {"follow_up_at": "garbage"}})
394 assert namespace["FOLLOW_UP_CHECK"]({"record": {"follow_up_at": ""}}) is None
395
396
397def test_unique_is_case_sensitive_by_default_and_trims_edges_only(tmp_path):
398 """The page states this; ignore_case is the opt-in."""
399 for ignore_case in (False, True):
400 root = build(tmp_path / str(ignore_case))
401 path = root / "deals" / "schemas" / "deals.json"
402 schema = json.loads(path.read_text())
403 schema["unique"] = [{"fields": ["title"], **({"ignore_case": True} if ignore_case else {})}]
404 path.write_text(json.dumps(schema))
405 with Sandbox(["deals"], packages_dir=root) as box:
406 box.add_user("ann")
407 create(box, "ann", "Acme")
408 assert box.call("ann", "POST", RECORDS, {"title": "Acme ", "owner_id": "ann"})[0] == 409 # trimmed
409 assert box.call("ann", "POST", RECORDS, {"title": " Acme", "owner_id": "ann"})[0] == 409
410 assert box.call("ann", "POST", RECORDS, {"title": "Ac me", "owner_id": "ann"})[0] == 201 # inner space counts
411 lower = box.call("ann", "POST", RECORDS, {"title": "acme", "owner_id": "ann"})
412 assert lower[0] == (409 if ignore_case else 201)
413
414
415def test_a_required_field_must_be_in_every_create_payload_of_a_real_package():
416 """The page tells a newcomer to send `first_name` when creating a contact."""
417 with Sandbox(["app-contacts"]) as box:
418 box.add_user("ann")
419 path = "/collections/contacts/records"
420 status, body = box.call("ann", "POST", path, {"last_name": "Lee", "owner_id": "ann"})
421 assert (status, body["error"]) == (400, "Record field 'first_name' is required")
422 assert box.call("ann", "POST", path, {"first_name": "Ada", "owner_id": "ann"})[0] == 201
423
424
425def test_integers_and_booleans_come_back_as_strings_and_the_schema_says_which(tmp_path):
426 """The page says what a client should expect on the wire; this is the claim."""
427 with Sandbox(["deals"], packages_dir=build(tmp_path)) as box:
428 box.add_user("ann")
429 deal = create(box, "ann", "x", amount_cents=500) # a JSON number goes in
430 record = box.call("ann", "GET", f"{RECORDS}/{deal}")[1]["record"]
431 assert record["amount_cents"] == "500" # a string comes out
432 assert box.call("ann", "GET", RECORDS + "?amount_cents=500")[1]["total"] == 1
433 assert box.call("ann", "POST", RECORDS, {"title": "x", "owner_id": "ann",
434 "amount_cents": "5.5"})[0] == 400
435 types = {f["name"]: f["type"] for f in box.call("ann", "GET", "/api/schema/deals")[1]["schema"]["fields"]}
436 assert types["amount_cents"] == "integer"
437 with Sandbox(["app-views", "app-notes"]) as box:
438 box.add_user("ann")
439 for sent in (True, "true", "yes", 1):
440 status, body = box.call("ann", "POST", "/collections/notes/records",
441 {"content": "n", "owner_id": "ann", "is_public": sent})
442 assert body["record"]["is_public"] == "true", sent
443 status, body = box.call("ann", "POST", "/collections/notes/records",
444 {"content": "n", "owner_id": "ann", "is_public": False})
445 assert body["record"]["is_public"] == "false"
446
447
448# --- A requirement another collection decides (deals-type-*) -----------------
449
450def build_typed(tmp_path):
451 """The base deals package with the six deal-type blocks applied as the
452 page says: a new schema file, two manifest keys merged, a rule appended,
453 three fields appended, two schema keys merged, a new hook file."""
454 root = build(tmp_path)
455 package = root / "deals"
456 manifest = json.loads((package / "dbbasic-package.json").read_text())
457 schema = json.loads((package / "schemas" / "deals.json").read_text())
458 rules = json.loads((package / "permissions" / "rules.json").read_text())
459 (package / "schemas" / "deal_types.json").write_text(json.dumps(RECIPES["deals-type-schema"]))
460 manifest.update(RECIPES["deals-type-manifest"])
461 rules["rules"].append(RECIPES["deals-type-rule"])
462 schema["fields"].extend(RECIPES["deals-type-fields"])
463 schema.update(json.loads(json.dumps(RECIPES["deals-type-keys"])))
464 (package / "objects" / "hook").mkdir(parents=True)
465 (package / "objects" / "hook" / "deal_po.py").write_text(PYTHON_RECIPES["deals-type-hook"] + "\n")
466 (package / "dbbasic-package.json").write_text(json.dumps(manifest))
467 (package / "schemas" / "deals.json").write_text(json.dumps(schema))
468 (package / "permissions" / "rules.json").write_text(json.dumps(rules))
469 return root
470
471
472def test_recipe_f_a_requirement_another_collection_decides(tmp_path):
473 import object_records
474
475 with Sandbox(["deals"], packages_dir=build_typed(tmp_path)) as box:
476 box.add_user("ann")
477 status, body = box.call("admin", "POST", "/collections/deal_types/records",
478 {"name": "Enterprise", "requires_po": True})
479 assert status == 201, body
480 enterprise = body["record"]["id"]
481
482 status, body = box.call("ann", "POST", RECORDS, {"title": "Big", "owner_id": "ann",
483 "deal_type_id": enterprise})
484 assert (status, body["record"]["po_required"]) == (201, "true")
485 big = body["record"]["id"]
486 status, body = box.call("ann", "PUT", f"{RECORDS}/{big}", {"status": "won"})
487 assert (status, body["error"]) == (
488 400, "Record field 'po_number' is required when po_required is true and status is won")
489 status, body = box.call("ann", "PUT", f"{RECORDS}/{big}", {"status": "won", "po_number": "PO-1"})
490 assert status == 200, body
491
492 plain = create(box, "ann", "Small")
493 status, body = box.call("ann", "PUT", f"{RECORDS}/{plain}", {"status": "won"})
494 assert (status, body["record"]["po_required"]) == (200, "false")
495
496 with pytest.raises(object_records.CheckRefusedError, match="po_required must be true"):
497 object_records.create_collection_record(
498 "deals", {"title": "Import", "owner_id": "ann", "deal_type_id": enterprise,
499 "po_required": "false"},
500 base_dir=box.data_dir, roots=[box.objects_dir])
501
502 status, _ = box.call("admin", "PUT", f"/collections/deal_types/records/{enterprise}",
503 {"requires_po": False})
504 assert status == 200
505 assert box.call("ann", "GET", f"{RECORDS}/{big}")[1]["record"]["po_required"] == "true"