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_dron_loader_refusals.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_dron_loader_refusals.py · 52.4 KB · 901 lines
1"""A package declaration DRON refuses is refused at install, by name, before anything is written.
2
3tests/test_dron_schema.py compares the loaders with the JSON Schema case by
4case. This file pins what an author sees when the loader refuses: the file, the
5key path, what was wrong and the DRON spelling where there is one, and that a
6refused install leaves the server exactly as it was. The cases are the ones
7that used to install cleanly and do something other than what they said (task
8"Loaders refuse what DRON refuses"; docs/dron.md, "Known gaps in 0.1").
9"""
10
11from __future__ import annotations
12
13import json
14from pathlib import Path
15
16import pytest
17
18import object_packages
19
20GOOD_RULE = {"effect": "allow", "principal": "registered", "actions": ["read"],
21 "collection": "widgets", "row_filter": {"owner_id": "$user_id"}, "reason": "own rows"}
22
23
24def _write_package(root: Path, *, rules=None, schema=None, manifest_extra=None) -> None:
25 package = root / "widgets"
26 (package / "permissions").mkdir(parents=True)
27 (package / "schemas").mkdir()
28 (package / "objects" / "site").mkdir(parents=True)
29 (package / "objects" / "site" / "widgets.py").write_text("def GET(request):\n return {}\n")
30 (package / "permissions" / "rules.json").write_text(json.dumps(
31 rules if rules is not None else {"rules": [GOOD_RULE]}))
32 (package / "schemas" / "widgets.json").write_text(json.dumps(
33 schema if schema is not None else {"name": "widgets", "fields": [{"name": "id"}, {"name": "note"}]}))
34 manifest = {
35 "id": "widgets", "name": "Widgets", "version": "0.1.0",
36 "objects": [{"id": "site_widgets", "path": "objects/site/widgets.py"}],
37 "schemas": [{"collection": "widgets", "path": "schemas/widgets.json"}],
38 "permissions": [{"path": "permissions/rules.json"}],
39 **(manifest_extra or {}),
40 }
41 (package / object_packages.MANIFEST_FILE).write_text(json.dumps(manifest))
42
43
44def _snapshot(*roots: Path) -> dict[str, bytes]:
45 return {
46 str(path): path.read_bytes()
47 for root in roots if root.exists()
48 for path in sorted(root.rglob("*")) if path.is_file()
49 }
50
51
52def _refused_install(tmp_path: Path, **package) -> str:
53 """Install a package that must be refused; return the refusal and check nothing changed."""
54 packages, data, objects = tmp_path / "packages", tmp_path / "data", tmp_path / "objects"
55 objects.mkdir()
56 _write_package(packages, **package)
57 before = _snapshot(data, objects)
58 with pytest.raises((object_packages.PackageInstallError, ValueError)) as refused:
59 object_packages.install_package("widgets", root=packages, base_dir=data, object_roots=[objects])
60 assert _snapshot(data, objects) == before, "a refused install wrote something"
61 return str(refused.value)
62
63
64def _refused_install_and_dry_run(tmp_path: Path, **package) -> str:
65 """The install refuses, and the dry run (what an operator reads first)
66 reports the same reason without writing anything."""
67 (tmp_path / "install").mkdir()
68 message = _refused_install(tmp_path / "install", **package)
69 packages, data = tmp_path / "plan" / "packages", tmp_path / "plan" / "data"
70 _write_package(packages, **package)
71 plan = object_packages.dry_run_package("widgets", root=packages, base_dir=data, object_roots=[tmp_path / "plan"])
72 assert not plan["safe_to_install"]
73 assert message in plan["warnings"], plan["warnings"]
74 assert not data.exists(), "a dry run wrote something"
75 return message
76
77
78def test_the_good_package_installs(tmp_path):
79 packages, data, objects = tmp_path / "packages", tmp_path / "data", tmp_path / "objects"
80 objects.mkdir()
81 _write_package(packages)
82 object_packages.install_package("widgets", root=packages, base_dir=data, object_roots=[objects])
83 assert (data / "schemas" / "widgets.json").is_file()
84
85
86# --- permission rules --------------------------------------------------------
87
88@pytest.mark.parametrize("change,expected", [
89 # The worst case: the filter was dropped and the allow covered every row.
90 ({"row_filtr": {"owner_id": "$user_id"}}, "rule 2: unknown key 'row_filtr' (did you mean 'row_filter'?)"),
91 ({"principal": "admin"}, "did you mean 'role:admin'?"),
92 ({"principal": "regsitered"}, "did you mean 'registered'?"),
93 ({"actions": ["raed"]}, "actions: 'raed' is not an action (did you mean 'read'?)"),
94 ({"actions": ["read", "read"]}, "listed twice"),
95 ({"effect": "Allow"}, "DRON spells it 'allow'"),
96 ({"row_filter": {"owner_id": "$userid"}}, "row_filter.owner_id: '$userid' is not a $-variable (did you mean '$user_id'?)"),
97 ({"row_filter": {"is_public": True}}, 'write "true"'),
98 ({"row_filter": {"status": {"op": "like", "value": "x"}}}, "op 'like' is not one of"),
99 ({"row_filter": {"status": {"op": "eq"}}}, "op 'eq' needs a value"),
100 ({"row_filter": {"status": {"op": "eq", "value": None}}}, "matches no row"),
101 ({"row_filter": {"status": {"op": "in", "vlaue": ["a"]}}}, "unknown key 'vlaue' (did you mean 'value'?)"),
102 ({"row_filter": {"status": ["a", "b"]}}, '{"op": "in"'),
103 ({"collection": 5}, "collection 5 is not a name"),
104 ({"expires_at": "tomorrow"}, "expires_at 'tomorrow' is not an ISO-8601"),
105])
106def test_a_rule_dron_refuses_refuses_the_install_and_says_where(tmp_path, change, expected):
107 rules = {"rules": [GOOD_RULE, {**GOOD_RULE, **change}]}
108 if "row_filtr" in change:
109 del rules["rules"][1]["row_filter"]
110 message = _refused_install(tmp_path, rules=rules)
111 assert "permissions/rules.json" in message
112 assert "rule 2" in message
113 assert expected in message
114
115
116def test_a_retracted_rule_is_held_to_the_same_language(tmp_path):
117 message = _refused_install(tmp_path, rules={"rules": [GOOD_RULE], "retracted": [{**GOOD_RULE, "because": "x"}]})
118 assert "permissions/rules.json retracted rule 1: unknown key 'because'" in message
119
120
121def test_a_misspelt_retracted_section_refuses_rather_than_withdrawing_nothing(tmp_path):
122 message = _refused_install(tmp_path, rules={"rules": [GOOD_RULE], "retracted_rules": []})
123 assert "unknown key 'retracted_rules' (did you mean 'retracted'?)" in message
124
125
126def test_a_bare_list_of_rules_is_refused(tmp_path):
127 assert "an object with a rules list" in _refused_install(tmp_path, rules=[GOOD_RULE])
128
129
130def test_every_variable_operator_and_principal_dron_defines_is_accepted(tmp_path):
131 """The other half: tightening must not refuse anything the language has."""
132 import object_permissions
133
134 for variable in sorted(object_permissions.FILTER_VARIABLES):
135 object_permissions.check_rule_declaration({**GOOD_RULE, "row_filter": {"x": variable}})
136 for op in sorted(object_permissions.FILTER_OPERATORS):
137 value = ["a", 1] if op == "in" else "a"
138 object_permissions.check_rule_declaration({**GOOD_RULE, "row_filter": {"x": {"op": op, "value": value}}})
139 object_permissions.check_rule_declaration({**GOOD_RULE, "row_filter": {"x": {"op": "ne", "value": None}}})
140 object_permissions.check_rule_declaration({**GOOD_RULE, "row_filter": {"x": {"op": "in", "value": "$accessible_projects"}}})
141 for principal in ("public", "registered", "owner", "role:a", "user:1", "account:b", "subscription:pro"):
142 object_permissions.check_rule_declaration({**GOOD_RULE, "principal": principal})
143 object_permissions.check_rule_declaration({**GOOD_RULE, "effect": "deny", "principal": "owner_fallback"})
144 for action in sorted(object_permissions.RULE_ACTIONS):
145 object_permissions.check_rule_declaration({**GOOD_RULE, "actions": [action]})
146
147
148# --- collection schemas ------------------------------------------------------
149
150def _schema_with(field=None, **root):
151 fields = [{"name": "id"}, {"name": "note", **(field or {})}]
152 return {"name": "widgets", "fields": fields, **root}
153
154
155@pytest.mark.parametrize("schema,expected", [
156 (_schema_with(colour="red"), "widgets: unknown key 'colour'"),
157 (_schema_with(titel="Widgets"), "unknown key 'titel' (did you mean 'title'?)"),
158 (_schema_with({"requird": True}), "widgets: field 'note': unknown key 'requird' (did you mean 'required'?)"),
159 # A dead key: the limit is validation.max_length.
160 (_schema_with({"maxlength": 8}), "field 'note': unknown key 'maxlength'"),
161 (_schema_with({"validation": {"max_lenght": 8}}),
162 "field 'note' validation: unknown key 'max_lenght' (did you mean 'max_length'?)"),
163 (_schema_with(views={"list_mode": "board", "colums": ["note"]}), "widgets: views: unknown key 'colums'"),
164 (_schema_with(views={"board": {"group_by": "note"}}), "views.board: unknown key 'group_by'"),
165 (_schema_with(hooks={"before_wirte": "hook_widgets"}),
166 "hooks: unknown key 'before_wirte' (did you mean 'before_write'?)"),
167 (_schema_with({"relation": {"collection": "gadgets", "display": "name"}}),
168 "field 'note' relation: unknown key 'display'"),
169])
170def test_a_schema_key_dron_does_not_define_refuses_the_install_and_says_where(tmp_path, schema, expected):
171 message = _refused_install(tmp_path, schema=schema)
172 assert "schemas/widgets.json" in message
173 assert expected in message
174
175
176@pytest.mark.parametrize("field,spelling", [
177 ({"readonly": True}, "write read_only instead"),
178 ({"readOnly": True}, "write read_only instead"),
179 ({"computed": True}, 'write "type": "computed" instead'),
180 ({"validation": {"regex": "a+"}}, "write pattern instead"),
181 ({"validation": {"required": True}}, 'write "required": true on the field instead'),
182 ({"validation": {"choices": ["a"]}}, 'write "type": "enum" with an "enum" list on the field instead'),
183 ({"validation": {"in": ["a"]}}, 'write "type": "enum" with an "enum" list on the field instead'),
184])
185def test_an_engine_synonym_is_refused_with_the_dron_spelling(tmp_path, field, spelling):
186 message = _refused_install(tmp_path, schema=_schema_with(field))
187 assert "is not DRON" in message and spelling in message
188
189
190def test_a_refused_upgrade_leaves_the_installed_version_exactly_as_it_was(tmp_path):
191 """The case a deployed box meets: v1 is installed, v2 carries a mistake."""
192 import shutil
193
194 packages, data, objects = tmp_path / "packages", tmp_path / "data", tmp_path / "objects"
195 objects.mkdir()
196 _write_package(packages)
197 object_packages.install_package("widgets", root=packages, base_dir=data, object_roots=[objects])
198 before = _snapshot(data, objects)
199 shutil.rmtree(packages / "widgets")
200 _write_package(packages, schema=_schema_with({"requird": True}),
201 rules={"rules": [{**GOOD_RULE, "row_filtr": {}}]})
202 with pytest.raises(object_packages.PackageInstallError, match="requird"):
203 object_packages.install_package("widgets", root=packages, base_dir=data,
204 object_roots=[objects], allow_replace=True)
205 assert _snapshot(data, objects) == before
206
207
208def test_a_dry_run_reports_the_schema_refusal(tmp_path):
209 packages, data = tmp_path / "packages", tmp_path / "data"
210 _write_package(packages, schema=_schema_with({"maxlength": 8}))
211 plan = object_packages.dry_run_package("widgets", root=packages, base_dir=data, object_roots=[tmp_path])
212 assert not plan["safe_to_install"]
213 assert any("unknown key 'maxlength'" in warning for warning in plan["warnings"])
214
215
216# --- the manifest ------------------------------------------------------------
217
218@pytest.mark.parametrize("extra,expected", [
219 # A misspelt section used to ship nothing and install cleanly.
220 ({"schedule": [{"id": "n", "object_id": "site_widgets", "schedule": "10 6 * * *"}]},
221 "dbbasic-package.json: unknown section 'schedule' (did you mean 'schedules'?)"),
222 ({"permisions": [{"path": "permissions/rules.json"}]}, "unknown section 'permisions' (did you mean 'permissions'?)"),
223 ({"nav": [{"id": "w", "label": "W", "path": "/w", "surfce": "admin"}]},
224 "dbbasic-package.json nav entry 1: unknown key 'surfce' (did you mean 'surface'?)"),
225 ({"schedules": [{"id": "n", "object_id": "site_widgets", "cron": "10 6 * * *"}]},
226 "schedules entry 1: unknown key 'cron'"),
227])
228def test_a_manifest_key_dron_does_not_define_refuses_the_install_and_says_where(tmp_path, extra, expected):
229 assert expected in _refused_install(tmp_path, manifest_extra=extra)
230
231
232# --- manifest values the schema refuses and the loader used to read as absent ---
233
234_NAV = {"id": "w", "label": "W", "path": "/w"}
235_ATT = {"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "draft"}}
236_PROVIDER = {"id": "p", "label": "P", "path": "/p", "object_id": "site_widgets"}
237_SCHED = {"id": "n", "object_id": "site_widgets", "schedule": "10 6 * * *"}
238
239
240def _refused_manifest(tmp_path: Path, **package) -> str:
241 """A manifest refusal stops the dry run the same way it stops the install
242 (the manifest is read before any plan is made); nothing is written."""
243 (tmp_path / "install").mkdir()
244 message = _refused_install(tmp_path / "install", **package)
245 packages, data = tmp_path / "plan" / "packages", tmp_path / "plan" / "data"
246 _write_package(packages, **package)
247 with pytest.raises(object_packages.InvalidPackageManifestError) as refused:
248 object_packages.dry_run_package("widgets", root=packages, base_dir=data, object_roots=[tmp_path / "plan"])
249 assert str(refused.value) == message
250 assert not data.exists(), "a dry run wrote something"
251 return message
252
253
254def _att(**keys):
255 return {"attention": [{**_ATT, **keys}]}
256
257
258@pytest.mark.parametrize("section", [
259 "attention", "nav", "objects", "schemas", "seed", "permissions", "schedules", "connectors",
260 "dependencies", "migrations",
261])
262def test_a_null_manifest_section_refuses_the_install(tmp_path, section):
263 # Read as an empty list: the author wrote the section and got nothing.
264 message = _refused_manifest(tmp_path, manifest_extra={section: None})
265 assert f"dbbasic-package.json: {section} must be a list, not null" in message
266
267
268@pytest.mark.parametrize("extra,expected", [
269 ({"description": None}, "dbbasic-package.json: description must be text, not None"),
270 ({"compatibility": None}, "dbbasic-package.json: compatibility must be an object, not null"),
271 ({"compatibility": {"object_server": 1}}, "compatibility 'object_server' must be text such as '>=0.1', not 1"),
272 ({"schedules": [{**_SCHED, "description": 5}]}, "schedules entry 1: description must be text, not 5"),
273 ({"connectors": [{"collection": "widgets", "module": "objects/x.py", "entry": ""}]},
274 "connectors entry 1: entry must not be blank"),
275 ({"connectors": [{"collection": "widgets", "module": "objects/x.py", "entry": 3}]},
276 "connectors entry 1: entry must be text, not 3"),
277 ({"connectors": [{"collection": "widgets", "module": "objects/x.py", "entry": " run "}]},
278 "connectors entry 1: entry ' run ' must be a function name"),
279 ({"nav": [{**_NAV, "blurb": 5}]}, "nav entry 1: blurb must be text, not 5"),
280 ({"nav": [{**_NAV, "group": None}]}, "nav entry 1: group must be text, not None"),
281 ({"nav": [{**_NAV, "order": None}]}, "nav entry 1: order must be a whole number such as 10, not None"),
282 ({"nav": [{**_NAV, "order": ""}]}, "nav entry 1: order must be a whole number such as 10, not ''"),
283 ({"nav": [{**_NAV, "surface": None}]}, "nav entry 1: surface must be text, not None"),
284 ({"nav": [{**_NAV, "surface": ""}]}, "nav entry 1: surface must not be blank"),
285 (_att(group=3), "attention entry 1: group must be text, not 3"),
286 (_att(nav_id=""), "attention entry 1: nav_id must not be blank"),
287 (_att(nav_id=None), "attention entry 1: nav_id must be text, not None"),
288 (_att(severity=None), "attention entry 1: severity must be text, not None"),
289 (_att(severity=""), "attention entry 1: severity must not be blank"),
290 (_att(severity="Urgent"), "attention entry 1: severity 'Urgent' is not DRON; write one of normal, warning, urgent"),
291 ({"attention": [{**_PROVIDER, "reads": ""}]}, "attention entry 1: reads must be a list of collection names, not ''"),
292 ({"attention": [{**_PROVIDER, "reads": None}]}, "attention entry 1: reads must be a list of collection names, not None"),
293 (_att(detail=None), "attention entry 1: detail must be a part or a list of parts, not None"),
294 (_att(detail=[]), "attention entry 1: detail must be a part or a list of parts, not []"),
295 (_att(detail={}), "attention entry 1: detail must be a part or a list of parts, not {}"),
296 (_att(detail=""), "attention entry 1: detail must be a part or a list of parts, not ''"),
297 (_att(detail=[{"op": "sum", "field": "qty", "text": "{value}", "format": None}]),
298 "attention entry 1: detail part 1: format must be one of integer, cents, dollars, hours, not None"),
299 (_att(detail={"op": "count", "text": "n", "format": 0}),
300 "detail part 1: format must be one of integer, cents, dollars, hours, not 0"),
301 (_att(detail={"op": "count", "text": "n", "format": ""}),
302 "detail part 1: format must be one of integer, cents, dollars, hours, not ''"),
303 (_att(detail={"op": 0, "text": "n"}), "detail part 1: op must be text, one of count, sum, max_age_days, not 0"),
304 (_att(where={"status": {"op": None, "value": "x"}}),
305 "attention entry 1: where status: op None is not DRON; write one of eq, ne, in, gte, lte, gt, lt, older_than_days"),
306 (_att(where={"status": {"op": "", "value": "x"}}), "where status: op '' is not DRON; write one of eq"),
307 (_att(where={"status": {"op": 0, "value": "x"}}), "where status: op 0 is not DRON; write one of eq"),
308 (_att(where={"status": {"value": "x"}}), "where status: a condition needs an op, one of eq, ne"),
309 (_att(where={"status": "draft", "n": [{"op": "GT", "value": "1"}]}), "where n: op 'GT' is not DRON; write 'gt'"),
310 (_att(detail={"op": "count", "text": "n", "where": {"owner_id": {"op": [], "value": "x"}}}),
311 "detail part 1 where owner_id: op [] is not DRON; write one of eq"),
312])
313def test_a_manifest_value_the_schema_refuses_refuses_the_install_and_says_where(tmp_path, extra, expected):
314 message = _refused_manifest(tmp_path, manifest_extra=extra)
315 assert "dbbasic-package.json" in message
316 assert expected in message
317
318
319def test_the_manifest_values_dron_allows_still_install(tmp_path):
320 extra = {
321 "description": "", "compatibility": {"object_server": ">=0.1"}, "dependencies": [], "seed": [],
322 "schedules": [{**_SCHED, "description": ""}],
323 "nav": [{**_NAV, "blurb": "", "group": "", "order": 0, "surface": "hidden"}],
324 "attention": [
325 {**_ATT, "group": "", "severity": "urgent", "nav_id": "w",
326 "where": {"status": {"op": "in", "value": ["a"]}, "age": {"op": "older_than_days", "value": 3}},
327 "detail": [{"op": "count", "text": "n", "format": "integer"}]},
328 {**_PROVIDER, "reads": []},
329 ],
330 }
331 packages, data, objects = tmp_path / "packages", tmp_path / "data", tmp_path / "objects"
332 objects.mkdir()
333 _write_package(packages, manifest_extra=extra)
334 object_packages.install_package("widgets", root=packages, base_dir=data, object_roots=[objects])
335
336
337# --- values of the wrong type are refused, not coerced ------------------------
338
339@pytest.mark.parametrize("schema,expected", [
340 # bool("no") is True: this made the field required.
341 (_schema_with({"required": "no"}), "field 'note': required must be true or false, not 'no'"),
342 (_schema_with({"read_only": "yes"}), "field 'note': read_only must be true or false"),
343 (_schema_with(version="3"), "version '3' must be a whole number"),
344 (_schema_with(version=2.7), "version 2.7 must be a whole number"),
345])
346def test_a_schema_value_of_the_wrong_type_is_refused_not_coerced(tmp_path, schema, expected):
347 assert expected in _refused_install(tmp_path, schema=schema)
348
349
350@pytest.mark.parametrize("extra,expected", [
351 ({"nav_optional": "no"}, "nav_optional must be true or false, not 'no'"),
352 ({"description": 5}, "description must be text"),
353])
354def test_a_manifest_value_of_the_wrong_type_is_refused_not_coerced(tmp_path, extra, expected):
355 assert expected in _refused_install(tmp_path, manifest_extra=extra)
356
357
358def test_a_whole_number_version_written_as_a_float_still_loads():
359 """JSON Schema's integer includes 2.0, so DRON does too."""
360 import object_schemas
361
362 assert object_schemas.normalize_declaration("widgets", _schema_with(version=2.0))["version"] == 2
363
364
365# --- one spelling for each type and choice ------------------------------------
366
367@pytest.mark.parametrize("field,expected", [
368 ({"type": "INTEGER"}, "type 'INTEGER' is not DRON; write 'integer'"),
369 ({"type": "Date"}, "type 'Date' is not DRON; write 'date'"),
370 ({"type": "money"}, "unknown type 'money'"),
371 ({"type": "integr"}, "unknown type 'integr' (did you mean 'integer'?)"),
372 ({"type": "enum", "enum": {"values": ["a", "b"]}}, 'enum {"values": [...]} is not DRON; write the list itself'),
373])
374def test_a_field_type_or_enum_spelt_another_way_is_refused_with_the_dron_spelling(tmp_path, field, expected):
375 message = _refused_install(tmp_path, schema=_schema_with(field))
376 assert "field 'note'" in message and expected in message
377
378
379@pytest.mark.parametrize("extra,expected", [
380 ({"schedules": [{"id": "n", "object_id": "site_widgets", "schedule": "10 6 * * *", "type": "CRON"}]},
381 "schedule n: type 'CRON' is not DRON; write 'cron'"),
382 ({"schedules": [{"id": "n", "object_id": "site_widgets", "schedule": "10 6 * * *", "method": "post"}]},
383 "schedule n: method 'post' is not DRON; write 'POST'"),
384 ({"nav": [{"id": "w", "label": "W", "path": "/w", "surface": "Public"}]},
385 "nav w: surface 'Public' is not DRON; write 'public'"),
386])
387def test_a_manifest_choice_spelt_another_way_is_refused_with_the_dron_spelling(tmp_path, extra, expected):
388 assert expected in _refused_install(tmp_path, manifest_extra=extra)
389
390
391def test_a_transition_guard_with_a_variable_that_is_not_one_is_refused(tmp_path):
392 field = {"type": "enum", "enum": ["draft", "posted"],
393 "transitions": {"draft": [{"to": "posted", "when": {"owner_id": "$userid"}}]}}
394 message = _refused_install(tmp_path, schema=_schema_with(field))
395 assert "field 'note' transitions['draft'] when.owner_id: '$userid' is not a $-variable" in message
396 assert "(did you mean '$user_id'?)" in message
397
398
399def test_a_capability_written_as_text_is_refused(tmp_path):
400 message = _refused_install(tmp_path, schema=_schema_with(capabilities={"comments": "yes"}))
401 assert "capabilities.comments must be true or false, not 'yes'" in message
402
403
404def test_a_stored_schema_keeps_loading_with_a_key_dron_lacks():
405 """The normalizer stays lenient: a box must not stop reading its own data
406 over a key. Only a package declaration is held to DRON."""
407 import object_schemas
408
409 stored = object_schemas.normalize_schema("widgets", _schema_with({"readonly": True}))
410 assert stored["fields"][1]["readonly"] is True
411 assert object_schemas.normalize_schema("widgets", stored) == stored
412
413
414# --- values DRON refuses that used to load and never apply (round 2) ------------
415#
416# Each of these installed cleanly and then either failed at the first write or
417# render that touched it, or did nothing at all. Only a package declaration is
418# held to them; a schema stored on a box keeps loading (the last test).
419
420@pytest.mark.parametrize("validation,expected", [
421 ({"min": "abc"}, "field 'note' validation: min must be a number such as 1 or 2.5, not 'abc'"),
422 ({"max": "ten"}, "field 'note' validation: max must be a number such as 1 or 2.5, not 'ten'"),
423 ({"min": ""}, "min must be a number"),
424 ({"min": None}, "min must be a number such as 1 or 2.5, not None"),
425 ({"max": True}, "max must be a number such as 1 or 2.5, not True"),
426 ({"min": [1]}, "min must be a number"),
427 ({"min": "1_000"}, "min must be a number"),
428 ({"min": "inf"}, "min must be a number"),
429])
430def test_a_min_or_max_that_is_not_a_number_refuses_the_install_and_says_where(tmp_path, validation, expected):
431 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with({"validation": validation}))
432 assert "schemas/widgets.json" in message and "widgets: " in message
433 assert expected in message
434
435
436@pytest.mark.parametrize("bound", [0, 1, -5, 2.5, "0", " 7 ", "2.5", "-1e3", "+.5", "3."])
437def test_every_number_a_bound_may_be_written_as_is_accepted(bound):
438 import object_schemas
439
440 object_schemas.normalize_declaration(
441 "widgets", _schema_with({"type": "number", "validation": {"min": bound, "max": bound}}))
442
443
444def test_the_number_a_bound_may_be_written_as_is_the_one_the_schema_defines():
445 """The loader's pattern is the schema's, so they cannot drift apart."""
446 import object_schemas
447
448 bound = json.loads((Path(object_schemas.__file__).parent / "dron" / "dron-collection.schema.json")
449 .read_text(encoding="utf-8"))["$defs"]["numericBound"]
450 assert object_schemas._NUMERIC_BOUND_RE.pattern == bound["anyOf"][1]["pattern"]
451
452
453@pytest.mark.parametrize("permissions,expected", [
454 ({"default": "maybe"}, "field 'note' permissions.default: 'maybe' is not an access level; write edit, read or hidden"),
455 ("maybe", "field 'note' permissions: 'maybe' is not an access level"),
456 ({"owner": "hiden"}, "permissions.owner: 'hiden' is not an access level; write edit, read or hidden (did you mean 'hidden'?)"),
457 ({"roles": {"sales": "deny"}}, "permissions.roles.sales: 'deny' is not DRON; write 'hidden'"),
458 # The engine reads these spellings; DRON defines the three levels only.
459 ({"owner": "readonly"}, "permissions.owner: 'readonly' is not DRON; write 'read'"),
460 ({"default": "write"}, "permissions.default: 'write' is not DRON; write 'edit'"),
461 ({"default": " Edit "}, "permissions.default: ' Edit ' is not DRON; write 'edit'"),
462 ({"owner": {"access": "edit"}}, "permissions.owner: access must be edit, read or hidden, not {'access': 'edit'}"),
463 ({"default": None}, "permissions.default: access must be edit, read or hidden, not None"),
464 ({"roles": ["sales"]}, "permissions.roles: must be an object of role name to access level"),
465 ({"edit": ["role:a", ""]}, "permissions.edit: a principal must be non-empty text"),
466 (["edit"], "permissions must be an access level (edit, read or hidden) or an object"),
467 (None, "permissions must be an access level (edit, read or hidden) or an object"),
468])
469def test_a_field_permission_level_that_is_not_one_refuses_the_install_and_says_where(tmp_path, permissions, expected):
470 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with({"permissions": permissions}))
471 assert "schemas/widgets.json" in message and "widgets: field 'note' permissions" in message
472 assert expected in message
473
474
475@pytest.mark.parametrize("permissions", [
476 "hidden",
477 {},
478 {"default": "hidden"},
479 {"owner": "read", "role:moderator": "edit", "default": "hidden"},
480 {"roles": {"sales": "hidden", "ops": "read"}, "default": "edit"},
481 {"edit": ["role:admin", "user:7"], "hidden": ["public"]},
482])
483def test_every_field_permission_shape_dron_defines_is_accepted(permissions):
484 import object_schemas
485
486 object_schemas.normalize_declaration("widgets", _schema_with({"permissions": permissions}))
487
488
489@pytest.mark.parametrize("relation,expected", [
490 # Refused only when a record was written: "has an invalid collection".
491 ({"display_field": "name"}, "field 'note' relation: no collection (name the collection the id must exist in, "
492 '{"collection": "projects"})'),
493 ({}, "field 'note' relation: no collection"),
494 ({"collection": "bad name!"}, "field 'note' relation: collection 'bad name!' is not a collection name"),
495 ({"collection": ""}, "relation: collection '' is not a collection name"),
496 ({"collection": 5}, "relation: collection 5 is not a collection name"),
497 ({"collection": None, "display_field": "name"}, "relation: collection None is not a collection name"),
498 ("bad name!", "field 'note' relation: collection 'bad name!' is not a collection name"),
499 ("", "relation: collection '' is not a collection name"),
500 (["gadgets"], "field 'note' relation must be a collection name or an object with a collection, not ['gadgets']"),
501 (None, "relation must be a collection name or an object with a collection, not None"),
502])
503def test_a_relation_with_no_collection_refuses_the_install_and_says_where(tmp_path, relation, expected):
504 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with({"relation": relation}))
505 assert "schemas/widgets.json" in message and "widgets: field 'note' relation" in message
506 assert expected in message
507
508
509@pytest.mark.parametrize("relation", [
510 "gadgets",
511 {"collection": "gadgets"},
512 {"collection": "gadgets", "display_field": "name", "requires": "update"},
513])
514def test_every_relation_shape_dron_defines_is_accepted(relation):
515 import object_schemas
516
517 object_schemas.normalize_declaration("widgets", _schema_with({"relation": relation}))
518
519
520GOOD_ROLLUP = {"collection": "gadgets", "fk_field": "widget_id", "op": "sum", "field": "cents"}
521
522
523@pytest.mark.parametrize("field,expected", [
524 # The formula was kept and never evaluated: the field stayed blank.
525 ({"formula": "id + 1"},
526 'field \'note\': formula is only evaluated on a field with "type": "computed", and this one is '
527 "type 'text' (the default)"),
528 ({"type": "integer", "formula": "id + 1"}, "formula is only evaluated on a field with \"type\": \"computed\", and this one is type 'integer'"),
529 ({"type": "text", "rollup": GOOD_ROLLUP}, "field 'note': rollup is only evaluated on a field with \"type\": \"computed\", and this one is type 'text'"),
530 ({"type": "enum", "enum": ["a"], "formula": "id"}, "type 'enum'"),
531])
532def test_a_formula_or_rollup_on_a_field_that_is_not_computed_refuses_the_install_and_says_where(tmp_path, field, expected):
533 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(field))
534 assert "schemas/widgets.json" in message and "widgets: field 'note'" in message
535 assert expected in message
536
537
538def test_a_formula_or_rollup_on_a_computed_field_is_accepted():
539 import object_schemas
540
541 object_schemas.normalize_declaration("widgets", _schema_with({"type": "computed", "formula": 'id + "x"'}))
542 object_schemas.normalize_declaration("widgets", _schema_with({"type": "computed", "rollup": GOOD_ROLLUP}))
543
544
545def _rollup(**keys):
546 rollup = {**GOOD_ROLLUP, **keys}
547 return {"type": "computed", "rollup": {k: v for k, v in rollup.items() if v is not None}}
548
549
550@pytest.mark.parametrize("field,expected", [
551 # Skipped by the engine without a word: the field never computed.
552 (_rollup(op="median"), "field 'note' rollup: op 'median' is not a rollup op; write one of avg, count, max, min or sum"),
553 (_rollup(op="sun"), "op 'sun' is not a rollup op; write one of avg, count, max, min or sum (did you mean 'sum'?)"),
554 (_rollup(op="Sum"), "field 'note' rollup: op 'Sum' is not DRON; write 'sum'"),
555 (_rollup(op=5), "rollup: op 5 is not a rollup op"),
556 (_rollup(op=None), "field 'note' rollup: no op (write one of avg, count, max, min or sum)"),
557 # A sum with no field added up nothing and read 0 for ever.
558 (_rollup(field=None), "field 'note' rollup: op 'sum' needs a field, the child field it aggregates (only count works without one)"),
559 (_rollup(op="avg", field=None), "rollup: op 'avg' needs a field"),
560 (_rollup(op="min", field=None), "rollup: op 'min' needs a field"),
561 (_rollup(collection=None), "field 'note' rollup: no collection (the child collection to aggregate)"),
562 (_rollup(fk_field=None), "field 'note' rollup: no fk_field (the child field that holds this record's id)"),
563 ({"type": "computed", "rollup": "gadgets"}, "field 'note' rollup must be an object with collection, fk_field and op, not 'gadgets'"),
564])
565def test_a_rollup_that_could_never_compute_refuses_the_install_and_says_where(tmp_path, field, expected):
566 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(field))
567 assert "schemas/widgets.json" in message and "widgets: field 'note' rollup" in message
568 assert expected in message
569
570
571def test_every_rollup_shape_dron_defines_is_accepted():
572 import object_computed
573 import object_schemas
574
575 for op in object_computed.ROLLUP_OPS:
576 object_schemas.normalize_declaration("widgets", _schema_with(_rollup(op=op)))
577 # A count has nothing to read from the child rows, so it needs no field; a where narrows the children.
578 object_schemas.normalize_declaration("widgets", _schema_with(_rollup(op="count", field=None, where={"status": "ok"})))
579
580
581@pytest.mark.parametrize("hook,shown", [
582 ("bad name!", "'bad name!'"),
583 ("hook widgets", "'hook widgets'"),
584 ("hook_widgets ", "'hook_widgets '"), # the engine strips it; DRON's id has no spaces
585 ("hooks/widgets.py", "'hooks/widgets.py'"),
586 ("", "''"),
587 ("h" * 65, "'" + "h" * 65 + "'"),
588 (["hook_widgets"], "['hook_widgets']"),
589 (None, "None"),
590])
591def test_a_hook_name_that_is_not_an_object_id_refuses_the_install_and_says_where(tmp_path, hook, shown):
592 # It never resolved, and a declared hook that fails stops every public write.
593 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(hooks={"before_write": hook}))
594 assert "schemas/widgets.json" in message
595 assert (f"widgets: hooks.before_write {shown} is not an object id "
596 "(letters, digits and underscores, 1 to 64 characters)") in message
597
598
599def test_a_hook_name_that_is_an_object_id_is_accepted():
600 import object_schemas
601
602 for name in ("hook_widgets", "H", "u_7_x", "h" * 64):
603 object_schemas.normalize_declaration("widgets", _schema_with(hooks={"before_write": name}))
604
605
606@pytest.mark.parametrize("mode,shown,hint", [
607 ("grid", "'grid'", ""),
608 ("tabel", "'tabel'", " (did you mean 'table'?)"),
609 ("Table", "'Table'", " (did you mean 'table'?)"),
610 ("", "''", ""),
611 (["table"], "['table']", ""),
612 (None, "None", ""),
613])
614def test_a_list_mode_that_is_not_one_refuses_the_install_and_says_where(tmp_path, mode, shown, hint):
615 # The list fell back to plain rows with a notice, so the view the author
616 # described never appeared.
617 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(views={"list_mode": mode}))
618 assert "schemas/widgets.json" in message
619 assert (f"widgets: views.list_mode {shown} is not a list mode; write one of "
620 f"table, board, tree, calendar, cards or feed{hint}") in message
621
622
623def test_every_list_mode_dron_defines_is_accepted():
624 import object_schemas
625
626 for mode in ("table", "board", "tree", "calendar", "cards", "feed"):
627 object_schemas.normalize_declaration("widgets", _schema_with(views={"list_mode": mode}))
628 object_schemas.normalize_declaration("widgets", _schema_with(views={"list_fields": ["note"]}))
629
630
631@pytest.mark.parametrize("rules,expected", [
632 ({"min_length": -1}, "field 'note' validation: min_length must be a whole number of at least 0 such as 3, not -1"),
633 ({"min_length": 2.5}, "validation: min_length must be a whole number of at least 0 such as 3, not 2.5"),
634 ({"min_length": "3"}, "validation: min_length must be a whole number of at least 0 such as 3, not '3'"),
635 ({"max_length": True}, "validation: max_length must be a whole number of at least 0 such as 3, not True"),
636 ({"max_length": [20]}, "validation: max_length must be a whole number of at least 0 such as 3, not [20]"),
637 ({"max_length": ""}, "validation: max_length must be a whole number of at least 0 such as 3, not ''"),
638 ({"pattern": "("}, "field 'note' validation: pattern '(' is not a DRON regular expression: "
639 "the ( at position 0 is never closed. The dialect is in docs/dron.md, \"Regular expressions\""),
640 ({"pattern": "[a-"}, "validation: pattern '[a-' is not a DRON regular expression: the [ at position 0 is never closed"),
641 # Python's `re` compiles each of these; a second engine reads it differently or not at all.
642 ({"pattern": "(?i)[a-z]+"}, "validation: pattern '(?i)[a-z]+' is not a DRON regular expression: an inline flag "
643 "((?i at position 0) is not in the dialect; write both cases, as in [Aa]"),
644 ({"pattern": "(?<=a)b"}, "is not a DRON regular expression: a lookbehind ((?<= at position 0) is not in the dialect"),
645 ({"pattern": "(?P<year>[0-9]{4})"}, "is not a DRON regular expression: a named group (position 0) is not in the dialect"),
646 ({"pattern": "([a-z])\\1"}, "is not a DRON regular expression: a backreference (\\1 at position 7) is not in the dialect"),
647 ({"pattern": "[a-z]++"}, "is not a DRON regular expression: a possessive quantifier (the + at position 6) is not in the dialect"),
648 ({"pattern": "\\bword\\b"}, "is not a DRON regular expression: \\b (a word boundary) is not in the dialect (position 0)"),
649 ({"pattern": "[a-z]+\\Z"}, "is not a DRON regular expression: \\Z is not in the dialect; write $ (position 6)"),
650 ({"pattern": "{value}"}, "is not a DRON regular expression: the { at position 0 is not a count such as {2}, {2,} or {2,5}; "
651 "write \\{ for a literal {"),
652 ({"pattern": 5}, "validation: pattern must be text holding a regular expression, not 5"),
653])
654def test_a_length_or_pattern_the_engine_would_misread_refuses_the_install_and_says_where(tmp_path, rules, expected):
655 # Every write of the field was refused (an uncompilable pattern), the
656 # value was cut or reinterpreted (2.5 read as 2, "3" as 3, True as 1), or
657 # the pattern is outside the dialect two engines read alike
658 # (tests/test_dron_regex.py has the whole table).
659 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with({"validation": rules}))
660 assert "schemas/widgets.json" in message
661 assert expected in message
662
663
664@pytest.mark.parametrize("key,value", [
665 ("exclusive_min", "1_0"), ("exclusive_max", "1_000"), ("exclusive_min", "0x10"), ("exclusive_max", "abc"),
666])
667def test_an_exclusive_bound_that_is_not_written_as_a_number_refuses_the_install(tmp_path, key, value):
668 # Decimal("1_0") is 10, so the normalizer read what the schema refuses.
669 message = _refused_install_and_dry_run(
670 tmp_path, schema=_schema_with({"type": "integer", "validation": {key: value}}))
671 assert f"field 'note' validation: {key} must be a number such as 1 or 2.5, not {value!r}" in message
672
673
674def test_the_lengths_patterns_and_bounds_dron_defines_are_accepted():
675 import object_schemas
676
677 for rules in ({"min_length": 0, "max_length": 3}, {"max_length": 3.0}, {"pattern": r"^[a-z]+\d*$"}):
678 object_schemas.normalize_declaration("widgets", _schema_with({"validation": rules}))
679 object_schemas.normalize_declaration(
680 "widgets", _schema_with({"type": "number", "validation": {"exclusive_min": " 0 ", "exclusive_max": "1e3"}}))
681
682
683def _rollup_field(**keys):
684 return {"type": "computed", "rollup": {**GOOD_ROLLUP, **keys}}
685
686
687@pytest.mark.parametrize("field,expected", [
688 ({**_rollup_field(), "formula": "id + 1"},
689 "field 'note': has both a formula and a rollup; a computed field has one or the other"),
690 (_rollup_field(collection="bad name!"),
691 "field 'note' rollup: collection 'bad name!' is not a collection name (letters, digits and underscores, 1 to 64 characters); no such collection can exist"),
692 (_rollup_field(collection=5), "rollup: collection 5 is not a collection name"),
693 (_rollup_field(fk_field="1x"),
694 "field 'note' rollup: fk_field '1x' is not a field name (letters, digits and underscores, not starting with a digit, 1 to 64 characters)"),
695 (_rollup_field(field="a b"), "rollup: field 'a b' is not a field name"),
696 (_rollup_field(where=["status"]),
697 "field 'note' rollup: where must be an object of child field to the one value it must equal"),
698 (_rollup_field(where="status=paid"), "rollup: where must be an object of child field"),
699 (_rollup_field(where={"bad key": "x"}), "rollup: where field 'bad key' is not a field name"),
700 (_rollup_field(where={"status": ["a", "b"]}),
701 "field 'note' rollup: where.status must be one text, number or true/false value, not ['a', 'b']"),
702 ({"relation": {"collection": "gadgets", "display_field": "full name"}},
703 "field 'note' relation: display_field 'full name' is not a field name"),
704 ({"relation": {"collection": "gadgets", "display_field": 5}},
705 "field 'note' relation: display_field 5 is not a field name"),
706])
707def test_a_computed_or_relation_name_the_engine_could_never_look_up_refuses_the_install(tmp_path, field, expected):
708 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(field))
709 assert "schemas/widgets.json" in message
710 assert expected in message
711
712
713def test_a_rollup_where_and_a_relation_display_field_dron_defines_are_accepted():
714 import object_schemas
715
716 object_schemas.normalize_declaration(
717 "widgets", _schema_with(_rollup_field(where={"status": "paid", "settled": True, "n": 3})))
718 object_schemas.normalize_declaration(
719 "widgets", _schema_with({"relation": {"collection": "gadgets", "display_field": "full_name"}}))
720
721
722@pytest.mark.parametrize("root,expected", [
723 # `"hooks": "hook_x"` declared no hook and installed without a word.
724 ({"hooks": "hook_widgets"},
725 'widgets: hooks must be an object such as {"before_write": "hook_widgets"}, not \'hook_widgets\''),
726 ({"views": "table"}, "widgets: views must be an object such as"),
727 ({"search": ["note"]}, "widgets: search must be an object such as"),
728 ({"capabilities": ["comments"]}, 'widgets: capabilities must be an object such as {"comments": true}, not [\'comments\']'),
729 ({"ui": "compact"}, "widgets: ui must be an object such as {}, not 'compact'"),
730 ({"blocks": "feed"}, "widgets: blocks must be an object"),
731 ({"forms": "default"}, "widgets: forms must be an object"),
732 ({"title": ["Widgets"]}, "widgets: title must be text, not ['Widgets']"),
733 ({"description": None}, "widgets: description must be text, not None"),
734 ({"forms": {"default": "x"}}, 'widgets: forms.default must be an object such as {"fields": ["name"]}, not \'x\''),
735 ({"forms": {"default": {"fields": "note"}}},
736 'widgets: forms.default.fields must be a list of field names such as ["name", "status"], not \'note\''),
737 ({"search": {"fields": "note"}}, "widgets: search.fields must be a list of field names"),
738 ({"search": {"fields": []}}, "widgets: search.fields must name at least one field"),
739 ({"search": {"fields": ["a b"]}},
740 "widgets: search.fields: 'a b' is not a field name (letters, digits and underscores, not starting with a digit, 1 to 64 characters)"),
741 ({"search": {"fields": ["note"], "result_fields": "id"}}, "widgets: search.result_fields must be a list of field names"),
742 ({"views": {"list_fields": "note"}}, "widgets: views.list_fields must be a list of field names such as"),
743 ({"views": {"detail_fields": {"a": 1}}}, "widgets: views.detail_fields must be a list"),
744 ({"views": {"filter_fields": [3]}}, "widgets: views.filter_fields: 3 is not a field name"),
745 ({"views": {"board": "status"}}, "widgets: views.board must be an object, not 'status'"),
746 ({"views": {"board": {"group_field": "a b"}}}, "widgets: views.board: group_field 'a b' is not a field name"),
747 ({"views": {"calendar": {"date_field": ""}}}, "widgets: views.calendar: date_field '' is not a field name"),
748 ({"views": {"related": "gadgets"}}, "widgets: views.related must be a list of"),
749 ({"views": {"related": ["gadgets"]}}, "widgets: views.related[0] must be an object with collection and fk_field"),
750 ({"views": {"related": [{"collection": "gadgets"}]}}, "widgets: views.related[0]: no fk_field"),
751 ({"views": {"related": [{"collection": "bad name", "fk_field": "w"}]}},
752 "widgets: views.related[0]: collection 'bad name' is not a collection name"),
753 ({"views": {"related": [{"collection": "gadgets", "fk_field": "a b"}]}},
754 "widgets: views.related[0]: fk_field 'a b' is not a field name"),
755 ({"blocks": {"feed": "x"}}, "widgets: blocks.feed must be an object, not 'x'"),
756 ({"blocks": {"feed": {"owner_field": "note"}}}, "widgets: blocks.feed: no time_field"),
757 ({"blocks": {"feed": {"owner_field": "note", "time_field": "note", "summary_fields": "note"}}},
758 "widgets: blocks.feed.summary_fields must be a list of field names"),
759 ({"blocks": {"feed": {"owner_field": "note", "time_field": "note", "visibility_true_value": 1}}},
760 "widgets: blocks.feed: visibility_true_value must be text, not 1"),
761])
762def test_a_section_of_the_wrong_shape_refuses_the_install_and_says_where(tmp_path, root, expected):
763 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(**root))
764 assert "schemas/widgets.json" in message
765 assert expected in message
766
767
768def test_every_section_shape_dron_defines_is_accepted():
769 import object_schemas
770
771 object_schemas.normalize_declaration("widgets", _schema_with(
772 title="Widgets", description="Things.", hooks={"before_write": "hook_widgets"}, ui={"icon": "box"},
773 capabilities={"comments": True}, search={"fields": ["note"], "result_fields": ["id"]},
774 forms={"default": {"fields": ["note"]}, "wide": {"fields": ["note"], "columns": 2}},
775 views={"list_mode": "board", "list_fields": ["note"], "board": {"group_field": "note"},
776 "tree": {"parent_field": "note"}, "calendar": {"date_field": "note"},
777 "related": [{"collection": "gadgets", "fk_field": "widget_id"}]},
778 blocks={"feed": {"owner_field": "note", "time_field": "note", "visibility_true_value": "yes",
779 "summary_fields": ["note"], "link_field": "note"}}))
780
781
782@pytest.mark.parametrize("field,expected", [
783 ({"label": 5}, "widgets: field 'note': label must be text, not 5"),
784 ({"label": ["Note"]}, "field 'note': label must be text, not ['Note']"),
785 ({"help": 1}, "field 'note': help must be text, not 1"),
786 ({"placeholder": None}, "field 'note': placeholder must be text, not None"),
787 ({"description": {"a": 1}}, "field 'note': description must be text, not {'a': 1}"),
788 ({"default": ["a"]},
789 "field 'note': default must be one text, number or true/false value (or null), not ['a']"),
790 ({"default": {"a": 1}}, "field 'note': default must be one text"),
791 ({"ui": "wide"}, "field 'note': ui must be an object, not 'wide'"),
792 ({"layout": []}, "field 'note': layout must be an object, not []"),
793 ({"validation": "required"}, "field 'note': validation must be an object, not 'required'"),
794 ({"enum": []}, "field 'note': enum must list at least one allowed value"),
795 ({"enum": ["a", ["b"]]}, "field 'note': enum value ['b'] must be text, a number or true/false"),
796 ({"enum": ["a", "a"]}, "field 'note': enum value 'a' is listed twice"),
797 ({"store": "main"}, 'field \'note\': store must be "extra" (the only value DRON defines), not \'main\''),
798 ({"visible_when": "status"},
799 'field \'note\' visible_when must be an object such as {"field": "kind", "equals": "asset"}, not \'status\''),
800 ({"visible_when": {"equals": "x"}},
801 "field 'note' visible_when: no field (the field whose value decides whether this one shows)"),
802 ({"visible_when": {"field": "a b", "equals": "x"}}, "field 'note' visible_when: field 'a b' is not a field name"),
803 ({"visible_when": {"field": "id", "equals": 1}}, "field 'note' visible_when: equals must be text, not 1"),
804 ({"visible_when": {"field": "id", "in": "a"}}, "field 'note' visible_when: in must be a list of text values, not 'a'"),
805])
806def test_a_field_value_of_the_wrong_kind_refuses_the_install_and_says_where(tmp_path, field, expected):
807 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(field))
808 assert "schemas/widgets.json" in message
809 assert expected in message
810
811
812def test_the_field_values_dron_defines_are_accepted():
813 import object_schemas
814
815 for field in (
816 {"label": "Note", "help": "h", "placeholder": "p", "description": "d"},
817 {"default": "x"}, {"default": 3}, {"default": True}, {"default": None},
818 {"ui": {"rows": 4}, "layout": {"width": "half"}, "validation": {}},
819 {"enum": ["a", 2, True], "type": "enum"}, {"store": "extra"},
820 {"visible_when": {"field": "id", "equals": "x"}}, {"visible_when": {"field": "id", "in": ["a", "b"]}},
821 ):
822 object_schemas.normalize_declaration("widgets", _schema_with(field))
823
824
825@pytest.mark.parametrize("permissions,expected", [
826 # The engine reads a list only under edit, read or hidden and raised at
827 # the first request that touched the field.
828 ({"owner": ["role:a"]},
829 "field 'note' permissions.owner: a list of principals belongs under edit, read or hidden, "
830 "as {\"edit\": ['owner']}; give a principal one access level instead, as {'owner': \"read\"}"),
831 ({"role:admin": ["role:a"]}, "permissions.role:admin: a list of principals belongs under edit, read or hidden"),
832 ({"write": ["role:a"]}, "field 'note' permissions.write: 'write' is not DRON; write 'edit' for a list of principals"),
833 ({"Hidden": ["public"]}, "permissions.Hidden: 'Hidden' is not DRON; write 'hidden' for a list of principals"),
834 ({"default": ["edit"]}, "field 'note' permissions.default: access must be edit, read or hidden, not ['edit']"),
835 ({"edit": [""]}, "permissions.edit: a principal must be non-empty text"),
836])
837def test_a_field_permission_list_under_a_key_the_engine_ignores_refuses_the_install(tmp_path, permissions, expected):
838 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with({"permissions": permissions}))
839 assert "schemas/widgets.json" in message
840 assert expected in message
841
842
843def test_a_list_of_principals_under_edit_read_and_hidden_is_accepted():
844 import object_schemas
845
846 object_schemas.normalize_declaration("widgets", _schema_with({"permissions": {
847 "edit": ["role:admin"], "read": ["registered"], "hidden": ["public"], "default": "read"}}))
848
849
850@pytest.mark.parametrize("root,expected", [
851 ({"name": ""}, "widgets: name '' is not a collection name"),
852 ({"name": None}, "widgets: name None is not a collection name"),
853 ({"unique": [{"fields": ["note"], "message": None}]}, "widgets: unique[0]: message must be text, not None"),
854 ({"locked_when": [{"when": {"note": "x"}, "message": 5}]}, "widgets: locked_when[0]: message must be text, not 5"),
855])
856def test_a_blank_name_or_a_message_that_is_not_text_refuses_the_install(tmp_path, root, expected):
857 message = _refused_install_and_dry_run(tmp_path, schema=_schema_with(**root))
858 assert expected in message
859
860
861@pytest.mark.parametrize("stored", [
862 pytest.param(_schema_with({"validation": {"min": "abc"}}), id="a min that is not a number"),
863 pytest.param(_schema_with({"permissions": {"default": "maybe", "owner": "readonly"}}),
864 id="a field permission level that is not one"),
865 pytest.param(_schema_with({"relation": {"display_field": "name"}}), id="a relation with no collection"),
866 pytest.param(_schema_with({"formula": "id + 1"}), id="a formula on a field that is not computed"),
867 pytest.param(_schema_with({"rollup": GOOD_ROLLUP}), id="a rollup on a field that is not computed"),
868 pytest.param(_schema_with(_rollup(op="median", field=None)), id="a rollup that could never compute"),
869 pytest.param(_schema_with(hooks={"before_write": "bad name!"}), id="a hook name that is not an object id"),
870 pytest.param(_schema_with(views={"list_mode": "grid"}), id="a list mode that is not one"),
871 pytest.param(_schema_with({"validation": {"min_length": "3", "max_length": 2.5, "pattern": "("}}),
872 id="a length or pattern the engine would misread"),
873 pytest.param(_schema_with({**_rollup_field(where=["status"], fk_field="1x"), "formula": "id + 1"}),
874 id="a field with a formula and a rollup with names that are not names"),
875 pytest.param(_schema_with(hooks="hook_widgets", capabilities=["comments"], ui="compact",
876 views={"list_fields": "note", "related": "gadgets"}),
877 id="a section of the wrong shape"),
878 pytest.param(_schema_with({"permissions": {"owner": ["role:a"]}}), id="a list of principals under a principal"),
879 pytest.param(_schema_with({"label": 5, "default": ["a"], "ui": "wide", "visible_when": {"equals": "x"}}),
880 id="a field value of the wrong kind"),
881 pytest.param(_schema_with({"relation": {"collection": "gadgets", "display_field": "full name"}}),
882 id="a relation display field that is not a name"),
883 pytest.param(_schema_with({"type": "integer", "validation": {"exclusive_min": "1_0"}}),
884 id="an exclusive bound written with an underscore"),
885])
886def test_a_stored_schema_keeps_loading_with_a_value_dron_refuses(tmp_path, stored):
887 """A box must not stop reading its own data over a value: what is already
888 stored and what an operator saves through the schema API stay as lenient as
889 before. Only a package declaration is held to DRON."""
890 import object_schemas
891
892 saved = object_schemas.replace_schema("widgets", stored, base_dir=tmp_path)
893 assert object_schemas.get_schema("widgets", base_dir=tmp_path) == saved
894 assert object_schemas.normalize_schema("widgets", saved) == saved
895 # Nothing the declaration said was dropped or corrected on the way in.
896 for key, value in stored.items():
897 if key != "fields":
898 assert saved[key] == value, key
899 for given, kept in zip(stored["fields"], saved["fields"]):
900 for key, value in given.items():
901 assert kept[key] == value, key