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_validation_exclusive_required_when.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_validation_exclusive_required_when.py · 11.2 KB · 262 lines
1"""Strict bounds and conditional required fields, declared on the field.
2
3`validation.exclusive_min` / `exclusive_max` (strictly greater / less) and
4`validation.required_when` (non-blank while the stored-after-write record
5matches `{field: value | [values]}`) are checked by object_records next to
6`min` / `max` / `required`, so every writer meets them, HTTP and storage
7level, on create and on update. Three shipped hooks used to say the same
8things in code ("quantity must be positive", "a matched line names its
9target"); the claim worth pinning is that the declaration refuses what the
10hook refused, for the writers the hook never reached.
11"""
12
13import json
14from pathlib import Path
15
16import pytest
17
18import object_records
19import object_schemas
20import object_server
21from test_object_server import TEST_ADMIN_TOKEN, enable_admin_token, request
22
23AUTH = [("authorization", f"Token {TEST_ADMIN_TOKEN}")]
24
25FIELDS = [
26 {"name": "id"},
27 {"name": "quantity", "type": "number", "validation": {"exclusive_min": 0}},
28 {"name": "count", "type": "integer",
29 "validation": {"exclusive_min": 0, "exclusive_max": 10}},
30 {"name": "match_status", "type": "enum", "default": "open",
31 "enum": ["open", "matched", "resolved"]},
32 {"name": "target", "type": "text",
33 "validation": {"required_when": {"match_status": "matched"}}},
34 {"name": "flagged", "type": "boolean", "default": "false"},
35 {"name": "note", "type": "text",
36 "validation": {"required_when": {"match_status": ["matched", "resolved"],
37 "flagged": "true"}}},
38]
39
40
41def stage(tmp_path, fields=FIELDS, storage=None):
42 data_dir = tmp_path / "data"
43 schema = {"name": "things", "version": 1, "fields": fields}
44 if storage:
45 schema["storage"] = storage
46 (data_dir / "schemas").mkdir(parents=True, exist_ok=True)
47 (data_dir / "schemas" / "things.json").write_text(json.dumps(schema))
48 return data_dir
49
50
51def create(data_dir, record_id, **fields):
52 return object_records.create_collection_record(
53 "things", {"id": record_id, **fields}, base_dir=data_dir, roots=[])
54
55
56def update(data_dir, record_id, **changes):
57 return object_records.update_collection_record(
58 "things", record_id, changes, base_dir=data_dir, roots=[])
59
60
61def stored(data_dir):
62 return {row["id"]: row for row in
63 object_records.read_collection_records("things", base_dir=data_dir, roots=[])}
64
65
66@pytest.fixture(params=["classic", "append"])
67def storage(request):
68 return request.param
69
70
71# --- the declarations -----------------------------------------------------------
72
73
74def test_the_declarations_survive_normalization_and_required_when_values_become_lists():
75 schema = object_schemas.normalize_schema("things", {"name": "things", "fields": FIELDS})
76 by_name = {field["name"]: field for field in schema["fields"]}
77 assert by_name["quantity"]["validation"] == {"exclusive_min": 0}
78 assert by_name["target"]["validation"] == {"required_when": {"match_status": ["matched"]}}
79 again = object_schemas.normalize_schema("things", schema)
80 assert again["fields"] == schema["fields"]
81
82
83def _with(validation, **field):
84 return [{"name": "id"},
85 {"name": "match_status", "type": "text"},
86 {"name": "quantity", "type": "number", "validation": validation, **field}]
87
88
89@pytest.mark.parametrize("validation", [
90 {"exclusive_min": "lots"},
91 {"exclusive_min": True}, # a bool is not a bound
92 {"exclusive_max": None},
93 {"exclusive_min": [0]},
94 {"exclusive_min": "nan"},
95 {"exclusive_max": "inf"},
96 {"exclusive_min": 5, "exclusive_max": 5}, # no value is allowed
97 {"exclusive_min": 5, "exclusive_max": 3},
98 {"exclusive_min": 5, "max": 5}, # strictly above 5 and at most 5
99 {"min": 5, "exclusive_max": 5},
100 {"required_when": ["match_status"]}, # not the field: value shape
101 {"required_when": {}}, # always true is not a state
102 {"required_when": "matched"},
103 {"required_when": {"match_status": []}},
104 {"required_when": {"match_status": [3]}},
105 {"required_when": {"match_status": {"is": "x"}}},
106 {"required_when": {"quantity": "1"}}, # depends on itself
107 {"required_when": {"no such field": "x"}},
108 {"required_when": {"ghost_field": "x"}}, # a typo would never apply
109], ids=lambda value: json.dumps(value))
110def test_a_malformed_declaration_is_refused_not_ignored(validation):
111 with pytest.raises(ValueError):
112 object_schemas.normalize_schema(
113 "things", {"name": "things", "fields": _with(validation)})
114
115
116def test_an_exclusive_bound_on_a_text_field_is_refused():
117 fields = [{"name": "id"}, {"name": "label", "type": "text",
118 "validation": {"exclusive_min": 0}}]
119 with pytest.raises(ValueError, match="numeric"):
120 object_schemas.normalize_schema("things", {"name": "things", "fields": fields})
121
122
123def test_required_when_on_a_computed_field_is_refused():
124 fields = [{"name": "id"}, {"name": "status", "type": "text"},
125 {"name": "total", "type": "computed", "formula": "1 + 1",
126 "validation": {"required_when": {"status": "x"}}}]
127 with pytest.raises(ValueError, match="computed or read-only"):
128 object_schemas.normalize_schema("things", {"name": "things", "fields": fields})
129
130
131# --- exclusive bounds -----------------------------------------------------------
132
133
134@pytest.mark.parametrize("value", ["0", "0.0", "-1", "-0.0000001"])
135def test_a_value_at_or_below_an_exclusive_min_is_refused_and_nothing_is_written(
136 tmp_path, storage, value):
137 data_dir = stage(tmp_path, storage=storage)
138 with pytest.raises(object_records.InvalidRecordPayloadError,
139 match="'quantity' must be greater than 0"):
140 create(data_dir, "t1", quantity=value)
141 assert stored(data_dir) == {}
142
143
144@pytest.mark.parametrize("value", ["0.0000001", "1", "1e-9", "0.5"])
145def test_a_value_just_above_an_exclusive_min_is_accepted(tmp_path, value):
146 data_dir = stage(tmp_path)
147 assert create(data_dir, "t1", quantity=value)["quantity"] == value
148
149
150def test_exclusive_max_refuses_the_bound_itself(tmp_path, storage):
151 data_dir = stage(tmp_path, storage=storage)
152 assert create(data_dir, "t1", count="9")["count"] == "9"
153 for value in ("10", "11"):
154 with pytest.raises(object_records.InvalidRecordPayloadError,
155 match="'count' must be less than 10"):
156 create(data_dir, "t2", count=value)
157
158
159def test_an_update_to_the_bound_is_refused_and_a_blank_value_is_not_a_value(tmp_path):
160 data_dir = stage(tmp_path)
161 create(data_dir, "t1", quantity="2")
162 with pytest.raises(object_records.InvalidRecordPayloadError, match="greater than 0"):
163 update(data_dir, "t1", quantity="0")
164 assert stored(data_dir)["t1"]["quantity"] == "2"
165 # Like min and max: an absent value is for `required` to refuse, not a bound.
166 assert create(data_dir, "t2")["id"] == "t2"
167 assert update(data_dir, "t1", match_status="resolved")["quantity"] == "2"
168
169
170def test_a_non_number_is_still_the_type_error(tmp_path):
171 data_dir = stage(tmp_path)
172 with pytest.raises(object_records.InvalidRecordPayloadError, match="must be a number"):
173 create(data_dir, "t1", quantity="lots")
174
175
176# --- required_when --------------------------------------------------------------
177
178
179def test_a_blank_field_is_refused_while_the_condition_holds(tmp_path, storage):
180 data_dir = stage(tmp_path, storage=storage)
181 for blank in ({}, {"target": ""}, {"target": " "}):
182 with pytest.raises(object_records.InvalidRecordPayloadError,
183 match="'target' is required when match_status is matched"):
184 create(data_dir, "t1", match_status="matched", **blank)
185 assert stored(data_dir) == {}
186 assert create(data_dir, "t1", match_status="matched", target="payments/p1")["target"]
187 assert create(data_dir, "t2", match_status="open")["id"] == "t2"
188
189
190def test_an_update_is_judged_on_the_record_as_it_will_be_stored(tmp_path, storage):
191 data_dir = stage(tmp_path, storage=storage)
192 create(data_dir, "t1")
193 with pytest.raises(object_records.InvalidRecordPayloadError, match="'target' is required"):
194 update(data_dir, "t1", match_status="matched")
195 assert stored(data_dir)["t1"]["match_status"] == "open"
196 # The write that sets the condition may also set the field ...
197 assert update(data_dir, "t1", match_status="matched", target="payments/p1")["target"]
198 # ... a write that leaves the field alone is judged by what is stored ...
199 assert update(data_dir, "t1", match_status="matched")["target"] == "payments/p1"
200 # ... one that blanks it while the condition holds is refused ...
201 with pytest.raises(object_records.InvalidRecordPayloadError, match="'target' is required"):
202 update(data_dir, "t1", target="")
203 # ... and moving out of the state frees the field.
204 assert update(data_dir, "t1", match_status="open", target="")["target"] == ""
205
206
207def test_every_condition_must_hold_and_each_may_list_values(tmp_path):
208 data_dir = stage(tmp_path)
209 assert create(data_dir, "t1", match_status="matched", target="a/b")["id"] == "t1"
210 assert create(data_dir, "t2", flagged="true", match_status="open")["id"] == "t2"
211 for status in ("matched", "resolved"):
212 with pytest.raises(object_records.InvalidRecordPayloadError,
213 match="'note' is required when match_status is one of "
214 "matched, resolved and flagged is true"):
215 create(data_dir, "t3", match_status=status, target="a/b", flagged="true")
216
217
218def test_a_boolean_condition_matches_however_it_was_spelled(tmp_path):
219 data_dir = stage(tmp_path)
220 for spelling in ("True", "1", "yes"):
221 with pytest.raises(object_records.InvalidRecordPayloadError, match="'note' is required"):
222 create(data_dir, "t1", match_status="resolved", flagged=spelling)
223
224
225# --- over HTTP ------------------------------------------------------------------
226
227
228def http_site(tmp_path, monkeypatch):
229 data_dir = stage(tmp_path)
230 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
231 enable_admin_token(monkeypatch)
232 return data_dir
233
234
235def post(record):
236 return request("/collections/things/records", method="POST",
237 body=json.dumps(record).encode("utf-8"), headers=AUTH)
238
239
240def put(record_id, changes):
241 return request(f"/collections/things/records/{record_id}", method="PUT",
242 body=json.dumps(changes).encode("utf-8"), headers=AUTH)
243
244
245def test_a_refusal_over_http_is_the_ordinary_400(tmp_path, monkeypatch):
246 data_dir = http_site(tmp_path, monkeypatch)
247
248 status, _, payload = post({"id": "t1", "quantity": "0"})
249 assert status == 400
250 assert payload["status"] == "error"
251 assert "'quantity' must be greater than 0" in payload["error"]
252
253 status, _, payload = post({"id": "t1", "match_status": "matched"})
254 assert status == 400
255 assert "'target' is required when match_status is matched" in payload["error"]
256 assert stored(data_dir) == {}
257
258 assert post({"id": "t1", "quantity": "2"})[0] == 201
259 status, _, payload = put("t1", {"match_status": "matched"})
260 assert status == 400
261 assert "'target' is required" in payload["error"]
262 assert put("t1", {"match_status": "matched", "target": "payments/p1"})[0] == 200