Debian Codegraph @

tests/unit_tests/test_options.py

raw
1 """`AbstractOption.to_dict()`: the serialization every non-rendering consumer reads.
2
3 The shape is the contract. `hsql --spec` publishes it, the generated config
4 schema is built from it, and third-party adapters subclass the classes that
5 produce it -- so what is asserted here is that the keys are the same for every
6 type, and that a subclass written before the method existed still answers.
7 """
8
9 from __future__ import annotations
10
11 from contextlib import contextmanager
12 from typing import Any, Callable, Generator, Iterator
13
14 import pytest
15
16 from harlequin.options import (
17 AbstractOption,
18 FlagOption,
19 ListOption,
20 PathOption,
21 SelectOption,
22 TextOption,
23 )
24
25 KEYS = {
26 "name",
27 "type",
28 "label",
29 "description",
30 "short_decls",
31 "default",
32 "choices",
33 "multiple",
34 "secret",
35 }
36
37
38 class PrehistoricOption(AbstractOption):
39 """An option written before `to_dict()`, `option_type` or any of this.
40
41 It implements exactly the three renderings the ABC demanded when a
42 third-party adapter would have written it, and nothing else. Whatever
43 `to_dict()` does, it has to do it for this.
44 """
45
46 def merge(self, other: AbstractOption) -> AbstractOption:
47 return self
48
49 def to_click(self) -> Callable[..., Any]: # pragma: no cover - never called
50 raise NotImplementedError
51
52 def to_widgets(self) -> Generator[Any, None, None]: # pragma: no cover
53 raise NotImplementedError
54
55 def to_questionary( # pragma: no cover - never called
56 self, existing_value: Any | None = None
57 ) -> Any:
58 raise NotImplementedError
59
60
61 EVERY_OPTION = [
62 TextOption(name="host", description="The host."),
63 ListOption(name="extension", description="Load one."),
64 PathOption(name="init-path", description="A file."),
65 SelectOption(name="mode", description="How.", choices=["ro", "rw"]),
66 FlagOption(name="read-only", description="Refuse writes."),
67 PrehistoricOption(name="legacy", description="From before."),
68 ]
69
70
71 @pytest.mark.parametrize("option", EVERY_OPTION, ids=lambda o: type(o).__name__)
72 def test_every_option_serializes_to_the_same_keys(option: AbstractOption) -> None:
73 """A key that does not apply is null, not a key that is missing.
74
75 A consumer that has to branch on whether a key is there is a consumer
76 writing the three lines this could have written once.
77 """
78 assert set(option.to_dict()) == KEYS
79
80
81 def test_a_text_option_reports_what_it_was_declared_with() -> None:
82 option = TextOption(
83 name="host",
84 description="The host to connect to.",
85 label="Host",
86 short_decls=["-h"],
87 default="localhost",
88 )
89 assert option.to_dict() == {
90 "name": "host",
91 "type": "text",
92 "label": "Host",
93 "description": "The host to connect to.",
94 "short_decls": ["-h"],
95 "default": "localhost",
96 "choices": None,
97 "multiple": False,
98 "secret": False,
99 }
100
101
102 def test_a_short_decl_is_reported_the_way_it_will_be_typed() -> None:
103 """`short_decls=["h"]` is accepted and stored as `-h`, and this reports the
104 spelling, not the declaration."""
105 option = TextOption(name="host", description="The host.", short_decls=["h"])
106 assert option.to_dict()["short_decls"] == ["-h"]
107
108
109 def test_a_list_option_is_the_repeatable_one() -> None:
110 option = ListOption(name="extension", description="Load an extension.")
111 declared = option.to_dict()
112 assert declared["type"] == "list"
113 assert declared["multiple"] is True
114 assert declared["default"] is None
115
116
117 def test_a_select_option_reports_the_values_a_caller_can_type() -> None:
118 """A choice may be declared as a pair for a GUI to render, and a pair is not
119 something anyone can type."""
120 option = SelectOption(
121 name="mode",
122 description="Transaction mode.",
123 choices=["auto", ("manual", "Manual")],
124 default="auto",
125 )
126 declared = option.to_dict()
127 assert declared["type"] == "select"
128 assert declared["choices"] == ["auto", "manual"]
129 assert declared["default"] == "auto"
130
131
132 def test_a_flag_reports_the_default_it_declared() -> None:
133 """The option's own answer. What the *command line* does with a flag that
134 was not passed is `--spec`'s translation, not this one's."""
135 assert FlagOption(name="read-only", description="x").to_dict()["default"] is False
136 assert (
137 FlagOption(name="read-only", description="x", default=True).to_dict()["default"]
138 is True
139 )
140
141
142 def test_a_path_option_is_a_path() -> None:
143 option = PathOption(name="init-path", description="A file.", default="~/.duckdbrc")
144 assert option.to_dict()["type"] == "path"
145 assert option.to_dict()["default"] == "~/.duckdbrc"
146
147
148 def test_an_option_that_predates_the_method_still_answers() -> None:
149 """The reason `to_dict()` is concrete rather than abstract.
150
151 `AbstractOption` is public API and third-party adapters subclass it, so an
152 option class that has never heard of this method has to keep working: it
153 has no `option_type` and no `default`, and neither may raise.
154 """
155 declared = PrehistoricOption(name="legacy", description="From before.").to_dict()
156 assert declared["name"] == "legacy"
157 assert declared["type"] == "prehistoric"
158 assert declared["default"] is None
159 assert declared["choices"] is None
160 assert declared["multiple"] is False
161 assert declared["secret"] is False
162
163
164 def test_a_subclass_of_a_declared_type_inherits_its_type() -> None:
165 """An adapter that subclasses `TextOption` to add validation is still text,
166 and a consumer switching on the type should see that rather than a name it
167 has never met."""
168
169 class HostOption(TextOption):
170 pass
171
172 assert HostOption(name="host", description="x").to_dict()["type"] == "text"
173
174
175 def test_the_in_tree_adapters_serialize() -> None:
176 """Every option the bundled adapters declare, through the real classes."""
177 from harlequin_duckdb import DUCKDB_OPTIONS
178 from harlequin_sqlite import SQLITE_OPTIONS
179
180 for option in [*DUCKDB_OPTIONS, *SQLITE_OPTIONS]:
181 declared = option.to_dict()
182 assert set(declared) == KEYS
183 assert declared["name"]
184 assert declared["type"] in ("text", "list", "path", "select", "flag")
185 assert declared["secret"] in (True, False)
186
187
188 # --- `secret`, and what reads it ---------------------------------------------
189
190
191 def test_an_option_reports_what_it_declared_about_being_secret() -> None:
192 """The declaration `harlequin.redact` and `--spec` both read.
193
194 Core cannot enumerate every adapter's secret, so the adapter says so once
195 and every consumer gets it from here.
196 """
197 assert TextOption(name="token", description="x", secret=True).to_dict()["secret"]
198 assert not TextOption(name="host", description="x").to_dict()["secret"]
199
200
201 @pytest.mark.parametrize("option", EVERY_OPTION, ids=lambda o: type(o).__name__)
202 def test_nothing_is_secret_unless_it_says_so(option: AbstractOption) -> None:
203 """False is the answer a subclass that predates the attribute has to give.
204
205 A class attribute as well as a keyword, so that an option written before
206 any of this answers rather than raising -- and answers the safe way round
207 for the *caller*: an option core wrongly believed secret would be masked in
208 every report, which is a bug a user would have to guess at.
209 """
210 assert option.secret is False
211 assert option.to_dict()["secret"] is False
212
213
214 @pytest.mark.parametrize("adapter", ["duckdb", "sqlite"])
215 def test_every_declared_option_is_a_parameter_the_constructor_names(
216 adapter: str,
217 ) -> None:
218 """The name a caller types and the name the adapter is handed are one name.
219
220 An adapter takes supersets of what it declares and drops the rest, so a
221 declaration whose name no parameter matches is an option that parses,
222 validates, and does nothing -- in silence, which is how `--mode ro` opened
223 a writable database.
224 """
225 import inspect
226
227 from harlequin.config import sluggify_option_name
228 from harlequin.plugins import load_adapter
229
230 adapter_cls = load_adapter(adapter)
231 declared = {
232 sluggify_option_name(option.name)
233 for option in adapter_cls.ADAPTER_OPTIONS or []
234 }
235 named = set(inspect.signature(adapter_cls.__init__).parameters)
236 assert declared <= named
237
238
239 def test_the_duckdb_adapter_declares_its_token_secret() -> None:
240 """The one secret in tree, and the reason the declaration is not theory."""
241 from harlequin_duckdb import DUCKDB_OPTIONS
242
243 declared = {option.name: option.to_dict() for option in DUCKDB_OPTIONS}
244 assert declared["md_token"]["secret"] is True
245 assert declared["md_saas"]["secret"] is False
246
247
248 @pytest.mark.parametrize(
249 "left,right",
250 [
251 (
252 TextOption(name="token", description="A token.", secret=True),
253 TextOption(name="token", description="Not a token."),
254 ),
255 (
256 TextOption(name="token", description="Not a token."),
257 TextOption(name="token", description="A token.", secret=True),
258 ),
259 ],
260 ids=["secret first", "secret second"],
261 )
262 def test_merging_two_options_keeps_the_secret_one_secret(
263 left: AbstractOption, right: AbstractOption
264 ) -> None:
265 """Either half saying so is enough.
266
267 Two adapters spelling the same option two ways is what `merge()` is for,
268 and one of them calling it a password is the answer that cannot be wrong in
269 the direction that hurts.
270 """
271 assert left.merge(right).to_dict()["secret"] is True
272
273
274 @pytest.mark.parametrize(
275 "option_type", [TextOption, PathOption, ListOption], ids=lambda t: t.__name__
276 )
277 def test_a_secret_option_prompts_without_echoing(option_type: type) -> None:
278 """The wizard asks the same question and does not write the answer down.
279
280 A prompt that echoes a token puts it in a terminal, a screen share and a
281 scrollback buffer at once, and the wizard is where a token is typed.
282 """
283 with _no_terminal():
284 plain = option_type(name="token", description="x").to_questionary()
285 secret = option_type(
286 name="token", description="x", secret=True
287 ).to_questionary()
288 assert not _masks_input(plain)
289 assert _masks_input(secret)
290
291
292 @contextmanager
293 def _no_terminal() -> Iterator[None]:
294 """A prompt_toolkit session with nothing behind it.
295
296 `to_questionary()` builds a real `PromptSession`, which reaches for the
297 terminal as it is constructed -- and a test runner has none, which on
298 Windows is an error rather than a fallback. So both ends are replaced: a
299 pipe for input, and an output that draws nowhere.
300 """
301 from prompt_toolkit.application import create_app_session
302 from prompt_toolkit.input import create_pipe_input
303 from prompt_toolkit.output import DummyOutput
304
305 with create_pipe_input() as pipe:
306 with create_app_session(input=pipe, output=DummyOutput()):
307 yield
308
309
310 @contextmanager
311 def _capture_prompt(
312 monkeypatch: pytest.MonkeyPatch, kind: str
313 ) -> Iterator[dict[str, Any]]:
314 """Capture the kwargs of one questionary prompt kind, without a terminal.
315
316 `to_questionary()` imports questionary when it is called, which resolves to
317 the same module object -- so patching the attribute on the real module is
318 enough, and no prompt session is ever built.
319 """
320 import questionary
321
322 captured: dict[str, Any] = {}
323
324 def fake_prompt(**kwargs: Any) -> Any:
325 captured.update(kwargs)
326 return object()
327
328 monkeypatch.setattr(questionary, kind, fake_prompt)
329 yield captured
330
331
332 def _masks_input(question: Any) -> bool:
333 """Whether this prompt would show what is typed into it.
334
335 Read off the real prompt rather than by watching which questionary function
336 was called: what matters is that the input is not echoed, and that is a
337 property of the object the wizard is about to run.
338 """
339 from prompt_toolkit.layout.processors import ConditionalProcessor, PasswordProcessor
340
341 control = question.application.layout.current_window.content
342 return any(
343 isinstance(processor, ConditionalProcessor)
344 and isinstance(processor.processor, PasswordProcessor)
345 and processor.filter()
346 for processor in control.input_processors
347 )
348
349
350 # --- `to_questionary()`: what the wizard's prompts offer ---------------------
351
352
353 @pytest.mark.parametrize(
354 ("option", "prompt_kind"),
355 [
356 (TextOption(name="host", description="The host."), "text"),
357 (PathOption(name="init-path", description="A file."), "path"),
358 ],
359 ids=["text", "path"],
360 )
361 def test_an_unset_option_prompts_blank(
362 monkeypatch: pytest.MonkeyPatch,
363 option: AbstractOption,
364 prompt_kind: str,
365 ) -> None:
366 """A profile that never set the option is not offered the string "None".
367
368 The wizard passes `None` for an option the profile does not set, and
369 `str(None)` would pre-fill "None" -- a value the user would save as text.
370 """
371 with _capture_prompt(monkeypatch, prompt_kind) as captured:
372 option.to_questionary(None)
373 assert captured["default"] == ""
374
375
376 def test_an_unset_secret_option_prompts_blank(
377 monkeypatch: pytest.MonkeyPatch,
378 ) -> None:
379 """The secret's default must be blank too: "None" renders as `****`."""
380 with _capture_prompt(monkeypatch, "password") as captured:
381 TextOption(name="token", description="A token.", secret=True).to_questionary(
382 None
383 )
384 assert captured["default"] == ""
385
386
387 def test_an_unset_option_with_a_declared_default_offers_it(
388 monkeypatch: pytest.MonkeyPatch,
389 ) -> None:
390 """Unset is not the same as blank for an option that declares a default."""
391 with _capture_prompt(monkeypatch, "text") as captured:
392 TextOption(
393 name="host", description="The host.", default="localhost"
394 ).to_questionary(None)
395 assert captured["default"] == "localhost"
396
397
398 def test_an_unset_select_option_offers_its_declared_default(
399 monkeypatch: pytest.MonkeyPatch,
400 ) -> None:
401 with _capture_prompt(monkeypatch, "select") as captured:
402 SelectOption(
403 name="mode", description="How.", choices=["ro", "rw"], default="ro"
404 ).to_questionary(None)
405 assert captured["default"] == "ro"
406
407
408 def test_an_existing_value_is_still_offered(
409 monkeypatch: pytest.MonkeyPatch,
410 ) -> None:
411 """What the profile already says is what the prompt offers."""
412 with _capture_prompt(monkeypatch, "text") as captured:
413 TextOption(name="host", description="The host.").to_questionary(
414 "db.example.com"
415 )
416 assert captured["default"] == "db.example.com"