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_collection_membership.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_collection_membership.py · 11.9 KB · 266 lines
1"""get_schema asks "is this name a collection" without summarising every object.
2
3`object_schemas.get_schema` used to answer that for a name with no schema file
4by calling `object_collections.list_collections()`, which reads every object's
5state file, lists its files and probes its logs. The server asks it on every
6site-route request (`site_hosts`), so the question is now answered by
7`object_collections.is_known_collection`. These tests hold the two answers
8together: the old listing is the oracle, and nothing is cached, so every kind
9of change on disk has to show on the very next call.
10"""
11
12import json
13import os
14from pathlib import Path
15
16import pytest
17
18import object_collections
19import object_permission_store
20import object_permissions
21import object_schemas
22import object_state
23
24
25def write_source(path: Path) -> None:
26 path.parent.mkdir(parents=True, exist_ok=True)
27 path.write_text("def GET(request):\n return {}\n")
28
29
30def write_records(data_dir: Path, collection: str) -> Path:
31 path = data_dir / "collections" / collection / "records.tsv"
32 path.parent.mkdir(parents=True, exist_ok=True)
33 path.write_text("id\tname\nr1\tAda\n")
34 return path
35
36
37def write_schema(data_dir: Path, name: str) -> Path:
38 path = data_dir / "schemas" / f"{name}.json"
39 path.parent.mkdir(parents=True, exist_ok=True)
40 path.write_text(json.dumps({"fields": [{"name": "id"}]}))
41 return path
42
43
44def save_rules(data_dir: Path, *collections: str) -> None:
45 object_permission_store.save_policy(
46 object_permissions.PermissionPolicy(
47 access_mode="role_based",
48 rules=tuple(
49 object_permissions.PermissionRule.allow(
50 "registered", {object_permissions.READ}, collection=name
51 )
52 for name in collections
53 )
54 + (
55 object_permissions.PermissionRule.allow(
56 "public", {object_permissions.EXECUTE}, object_id="site_home"
57 ),
58 ),
59 ),
60 base_dir=data_dir,
61 )
62
63
64def listed_names(data_dir: Path, root: Path) -> set[str]:
65 """The oracle: the names the full listing reports."""
66 return {
67 item["name"]
68 for item in object_collections.list_collections(base_dir=data_dir, roots=[root])
69 }
70
71
72def known(name: str, data_dir: Path, root: Path) -> bool:
73 return object_collections.is_known_collection(name, base_dir=data_dir, roots=[root])
74
75
76@pytest.fixture
77def staged(tmp_path):
78 root = tmp_path / "objects"
79 data_dir = tmp_path / "data"
80 write_source(root / "site" / "home.py")
81 write_source(root / "action" / "nav_entries.py")
82 write_source(root / "deep" / "er" / "thing.py")
83 write_source(root / "rootlevel.py")
84 write_source(root / "top_level_named.py")
85 write_source(root / "users" / "42" / "deals.py")
86 write_source(root / "users" / "42" / "pipeline_report.py")
87 write_source(root / "_private" / "hidden.py")
88 write_records(data_dir, "loose_rows")
89 write_records(data_dir, "invoices")
90 write_schema(data_dir, "invoices")
91 write_schema(data_dir, "schema_only")
92 save_rules(data_dir, "rule_only", "invoices")
93 return data_dir, root
94
95
96CANDIDATES = [
97 "site", "action", "deep", "er", "deep_er", "rootlevel", "top", "top_level_named", "users", "u",
98 "deals", "pipeline", "pipeline_report", "u_42_deals", "_private", "hidden", "loose_rows", "invoices",
99 "schema_only", "rule_only", "site_hosts", "site_home", "nope", "Site", "LOOSE_ROWS", "Invoices",
100 "RULE_ONLY", "schema_Only", "bad!name", "", "a" * 65, "records", "collections", "schemas",
101]
102
103
104def test_membership_agrees_with_the_full_listing_for_every_kind_of_name(staged):
105 """One disagreement here is a request that used to work now answering
106 404 (or the reverse). The mixed-case names matter on a case-insensitive
107 filesystem, where a bare exists() check says yes to a name the listing
108 spells differently."""
109 data_dir, root = staged
110 names = listed_names(data_dir, root)
111 assert {"site", "action", "deep", "rootlevel", "top", "deals", "pipeline", "loose_rows",
112 "invoices", "schema_only", "rule_only"} <= names
113
114 for candidate in CANDIDATES:
115 assert known(candidate, data_dir, root) is (candidate in names), candidate
116
117
118def test_collection_names_is_the_listing_without_the_summaries(staged):
119 data_dir, root = staged
120 assert object_collections.collection_names(base_dir=data_dir, roots=[root]) == listed_names(data_dir, root)
121
122
123def test_membership_with_nothing_on_disk(tmp_path):
124 assert known("anything", tmp_path / "data", tmp_path / "objects") is False
125 assert object_collections.collection_names(
126 base_dir=tmp_path / "data", roots=[tmp_path / "objects"]
127 ) == set()
128
129
130def test_a_rule_added_or_removed_is_seen_by_the_next_call(staged):
131 data_dir, root = staged
132 assert known("fresh_rule", data_dir, root) is False
133 save_rules(data_dir, "rule_only", "invoices", "fresh_rule")
134 assert known("fresh_rule", data_dir, root) is True
135 object_schemas.get_schema("fresh_rule", base_dir=data_dir, roots=[root])
136 save_rules(data_dir, "invoices")
137 assert known("fresh_rule", data_dir, root) is False
138 assert known("rule_only", data_dir, root) is False
139 with pytest.raises(object_schemas.SchemaNotFoundError):
140 object_schemas.get_schema("fresh_rule", base_dir=data_dir, roots=[root])
141
142
143def test_a_policy_file_edited_by_hand_is_seen_by_the_next_call(staged):
144 data_dir, root = staged
145 policy_file = data_dir / "permissions" / "policy.json"
146 assert known("rule_only", data_dir, root) is True
147 text = policy_file.read_text()
148 policy_file.write_text(text.replace("rule_only", "rule_wxyz")) # same size, same instant
149 assert known("rule_only", data_dir, root) is False
150 assert known("rule_wxyz", data_dir, root) is True
151 policy_file.unlink()
152 assert known("rule_wxyz", data_dir, root) is False
153
154
155def test_a_records_file_created_or_deleted_is_seen_by_the_next_call(staged):
156 data_dir, root = staged
157 assert known("just_rows", data_dir, root) is False
158 path = write_records(data_dir, "just_rows")
159 assert known("just_rows", data_dir, root) is True
160 assert object_schemas.get_schema("just_rows", base_dir=data_dir, roots=[root])["source"] == "derived"
161 path.unlink()
162 assert known("just_rows", data_dir, root) is False
163 with pytest.raises(object_schemas.SchemaNotFoundError):
164 object_schemas.get_schema("just_rows", base_dir=data_dir, roots=[root])
165
166
167def test_an_object_file_created_or_deleted_is_seen_by_the_next_call(staged):
168 """Installing a package's objects makes their category a collection;
169 removing the last object of a category takes it away again."""
170 data_dir, root = staged
171 assert known("webhook", data_dir, root) is False
172 write_source(root / "webhook" / "stripe.py")
173 assert known("webhook", data_dir, root) is True
174 assert object_schemas.get_schema("webhook", base_dir=data_dir, roots=[root])["source"] == "derived"
175 (root / "webhook" / "stripe.py").unlink()
176 assert known("webhook", data_dir, root) is False
177 with pytest.raises(object_schemas.SchemaNotFoundError):
178 object_schemas.get_schema("webhook", base_dir=data_dir, roots=[root])
179
180 write_source(root / "users" / "7" / "ledger_view.py")
181 assert known("ledger", data_dir, root) is True
182 (root / "users" / "7" / "ledger_view.py").unlink()
183 assert known("ledger", data_dir, root) is False
184
185
186def test_a_schema_file_created_or_deleted_is_seen_by_the_next_call(staged):
187 data_dir, root = staged
188 with pytest.raises(object_schemas.SchemaNotFoundError):
189 object_schemas.get_schema("late_schema", base_dir=data_dir, roots=[root])
190 path = write_schema(data_dir, "late_schema")
191 assert known("late_schema", data_dir, root) is True
192 assert object_schemas.get_schema("late_schema", base_dir=data_dir, roots=[root])["source"] == "manual"
193 path.unlink()
194 assert known("late_schema", data_dir, root) is False
195 with pytest.raises(object_schemas.SchemaNotFoundError):
196 object_schemas.get_schema("late_schema", base_dir=data_dir, roots=[root])
197
198
199def test_a_dangling_schema_or_records_symlink_still_counts_as_the_listing_counts_it(staged):
200 data_dir, root = staged
201 os.symlink(data_dir / "missing-target.json", data_dir / "schemas" / "dangling.json")
202 (data_dir / "collections" / "dangling_rows").mkdir()
203 os.symlink(data_dir / "missing-target.tsv", data_dir / "collections" / "dangling_rows" / "records.tsv")
204 names = listed_names(data_dir, root)
205 for candidate in ("dangling", "dangling_rows"):
206 assert known(candidate, data_dir, root) is (candidate in names), candidate
207
208
209def test_the_listing_reports_a_dangling_records_symlink_on_every_python(staged):
210 """A glob whose last part is a plain name asks exists() on Python 3.10-3.11
211 and lexists() on 3.12+, so the listing and the lookup disagreed about a
212 dangling records.tsv symlink on the older ones (red CI, invisible on a
213 newer laptop). The listing must say lexists() everywhere, and a records
214 file in a symlinked directory still counts."""
215 data_dir, root = staged
216 (data_dir / "collections" / "dangling_rows").mkdir()
217 os.symlink(data_dir / "missing-target.tsv", data_dir / "collections" / "dangling_rows" / "records.tsv")
218 real = data_dir / "elsewhere"
219 real.mkdir()
220 (real / "records.tsv").write_text("id\tname\nr1\tAda\n")
221 os.symlink(real, data_dir / "collections" / "linked_rows")
222 (data_dir / "collections" / "no_records").mkdir()
223 (data_dir / "collections" / "a_plain_file").write_text("not a directory")
224 names = object_collections._iter_record_collections(data_dir)
225 assert "dangling_rows" in names and "linked_rows" in names
226 assert "no_records" not in names and "a_plain_file" not in names
227 assert names == sorted(names, key=lambda name: (data_dir / "collections" / name / "records.tsv").as_posix())
228
229
230def test_get_schema_for_a_name_without_a_schema_reads_no_object_state(staged, monkeypatch):
231 """The cost this replaces: one state-file read per installed object, on
232 every site-route request. If get_schema goes back to the full listing
233 this fails."""
234 data_dir, root = staged
235
236 def no_state_reads(*args, **kwargs):
237 raise AssertionError("get_schema must not read object state")
238
239 monkeypatch.setattr(object_state, "get_object_state", no_state_reads)
240 monkeypatch.setattr(object_collections.object_state, "get_object_state", no_state_reads)
241
242 assert object_schemas.get_schema("site", base_dir=data_dir, roots=[root])["source"] == "derived"
243 assert object_schemas.get_schema("loose_rows", base_dir=data_dir, roots=[root])["source"] == "derived"
244 assert object_schemas.get_schema("rule_only", base_dir=data_dir, roots=[root])["source"] == "derived"
245 with pytest.raises(object_schemas.SchemaNotFoundError):
246 object_schemas.get_schema("site_hosts", base_dir=data_dir, roots=[root])
247 summaries = object_schemas.list_schemas(base_dir=data_dir, roots=[root])
248 assert {item["name"] for item in summaries} == {
249 "site", "action", "deep", "rootlevel", "top", "deals", "pipeline", "loose_rows", "invoices",
250 "schema_only", "rule_only",
251 }
252
253
254def test_a_policy_file_that_cannot_be_parsed_still_fails_the_lookup(staged):
255 """Fail closed: a name must not quietly become "known" or "unknown"
256 while the policy cannot be read. The full listing raised here, for
257 every name, whatever else made the name known."""
258 data_dir, root = staged
259 (data_dir / "permissions" / "policy.json").write_text("{ not json")
260 for name in ("site", "loose_rows", "rule_only", "site_hosts"):
261 with pytest.raises(ValueError, match="invalid JSON"):
262 object_schemas.get_schema(name, base_dir=data_dir, roots=[root])
263 with pytest.raises(ValueError, match="invalid JSON"):
264 object_collections.is_known_collection(name, base_dir=data_dir, roots=[root])
265 # A name with a schema file never consulted the policy, before or now.
266 assert object_schemas.get_schema("invoices", base_dir=data_dir, roots=[root])["source"] == "manual"