Debian Codegraph @

tests/unit_tests/test_config_schema.py

raw
1 """The JSON Schema for a config file: what it accepts, and what it refuses.
2
3 A schema is only worth shipping if it is a schema, so most of what is here runs
4 a real validator over a real config document rather than asserting on the shape
5 of a dict. The two halves it has to get right are the same two the read path
6 does -- the keys a command owns, and the keys the adapter a profile names
7 declares -- and the interesting cases are all about the seam between them.
8 """
9
10 from __future__ import annotations
11
12 import json
13 from pathlib import Path
14 from typing import Any, Sequence
15
16 import pytest
17 from jsonschema import Draft202012Validator
18
19 from harlequin.config import Config, adapter_options_model, sluggify_option_name
20 from harlequin.config_schema import SCHEMA_ID, build_schema
21 from harlequin.hsql.cli import bare_command
22 from harlequin.options import (
23 AbstractOption,
24 FlagOption,
25 ListOption,
26 SelectOption,
27 TextOption,
28 )
29 from harlequin.plugins import adapter_names, load_adapter
30
31 REPO_ROOT = Path(__file__).resolve().parents[2]
32 BASE_SCHEMA_PATH = REPO_ROOT / "src" / "harlequin" / "schemas" / "config-v1.json"
33
34 FIX = "uv run python scripts/write_config_schema.py"
35 """What to run when the packaged base schema and the generator disagree."""
36
37 FAKE_OPTIONS: list[AbstractOption] = [
38 TextOption(name="host", description="Where the server is."),
39 TextOption(name="port", description="Which port it answers on."),
40 ListOption(name="extension", description="Load this extension. Repeatable."),
41 SelectOption(
42 name="sslmode",
43 description="How to negotiate TLS.",
44 choices=["disable", ("verify-full", "Verify the certificate")],
45 default="disable",
46 ),
47 FlagOption(name="no-verify", description="Skip certificate verification."),
48 ]
49 """One of every option type an adapter can declare, including the two shapes a
50 `SelectOption`'s choices come in."""
51
52
53 def schema_for(
54 adapters: dict[str, Sequence[AbstractOption] | None] | None,
55 ) -> dict[str, Any]:
56 """The schema for an installation, checked for being a schema at all."""
57 schema = build_schema(bare_command().params, adapters)
58 Draft202012Validator.check_schema(schema)
59 return schema
60
61
62 def validator(
63 adapters: dict[str, Sequence[AbstractOption] | None] | None,
64 ) -> Draft202012Validator:
65 return Draft202012Validator(schema_for(adapters))
66
67
68 def problems(check: Draft202012Validator, config: dict[str, Any]) -> list[str]:
69 return [error.message for error in check.iter_errors(config)]
70
71
72 def profile(check: Draft202012Validator, **keys: Any) -> list[str]:
73 return problems(check, {"profiles": {"p": keys}})
74
75
76 @pytest.fixture
77 def fake() -> Draft202012Validator:
78 """An installation with one adapter, which declares one of everything."""
79 return validator({"faux": FAKE_OPTIONS})
80
81
82 @pytest.fixture
83 def installed() -> Draft202012Validator:
84 """This machine, adapters and all -- the document the mode writes."""
85 return validator(
86 {
87 name: list(load_adapter(name).ADAPTER_OPTIONS or [])
88 for name in adapter_names()
89 }
90 )
91
92
93 # --- the top level, which the model owns -------------------------------------
94
95
96 def test_every_key_the_model_names_is_described() -> None:
97 """The schema and the parser have to agree on what a config file may say.
98
99 Which they do by construction -- the top level comes from `Config` -- so
100 this is what fails when a key added to the model needs a description.
101 """
102 described = schema_for({"faux": FAKE_OPTIONS})["properties"]
103 assert set(described) == set(Config.__struct_fields__)
104 assert all(described[key].get("description") for key in described)
105
106
107 def test_a_key_no_config_file_may_hold_is_an_error(fake: Draft202012Validator) -> None:
108 assert problems(fake, {"profile": {}})
109
110
111 def test_a_keymap_takes_the_three_properties_a_binding_has(
112 fake: Draft202012Validator,
113 ) -> None:
114 """The IDE refuses a fourth property by name, so the schema does too."""
115 assert not problems(
116 fake, {"keymaps": {"mine": [{"keys": "ctrl+j", "action": "quit"}]}}
117 )
118 assert problems(
119 fake, {"keymaps": {"mine": [{"keys": "ctrl+j", "action": "quit", "hue": 1}]}}
120 )
121 assert problems(fake, {"keymaps": {"mine": [{"keys": "ctrl+j"}]}})
122
123
124 # --- a profile: the command's keys, and its adapter's -------------------------
125
126
127 def test_a_profile_takes_the_commands_own_options(fake: Draft202012Validator) -> None:
128 assert not profile(fake, limit=1000, format="csv", tuples_only=True)
129
130
131 def test_a_profile_takes_the_options_of_the_adapter_it_names(
132 fake: Draft202012Validator,
133 ) -> None:
134 assert not profile(
135 fake,
136 adapter="faux",
137 host="db.example.com",
138 extension=["postgis"],
139 sslmode="verify-full",
140 no_verify=True,
141 )
142
143
144 def test_the_keys_described_are_the_fields_a_profile_is_parsed_into() -> None:
145 """The schema and the validator read one declaration rather than two.
146
147 Both go through `adapter_options_model()`, so an option the model drops --
148 a name that is not an identifier -- is one the schema does not describe
149 either, and a type the model learns arrives here without being taught.
150 """
151 options = {sluggify_option_name(o.name): o for o in FAKE_OPTIONS}
152 described = schema_for({"faux": FAKE_OPTIONS})["$defs"]["faux_options"]
153 assert set(described["properties"]) == set(
154 adapter_options_model("faux", options).__struct_fields__
155 )
156
157
158 def test_a_misspelled_option_is_an_error(fake: Draft202012Validator) -> None:
159 """The whole reason to build the schema from the declarations.
160
161 `reed_only` is dropped in silence by an adapter's constructor, so a schema
162 that left a profile open would be a schema that could not catch the one
163 typo that connects you read-write.
164 """
165 assert profile(fake, adapter="faux", reed_only=True)
166
167
168 def test_a_value_the_declared_choices_do_not_name_is_an_error(
169 fake: Draft202012Validator,
170 ) -> None:
171 assert profile(fake, adapter="faux", sslmode="verify-ful")
172
173
174 def test_an_option_declared_as_text_takes_the_number_toml_invites(
175 fake: Draft202012Validator,
176 ) -> None:
177 """`port = 5432` reaches the adapter as `"5432"`, so the schema takes it."""
178 assert not profile(fake, adapter="faux", port=5432)
179 assert not profile(fake, adapter="faux", port="5432")
180
181
182 def test_an_option_declared_as_a_list_has_to_be_written_as_one(
183 fake: Draft202012Validator,
184 ) -> None:
185 assert profile(fake, adapter="faux", extension="postgis")
186
187
188 def test_a_profile_that_names_no_adapter_takes_the_default_adapters_options(
189 installed: Draft202012Validator,
190 ) -> None:
191 """A profile with no `adapter` connects with duckdb, and takes its options."""
192 assert not profile(installed, md_token="secret")
193 assert profile(installed, md_toke="secret")
194
195
196 def test_one_adapters_options_are_not_anothers(
197 installed: Draft202012Validator,
198 ) -> None:
199 assert not profile(installed, adapter="sqlite", lock_timeout=3)
200 assert profile(installed, adapter="duckdb", lock_timeout=3)
201
202
203 def test_an_adapter_that_is_not_installed_is_an_error(
204 fake: Draft202012Validator,
205 ) -> None:
206 """Which is what makes it this installation's schema rather than the format's."""
207 assert profile(fake, adapter="duckdb")
208
209
210 def test_an_adapter_whose_options_could_not_be_read_leaves_a_profile_open() -> None:
211 """An adapter that will not import is a reason to say nothing, not to refuse.
212
213 Every key under a profile that names it would otherwise be reported as an
214 error, on the strength of a list we could not read.
215 """
216 check = validator({"faux": FAKE_OPTIONS, "broken": None})
217 assert not profile(check, adapter="broken", anything="at all")
218 assert profile(check, adapter="faux", anything="at all")
219
220
221 def test_a_key_a_command_reads_is_not_read_as_an_adapters(
222 fake: Draft202012Validator,
223 ) -> None:
224 """`limit` is hsql's wherever it appears, so it keeps hsql's type."""
225 options = schema_for({"faux": FAKE_OPTIONS})["$defs"]["faux_options"]["properties"]
226 assert "limit" not in options
227 assert profile(fake, adapter="faux", limit=True)
228
229
230 def test_an_option_a_command_owns_is_described_once() -> None:
231 """`read_only` is a parameter every adapter's constructor takes, so it is
232 described among the command's keys -- and stays there even for an adapter
233 that declares an option by the same name."""
234 declared = [*FAKE_OPTIONS, FlagOption(name="read-only", description="Read only.")]
235 profile_keys = schema_for(None)["$defs"]["profile"]["properties"]
236 assert profile_keys["read_only"]["type"] == "boolean"
237 options = schema_for({"faux": declared})["$defs"]["faux_options"]["properties"]
238 assert "read_only" not in options
239
240
241 def test_a_profile_takes_the_keys_the_ide_reads(fake: Draft202012Validator) -> None:
242 """One profile serves both commands, so hsql's schema describes both."""
243 assert not profile(fake, theme="nord", viewer_max_rows=10_000)
244
245
246 def test_conn_str_is_a_string_or_a_list_of_them(fake: Draft202012Validator) -> None:
247 assert not profile(fake, conn_str="my.db")
248 assert not profile(fake, conn_str=["my.db", "other.db"])
249
250
251 def test_a_row_count_written_as_a_boolean_is_an_error(
252 fake: Draft202012Validator,
253 ) -> None:
254 """`limit = true` is not one row, and the read path already refuses it."""
255 assert profile(fake, limit=True)
256
257
258 # --- the base schema, which describes the format rather than a machine --------
259
260
261 def test_the_base_schema_names_no_adapter() -> None:
262 """Published for readers whose installations we know nothing about.
263
264 So a profile stays open below the keys both commands read: the adapter it
265 names may well be installed where the file is.
266 """
267 base = schema_for(None)
268 assert not profile(Draft202012Validator(base), adapter="snowflake", account="acme")
269 assert "enum" not in base["$defs"]["profile"]["properties"]["adapter"]
270 assert base["$id"] == SCHEMA_ID
271
272
273 def test_the_base_schema_still_closes_what_it_does_know() -> None:
274 check = validator(None)
275 assert problems(check, {"profile": {}})
276 assert profile(check, limit=True)
277
278
279 def test_only_the_base_schema_claims_the_published_id() -> None:
280 """A schema built for one machine is not the one published at that URL."""
281 assert "$id" not in schema_for({"faux": FAKE_OPTIONS})
282
283
284 def test_the_packaged_base_schema_is_what_the_generator_writes() -> None:
285 """The file ships for the site to publish, and nothing reads it at run time.
286
287 So this is the only thing that notices when the config model, hsql's
288 options, or a description behind either of them has moved on without it.
289 """
290 packaged = json.loads(BASE_SCHEMA_PATH.read_text(encoding="utf-8"))
291 assert packaged == build_schema(bare_command().params, None), (
292 f"the packaged base schema is out of date: {FIX}"
293 )
294
295
296 def test_a_secret_option_is_write_only_and_carries_no_default() -> None:
297 """JSON Schema's own word for a value that must not be shown back.
298
299 An editor that knows the vocabulary does the right thing with the field
300 without being told twice -- and a default an adapter shipped for a secret
301 is a secret, so the schema does not write it down.
302 """
303 options: list[AbstractOption] = [
304 TextOption(name="token", description="A token.", default="sh", secret=True),
305 TextOption(name="host", description="Where.", default="localhost"),
306 ]
307 declared = schema_for({"faux": options})["$defs"]["faux_options"]["properties"]
308 assert declared["token"]["writeOnly"] is True
309 assert "default" not in declared["token"]
310 assert "writeOnly" not in declared["host"]
311 assert declared["host"]["default"] == "localhost"