Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/tests/test_object_schemas.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_object_schemas.py · 13.6 KB · 436 lines
1import json
2from pathlib import Path
3
4import pytest
5
6import object_schemas
7
8
9def write_source(path: Path, content: str = "def GET(request):\n return {}\n") -> Path:
10 path.parent.mkdir(parents=True, exist_ok=True)
11 path.write_text(content)
12 return path
13
14
15def write_schema(data_dir: Path, name: str, payload: dict) -> Path:
16 path = data_dir / "schemas" / f"{name}.json"
17 path.parent.mkdir(parents=True, exist_ok=True)
18 path.write_text(json.dumps(payload))
19 return path
20
21
22def test_get_schema_returns_manual_schema_with_normalized_fields(tmp_path):
23 data_dir = tmp_path / "data"
24 write_schema(
25 data_dir,
26 "invoices",
27 {
28 "title": "Invoices",
29 "version": 2,
30 "fields": [
31 {
32 "name": "customer_id",
33 "type": "relation",
34 "required": True,
35 "relation": {"collection": "contacts"},
36 "validation": {"not_null": True},
37 },
38 {
39 "name": "total",
40 "type": "computed",
41 "computed": "sum(line_items)",
42 },
43 ],
44 },
45 )
46
47 schema = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
48
49 assert schema == {
50 "name": "invoices",
51 "title": "Invoices",
52 "source": "manual",
53 "version": 2,
54 "fields": [
55 {
56 "name": "customer_id",
57 "type": "relation",
58 "required": True,
59 "relation": {"collection": "contacts"},
60 "validation": {"not_null": True},
61 },
62 {
63 "name": "total",
64 "type": "computed",
65 "required": False,
66 "computed": "sum(line_items)",
67 },
68 ],
69 "field_count": 2,
70 }
71
72
73def test_get_schema_derives_empty_schema_for_existing_collection(tmp_path):
74 root = tmp_path / "objects"
75 write_source(root / "contacts" / "directory.py")
76
77 schema = object_schemas.get_schema("contacts", base_dir=tmp_path / "data", roots=[root])
78
79 assert schema == {
80 "name": "contacts",
81 "title": "Contacts",
82 "source": "derived",
83 "version": 1,
84 "fields": [],
85 "field_count": 0,
86 }
87
88
89def test_list_schemas_includes_manual_and_derived_collection_schemas(tmp_path):
90 root = tmp_path / "objects"
91 data_dir = tmp_path / "data"
92 write_source(root / "contacts" / "directory.py")
93 write_schema(
94 data_dir,
95 "invoices",
96 {
97 "title": "Invoices",
98 "fields": [{"name": "invoice_date", "type": "date", "required": True}],
99 },
100 )
101
102 schemas = object_schemas.list_schemas(base_dir=data_dir, roots=[root])
103
104 assert schemas == [
105 {
106 "name": "contacts",
107 "title": "Contacts",
108 "source": "derived",
109 "version": 1,
110 "field_count": 0,
111 },
112 {
113 "name": "invoices",
114 "title": "Invoices",
115 "source": "manual",
116 "version": 1,
117 "field_count": 1,
118 },
119 ]
120
121
122def test_get_schema_preserves_scroll_field_metadata(tmp_path):
123 data_dir = tmp_path / "data"
124 write_schema(
125 data_dir,
126 "invoices",
127 {
128 "fields": [
129 {
130 "name": "cost_price",
131 "type": "currency",
132 "label": "Cost Price",
133 "read_only": True,
134 "ui": {"widget": "money", "section": "totals"},
135 "layout": {"column": 2, "order": 5},
136 "permissions": {
137 "admin": "edit",
138 "sales": "hidden",
139 "viewer": "hidden",
140 },
141 "placeholder": "0.00",
142 "help": "Internal margin input",
143 }
144 ]
145 },
146 )
147
148 schema = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
149
150 assert schema["fields"] == [
151 {
152 "name": "cost_price",
153 "type": "currency",
154 "required": False,
155 "label": "Cost Price",
156 "read_only": True,
157 "ui": {"widget": "money", "section": "totals"},
158 "layout": {"column": 2, "order": 5},
159 "permissions": {
160 "admin": "edit",
161 "sales": "hidden",
162 "viewer": "hidden",
163 },
164 "placeholder": "0.00",
165 "help": "Internal margin input",
166 }
167 ]
168
169
170def test_get_schema_preserves_store_extra_field_attribute(tmp_path):
171 data_dir = tmp_path / "data"
172 write_schema(
173 data_dir,
174 "notes",
175 {
176 "fields": [
177 {"name": "title", "type": "text"},
178 {"name": "x_mood", "type": "text", "store": "extra"},
179 ]
180 },
181 )
182
183 schema = object_schemas.get_schema("notes", base_dir=data_dir, roots=[])
184
185 assert schema["fields"] == [
186 {"name": "title", "type": "text", "required": False},
187 {"name": "x_mood", "type": "text", "required": False, "store": "extra"},
188 ]
189
190 # normalize_schema round-trips the same attribute directly (no file I/O).
191 normalized = object_schemas.normalize_schema(
192 "notes",
193 {
194 "fields": [
195 {"name": "x_mood", "type": "text", "store": "extra"},
196 ]
197 },
198 )
199 assert normalized["fields"] == [
200 {"name": "x_mood", "type": "text", "required": False, "store": "extra"},
201 ]
202
203
204def test_replace_schema_writes_normalized_schema_atomically(tmp_path):
205 data_dir = tmp_path / "data"
206
207 schema = object_schemas.replace_schema(
208 "invoices",
209 {
210 "title": "Invoices",
211 "version": 2,
212 "ui": {"default_view": "form"},
213 "views": [{"name": "admin_invoice_form", "type": "form"}],
214 "fields": [
215 {
216 "name": "customer_id",
217 "type": "relation",
218 "required": True,
219 "relation": {"collection": "contacts"},
220 "permissions": {"admin": "edit", "sales": "read"},
221 }
222 ],
223 },
224 base_dir=data_dir,
225 )
226
227 assert schema == {
228 "name": "invoices",
229 "title": "Invoices",
230 "source": "manual",
231 "version": 2,
232 "fields": [
233 {
234 "name": "customer_id",
235 "type": "relation",
236 "required": True,
237 "relation": {"collection": "contacts"},
238 "permissions": {"admin": "edit", "sales": "read"},
239 }
240 ],
241 "field_count": 1,
242 "ui": {"default_view": "form"},
243 "views": [{"name": "admin_invoice_form", "type": "form"}],
244 }
245 assert object_schemas.get_schema("invoices", base_dir=data_dir, roots=[]) == schema
246
247
248def test_replace_schema_keeps_search_metadata(tmp_path):
249 data_dir = tmp_path / "data"
250
251 schema = object_schemas.replace_schema(
252 "notes",
253 {
254 "fields": [{"name": "id"}, {"name": "content"}],
255 "search": {"fields": ["content"], "result_fields": ["id", "content"]},
256 },
257 base_dir=data_dir,
258 )
259
260 assert schema["search"] == {"fields": ["content"], "result_fields": ["id", "content"]}
261 assert object_schemas.get_schema("notes", base_dir=data_dir, roots=[])["search"] == schema["search"]
262
263
264def test_replace_schema_rejects_mismatched_name(tmp_path):
265 with pytest.raises(ValueError, match="does not match"):
266 object_schemas.replace_schema(
267 "invoices",
268 {"name": "contacts", "fields": []},
269 base_dir=tmp_path / "data",
270 )
271
272
273def test_get_schema_rejects_unsafe_names(tmp_path):
274 with pytest.raises(object_schemas.InvalidSchemaNameError):
275 object_schemas.get_schema("../bad", base_dir=tmp_path / "data", roots=[])
276
277
278def test_get_schema_rejects_missing_schemas(tmp_path):
279 with pytest.raises(object_schemas.SchemaNotFoundError):
280 object_schemas.get_schema("missing", base_dir=tmp_path / "data", roots=[])
281
282
283def test_manual_schema_rejects_mismatched_collection_name(tmp_path):
284 data_dir = tmp_path / "data"
285 write_schema(data_dir, "invoices", {"name": "contacts", "fields": []})
286
287 with pytest.raises(ValueError, match="does not match"):
288 object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
289
290
291def test_manual_schema_rejects_invalid_field_name(tmp_path):
292 data_dir = tmp_path / "data"
293 write_schema(data_dir, "invoices", {"fields": [{"name": "bad.name"}]})
294
295 with pytest.raises(ValueError, match="invalid name"):
296 object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
297
298
299def test_get_schema_accepts_guarded_transition_entries(tmp_path):
300 data_dir = tmp_path / "data"
301 write_schema(
302 data_dir,
303 "tasks",
304 {
305 "fields": [
306 {"name": "id"},
307 {
308 "name": "status",
309 "type": "enum",
310 "enum": ["open", "closed"],
311 "transitions": {
312 "open": [{"to": "closed", "when": {"owner_id": "$user_id"}}],
313 "closed": ["open"],
314 },
315 },
316 ]
317 },
318 )
319
320 schema = object_schemas.get_schema("tasks", base_dir=data_dir, roots=[])
321
322 status_field = next(f for f in schema["fields"] if f["name"] == "status")
323 assert status_field["transitions"] == {
324 "open": [{"to": "closed", "when": {"owner_id": "$user_id"}}],
325 "closed": ["open"],
326 }
327
328
329def test_manual_schema_rejects_transition_entry_missing_to(tmp_path):
330 data_dir = tmp_path / "data"
331 write_schema(
332 data_dir,
333 "tasks",
334 {
335 "fields": [
336 {"name": "id"},
337 {
338 "name": "status",
339 "type": "enum",
340 "transitions": {"open": [{"when": {"owner_id": "$user_id"}}]},
341 },
342 ]
343 },
344 )
345
346 with pytest.raises(ValueError, match="'to'"):
347 object_schemas.get_schema("tasks", base_dir=data_dir, roots=[])
348
349
350def test_manual_schema_rejects_non_string_when_values(tmp_path):
351 data_dir = tmp_path / "data"
352 write_schema(
353 data_dir,
354 "tasks",
355 {
356 "fields": [
357 {"name": "id"},
358 {
359 "name": "status",
360 "type": "enum",
361 "transitions": {
362 "open": [{"to": "closed", "when": {"owner_id": 42}}]
363 },
364 },
365 ]
366 },
367 )
368
369 with pytest.raises(ValueError, match="'when' values"):
370 object_schemas.get_schema("tasks", base_dir=data_dir, roots=[])
371
372
373# --- Perf pass: schema cache ---
374
375
376def test_get_schema_cache_reflects_external_file_change(tmp_path):
377 """A schema file rewritten directly on disk (bypassing replace_schema)
378 must be visible on the next get_schema call -- the stat-signature check
379 the schema cache relies on."""
380 data_dir = tmp_path / "data"
381 write_schema(data_dir, "invoices", {"fields": [{"name": "id"}, {"name": "total"}]})
382
383 first = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
384 assert [f["name"] for f in first["fields"]] == ["id", "total"]
385
386 write_schema(
387 data_dir,
388 "invoices",
389 {"fields": [{"name": "id"}, {"name": "total"}, {"name": "paid"}]},
390 )
391
392 second = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
393 assert [f["name"] for f in second["fields"]] == ["id", "total", "paid"]
394
395
396def test_replace_schema_invalidates_cache_immediately(tmp_path):
397 data_dir = tmp_path / "data"
398 object_schemas.replace_schema("invoices", {"fields": [{"name": "id"}]}, base_dir=data_dir)
399 warm = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
400 assert [f["name"] for f in warm["fields"]] == ["id"]
401
402 object_schemas.replace_schema(
403 "invoices", {"fields": [{"name": "id"}, {"name": "total"}]}, base_dir=data_dir
404 )
405 updated = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
406 assert [f["name"] for f in updated["fields"]] == ["id", "total"]
407
408
409def test_public_schema_meta_endpoint_returns_structure(tmp_path, monkeypatch):
410 import object_server
411 from test_object_server import request, write_records
412 data_dir = tmp_path / "data"
413 write_records(data_dir, "links", "id\ttitle\turl\n")
414 schema_file = data_dir / "schemas" / "links.json"
415 schema_file.parent.mkdir(parents=True, exist_ok=True)
416 schema_file.write_text(json.dumps({
417 "fields": [{"name": "id"}, {"name": "title", "required": True}, {"name": "url"}],
418 "forms": {"default": {"fields": ["title", "url"]}},
419 "views": {"list_mode": "cards"},
420 "search": {"fields": ["title"]},
421 "capabilities": {"comments": True},
422 }))
423 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
424 # public — no auth needed (structure, not data)
425 status, _, payload = request("/api/schema/links")
426 assert status == 200
427 schema = payload["schema"]
428 assert [f["name"] for f in schema["fields"]] == ["id", "title", "url"]
429 assert schema["forms"]["default"]["fields"] == ["title", "url"]
430 assert schema["views"]["list_mode"] == "cards"
431 # capabilities surface in the public meta so a UI can wire generic
432 # behaviors (e.g. the comment thread) from the schema alone.
433 assert schema["capabilities"] == {"comments": True}
434 # unknown collection -> 404-ish (derived empty schema still returns; bad name -> 400)
435 status, _, _ = request("/api/schema/bad!name")
436 assert status == 400