Debian Codegraph @

tests/unit_tests/test_config.py

raw
1 from __future__ import annotations
2
3 from pathlib import Path
4 from typing import Any, Callable, Sequence
5
6 import pytest
7
8 from harlequin.adapter import HarlequinAdapter, HarlequinConnection
9 from harlequin.config import (
10 TUI_ONLY_KEYS,
11 Config,
12 ConfigFile,
13 ConfigProblem,
14 Profile,
15 Provenance,
16 _discover_config_files,
17 _search_directories,
18 get_highest_priority_existing_config_file,
19 load_config,
20 load_profile,
21 load_profile_and_keymaps,
22 merge_profile_with_cli,
23 parse_profile_options,
24 parse_row_count,
25 resolve_profile,
26 validate_config_files,
27 )
28 from harlequin.exception import HarlequinConfigError
29 from harlequin.keymap import HarlequinKeyBinding, HarlequinKeyMap
30 from harlequin.options import (
31 AbstractOption,
32 FlagOption,
33 ListOption,
34 SelectOption,
35 TextOption,
36 )
37
38
39 @pytest.mark.parametrize("filename", ["good_config.toml", "pyproject.toml"])
40 def test_load_config(data_dir: Path, filename: str) -> None:
41 good_config_path = data_dir / "unit_tests" / "config" / filename
42 good_config = load_config(config_path=good_config_path)
43 assert good_config.default_profile == "my-duckdb-profile"
44 expected_profiles = ["my-duckdb-profile", "local-postgres"]
45 assert all(name in good_config.profiles for name in expected_profiles)
46 assert all(
47 isinstance(good_config.profiles[name], dict) for name in expected_profiles
48 )
49 assert good_config.profiles["my-duckdb-profile"]["limit"] == 200_000
50
51
52 def test_load_keymap(data_dir: Path) -> None:
53 good_config_path = data_dir / "unit_tests" / "config" / "keymaps.toml"
54 keymap_name = "more_arrows"
55 good_config = load_config(config_path=good_config_path)
56 assert keymap_name in good_config.keymaps
57 assert all(
58 k in good_config.keymaps[keymap_name][0]
59 for k in ["keys", "action", "key_display"]
60 )
61
62 _, keymaps = load_profile_and_keymaps(
63 config_path=good_config_path, profile_name=None
64 )
65 assert len(keymaps) == 1
66 assert isinstance(keymaps[0], HarlequinKeyMap)
67 assert keymaps[0].name == keymap_name
68 assert len(keymaps[0].bindings) == 4
69 assert isinstance(keymaps[0].bindings[0], HarlequinKeyBinding)
70
71
72 @pytest.mark.parametrize(
73 "filename,key_words",
74 [
75 ("keymaps_bad_binding.toml", ["Key bindings", "foo"]),
76 ],
77 )
78 def test_load_bad_keymap_raises(
79 data_dir: Path,
80 filename: str,
81 key_words: list[str],
82 ) -> None:
83 config_path = data_dir / "unit_tests" / "config" / filename
84 with pytest.raises(HarlequinConfigError) as exc_info:
85 _ = load_profile_and_keymaps(config_path=config_path, profile_name=None)
86 err = exc_info.value
87 print(err)
88 assert isinstance(err, HarlequinConfigError)
89 assert "keymap" in err.title
90 assert all([w in err.msg for w in key_words])
91
92
93 @pytest.mark.parametrize("filename", ["good_config.toml", "pyproject.toml"])
94 def test_load_named_profile(data_dir: Path, filename: str) -> None:
95 good_config_path = data_dir / "unit_tests" / "config" / filename
96 profile, keymaps = load_profile_and_keymaps(
97 config_path=good_config_path, profile_name="local-postgres"
98 )
99 assert profile["port"] == 5432
100 assert profile["theme"] == "fruity"
101
102
103 @pytest.mark.parametrize("filename", ["good_config.toml", "pyproject.toml"])
104 def test_load_default_profile(data_dir: Path, filename: str) -> None:
105 good_config_path = data_dir / "unit_tests" / "config" / filename
106 profile, keymaps = load_profile_and_keymaps(
107 config_path=good_config_path, profile_name=None
108 )
109 assert profile["adapter"] == "duckdb"
110 assert profile["theme"] == "monokai"
111
112
113 @pytest.mark.parametrize(
114 "filename,key_words",
115 [
116 ("extra_key.toml", ["unexpected key"]),
117 ("none_profile.toml", ["None", "not allowed"]),
118 ("not_toml.toml", ["Attempted to load"]),
119 ("profiles_not_table.toml", ["profiles", "table"]),
120 ("profile_not_table.toml", ["profiles", "table"]),
121 ("keymaps_not_array.toml", ["keymaps", "array"]),
122 ],
123 )
124 def test_bad_config_raises(
125 data_dir: Path,
126 filename: str,
127 key_words: list[str],
128 ) -> None:
129 config_path = data_dir / "unit_tests" / "config" / filename
130 with pytest.raises(HarlequinConfigError) as exc_info:
131 _ = load_config(config_path=config_path)
132 err = exc_info.value
133 assert isinstance(err, HarlequinConfigError)
134 assert "config" in err.title
135 assert all([w in err.msg for w in key_words])
136 # every message names the file the key is written in, which is what
137 # validating each file ahead of the merge is for
138 assert filename in err.msg
139
140
141 @pytest.mark.parametrize(
142 "filename",
143 [
144 "default_no_exist.toml",
145 # a file that names a default and defines no profiles at all used to
146 # escape as a KeyError rather than being reported
147 "default_no_profiles.toml",
148 ],
149 )
150 def test_a_default_that_names_no_profile_raises_where_it_is_resolved(
151 data_dir: Path, filename: str
152 ) -> None:
153 """Both commands report it, and neither reads it as a profile of its own."""
154 config_path = data_dir / "unit_tests" / "config" / filename
155
156 for resolve in (
157 lambda: load_profile_and_keymaps(config_path=config_path, profile_name=None),
158 lambda: load_profile(config_path=config_path, profile_name=None),
159 ):
160 with pytest.raises(HarlequinConfigError) as exc_info:
161 resolve()
162 assert all(w in exc_info.value.msg for w in ["default_profile", "foo"])
163
164
165 @pytest.mark.parametrize("profile_name", ["None", "my-duckdb-profile"])
166 def test_a_default_that_names_no_profile_is_not_an_error_for_a_caller_that_overrode_it(
167 data_dir: Path, profile_name: str
168 ) -> None:
169 """A key nobody read cannot be what stops a command starting.
170
171 That is the shape of #1040, and it is also the only thing that kept the two
172 commands from agreeing: `hsql -P other` never consults `default_profile`,
173 so `harlequin -P other` must not refuse over it either.
174 """
175 config_path = data_dir / "unit_tests" / "config" / "default_no_exist.toml"
176
177 profile, _ = load_profile_and_keymaps(
178 config_path=config_path, profile_name=profile_name
179 )
180 assert profile == load_profile(config_path=config_path, profile_name=profile_name)
181 # and reading the document is not resolving a name, so it does not raise
182 assert load_config(config_path=config_path).default_profile == "foo"
183
184
185 def test_config_file_discovery(
186 tmp_path_factory: pytest.TempPathFactory,
187 monkeypatch: pytest.MonkeyPatch,
188 ) -> None:
189 # first, patch the real search paths with tmps
190 mock_home = tmp_path_factory.mktemp("home")
191 mock_config = tmp_path_factory.mktemp("config")
192 mock_cwd = tmp_path_factory.mktemp("cwd")
193 custom = tmp_path_factory.mktemp("custom") / "foo.toml"
194
195 # create empty config files in our mock dirs, highest priority first
196 expected_paths = [
197 custom,
198 mock_cwd / "harlequin.toml",
199 mock_cwd / ".harlequin.toml",
200 mock_cwd / "pyproject.toml",
201 mock_config / "harlequin.toml",
202 mock_config / "config.toml",
203 mock_home / "harlequin.toml",
204 mock_home / ".harlequin.toml",
205 mock_home / "pyproject.toml",
206 ]
207 for p in expected_paths:
208 p.parent.mkdir(parents=True, exist_ok=True)
209 p.open("w").close()
210
211 # the real search, which `no_discovered_config` stubs out for every other
212 # test, is the thing under test here -- so put it back and redirect the
213 # three directories it walks instead
214 monkeypatch.setattr("harlequin.config._search_directories", _search_directories)
215 monkeypatch.setattr(Path, "cwd", lambda: mock_cwd)
216 monkeypatch.setattr(Path, "home", lambda: mock_home)
217 monkeypatch.setattr("harlequin.config.user_config_path", lambda **_: mock_config)
218
219 assert list(_discover_config_files(config_path=custom)) == expected_paths
220
221 expected_paths.pop(0)
222 assert list(_discover_config_files(config_path=None)) == expected_paths
223 assert get_highest_priority_existing_config_file() == expected_paths[0]
224
225
226 def test_merge_profile_with_cli_prefers_values_the_user_typed() -> None:
227 profile: Profile = {"theme": "fruity", "limit": 200_000}
228 merged = merge_profile_with_cli(
229 profile=profile,
230 cli_values={"theme": "zenburn", "limit": 100_000},
231 explicitly_set={"theme"},
232 )
233 # the theme was typed, so it wins; the limit is a default, so it doesn't
234 assert merged == {"theme": "zenburn", "limit": 200_000}
235
236
237 def test_merge_profile_with_cli_keeps_options_the_profile_alone_defines() -> None:
238 """Adapter options live in the profile under names the CLI never saw."""
239 profile: Profile = {"adapter": "postgres", "dbname": "prod"}
240 merged = merge_profile_with_cli(
241 profile=profile,
242 cli_values={"username": "ted"},
243 explicitly_set={"username"},
244 )
245 assert merged == {"adapter": "postgres", "dbname": "prod", "username": "ted"}
246
247
248 def test_merge_profile_with_cli_ignores_an_empty_conn_str() -> None:
249 """An absent conn_str would otherwise leave `harlequin -P prod` nothing to open."""
250 profile: Profile = {"conn_str": ["my-database.db"]}
251 merged = merge_profile_with_cli(
252 profile=profile,
253 cli_values={"conn_str": tuple()},
254 explicitly_set={"conn_str"},
255 )
256 assert merged == {"conn_str": ["my-database.db"]}
257
258
259 def test_merge_profile_with_cli_accepts_a_conn_str_that_was_passed() -> None:
260 profile: Profile = {"conn_str": ["my-database.db"]}
261 merged = merge_profile_with_cli(
262 profile=profile,
263 cli_values={"conn_str": ("other.db",)},
264 explicitly_set={"conn_str"},
265 )
266 assert merged == {"conn_str": ("other.db",)}
267
268
269 def test_merge_profile_with_cli_leaves_its_arguments_alone() -> None:
270 """The profile is a live reference into the merged config files."""
271 profile: Profile = {"theme": "fruity"}
272 cli_values = {"theme": "zenburn"}
273 merged = merge_profile_with_cli(
274 profile=profile, cli_values=cli_values, explicitly_set={"theme"}
275 )
276 assert profile == {"theme": "fruity"}
277 assert cli_values == {"theme": "zenburn"}
278 assert merged is not profile
279
280
281 def test_merge_profile_with_cli_falsy_values_are_still_values() -> None:
282 """`--limit 0` and `--no-init` mean what they say."""
283 profile: Profile = {"limit": 200_000, "no_init": False}
284 merged = merge_profile_with_cli(
285 profile=profile,
286 cli_values={"limit": 0, "no_init": True},
287 explicitly_set={"limit", "no_init"},
288 )
289 assert merged == {"limit": 0, "no_init": True}
290
291
292 class TestParseRowCount:
293 """-1 is unlimited everywhere; 0 is zero rows, except for the viewer."""
294
295 @pytest.mark.parametrize("value,expected", [(500, 500), ("500", 500), (0, 0)])
296 def test_a_number_of_rows(self, value: object, expected: int) -> None:
297 assert parse_row_count(value, key="limit") == expected
298
299 def test_minus_one_is_unlimited(self) -> None:
300 assert parse_row_count(-1, key="limit") is None
301
302 def test_zero_is_unlimited_only_where_it_always_was(self) -> None:
303 """A Results Viewer holding no rows serves nobody, so 0 keeps the
304 meaning it has had there since before there was another key."""
305 assert parse_row_count(0, key="viewer_max_rows", zero_is_unlimited=True) is None
306
307 @pytest.mark.parametrize("value", ["all", None, 1.5, -2])
308 def test_what_is_not_a_number_of_rows(self, value: object) -> None:
309 with pytest.raises(HarlequinConfigError):
310 parse_row_count(value, key="limit")
311
312
313 class TestConfigFileRoundTrip:
314 """Reading and writing use different parsers, so writing has to be tested.
315
316 `ConfigFile` reads with `tomllib` because every start-up reads config, and
317 writes with tomlkit because a user's comments have to survive the write.
318 Nothing catches the two drifting apart except these.
319 """
320
321 def test_a_write_preserves_the_comments_around_what_it_did_not_touch(
322 self, tmp_path: Path
323 ) -> None:
324 """Which is why writing still goes through tomlkit.
325
326 `relevant_config` hands back plain data -- every reader wants that, and
327 it is on the hot path -- so it falls to `update()` to merge that data
328 back into the tomlkit document key by key. A table nobody edited keeps
329 its own nodes, and with them the comments written inside it.
330 """
331 path = tmp_path / ".harlequin.toml"
332 path.write_text(
333 "# a file someone wrote by hand\n"
334 'default_profile = "one"\n'
335 "\n"
336 "# and a note further down\n"
337 "[profiles.one]\n"
338 "# I like this theme best\n"
339 'theme = "fruity"\n'
340 )
341
342 config_file = ConfigFile(path)
343 config = config_file.relevant_config
344 config["profiles"]["two"] = {"theme": "monokai"}
345 config_file.update(config)
346 config_file.write()
347
348 written = path.read_text()
349 assert "# a file someone wrote by hand" in written
350 assert "# and a note further down" in written
351 # nothing was asked to change about profile one, inside it or around it
352 assert "# I like this theme best" in written
353 # and the new profile arrived, without disturbing the old one
354 reread = load_config(config_path=path)
355 assert reread.profiles["two"] == {"theme": "monokai"}
356 assert reread.profiles["one"] == {"theme": "fruity"}
357 assert reread.default_profile == "one"
358
359 def test_a_write_preserves_the_comments_around_the_value_it_changed(
360 self, tmp_path: Path
361 ) -> None:
362 """Editing one key in a table is not a reason to reflow the table."""
363 path = tmp_path / ".harlequin.toml"
364 path.write_text(
365 "[profiles.one]\n"
366 "# I like this theme best\n"
367 'theme = "fruity"\n'
368 "# the database I use every day\n"
369 'conn_str = ["analytics.db"]\n'
370 )
371
372 config_file = ConfigFile(path)
373 config = config_file.relevant_config
374 config["profiles"]["one"]["theme"] = "monokai"
375 config_file.update(config)
376 config_file.write()
377
378 written = path.read_text()
379 assert "# I like this theme best" in written
380 assert "# the database I use every day" in written
381 assert load_config(config_path=path).profiles["one"] == {
382 "theme": "monokai",
383 "conn_str": ["analytics.db"],
384 }
385
386 def test_a_write_removes_the_keys_the_caller_dropped(self, tmp_path: Path) -> None:
387 """A merge, but the caller's table is still the whole table.
388
389 `harlequin --config` hands back the profile it just built, so a key
390 that is not in it is a key the user turned off -- and leaving it behind
391 would be writing back an option nobody asked for.
392 """
393 path = tmp_path / ".harlequin.toml"
394 path.write_text(
395 "[profiles.one]\n"
396 'theme = "fruity"\n'
397 "show_files = '/home/me'\n"
398 "\n"
399 "[profiles.two]\n"
400 'theme = "monokai"\n'
401 )
402
403 config_file = ConfigFile(path)
404 config = config_file.relevant_config
405 config["profiles"]["one"] = {"theme": "fruity"}
406 del config["profiles"]["two"]
407 config_file.update(config)
408 config_file.write()
409
410 reread = load_config(config_path=path)
411 assert reread.profiles == {"one": {"theme": "fruity"}}
412
413 def test_a_write_leaves_alone_the_top_level_keys_it_was_not_given(
414 self, tmp_path: Path
415 ) -> None:
416 """What the keymap editor depends on: it writes `keymaps` and nothing
417 else, and must not take the profiles with it."""
418 path = tmp_path / ".harlequin.toml"
419 path.write_text(
420 'default_profile = "one"\n'
421 "\n"
422 "[profiles.one]\n"
423 "# still mine\n"
424 'theme = "fruity"\n'
425 )
426
427 config_file = ConfigFile(path)
428 config_file.update(
429 {"keymaps": {"mine": [{"keys": "ctrl+j", "action": "quit"}]}}
430 )
431 config_file.write()
432
433 assert "# still mine" in path.read_text()
434 reread = load_config(config_path=path)
435 assert reread.default_profile == "one"
436 assert reread.profiles["one"] == {"theme": "fruity"}
437 assert reread.keymaps["mine"] == [{"keys": "ctrl+j", "action": "quit"}]
438
439 def test_a_write_of_the_whole_section_removes_a_top_level_key_it_dropped(
440 self, tmp_path: Path
441 ) -> None:
442 """How `harlequin --config` turns a `default_profile` back off.
443
444 The wizard hands back the whole Harlequin section, so a key missing
445 from it is one the user turned off, and leaving it behind would write
446 back a default nobody asked for.
447 """
448 path = tmp_path / ".harlequin.toml"
449 path.write_text(
450 "# a file someone wrote by hand\n"
451 'default_profile = "one"\n'
452 "\n"
453 "[profiles.one]\n"
454 "# keep me\n"
455 'theme = "fruity"\n'
456 )
457
458 config_file = ConfigFile(path)
459 config = config_file.relevant_config
460 del config["default_profile"]
461 config_file.update(config, whole_section=True)
462 config_file.write()
463
464 written = path.read_text()
465 assert "default_profile" not in written
466 # the key went; the comments around what stayed did not
467 assert "# a file someone wrote by hand" in written
468 assert "# keep me" in written
469 reread = load_config(config_path=path)
470 assert reread.default_profile is None
471 assert reread.profiles["one"] == {"theme": "fruity"}
472
473 def test_a_write_to_pyproject_touches_only_the_harlequin_table(
474 self, tmp_path: Path
475 ) -> None:
476 path = tmp_path / "pyproject.toml"
477 path.write_text(
478 "[project]\n"
479 'name = "someone-elses-project"\n'
480 "\n"
481 "[tool.harlequin.profiles.one]\n"
482 "# I like this theme best\n"
483 'theme = "fruity"\n'
484 )
485
486 config_file = ConfigFile(path)
487 config = config_file.relevant_config
488 config["default_profile"] = "one"
489 config_file.update(config)
490 config_file.write()
491
492 reread = ConfigFile(path)
493 assert reread.relevant_config["default_profile"] == "one"
494 assert reread.relevant_config["profiles"]["one"] == {"theme": "fruity"}
495 written = path.read_text()
496 # the rest of the file is not ours to rewrite
497 assert 'name = "someone-elses-project"' in written
498 # and neither is the inside of a table we did not change
499 assert "# I like this theme best" in written
500
501 def test_a_write_creates_a_file_that_does_not_exist_yet(
502 self, tmp_path: Path
503 ) -> None:
504 path = tmp_path / "nested" / ".harlequin.toml"
505
506 config_file = ConfigFile(path)
507 assert config_file.relevant_config == {}
508 config_file.update(
509 {"default_profile": "one", "profiles": {"one": {"theme": "fruity"}}}
510 )
511 config_file.write()
512
513 assert path.exists()
514 assert load_config(config_path=path) == Config(
515 default_profile="one", profiles={"one": {"theme": "fruity"}}
516 )
517
518 def test_a_write_adds_the_harlequin_table_to_a_pyproject_without_one(
519 self, tmp_path: Path
520 ) -> None:
521 path = tmp_path / "pyproject.toml"
522 path.write_text('[project]\nname = "someone-elses-project"\n')
523
524 config_file = ConfigFile(path)
525 assert config_file.relevant_config == {}
526 config_file.update({"default_profile": "one"})
527 config_file.write()
528
529 assert ConfigFile(path).relevant_config == {"default_profile": "one"}
530
531 def test_an_unreadable_file_raises_before_anything_is_written(
532 self, data_dir: Path
533 ) -> None:
534 with pytest.raises(HarlequinConfigError):
535 ConfigFile(data_dir / "unit_tests" / "config" / "not_toml.toml")
536
537
538 @pytest.fixture
539 def config_dirs(
540 tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
541 ) -> tuple[Path, Path]:
542 """A cwd and a home directory to write config files into, and nothing else.
543
544 Returns them nearest first, which is the order the files in them are read.
545 """
546 mock_cwd = tmp_path_factory.mktemp("cwd")
547 mock_home = tmp_path_factory.mktemp("home")
548 monkeypatch.setattr(
549 "harlequin.config._search_directories",
550 lambda: [
551 (mock_cwd, (".harlequin.toml",)),
552 (mock_home, (".harlequin.toml",)),
553 ],
554 )
555 return mock_cwd, mock_home
556
557
558 class TestMergingConfigFiles:
559 """Later files merge into earlier ones per profile, not per table.
560
561 Every case here is a config that two files disagree about, which is the
562 only place the merge is visible at all.
563 """
564
565 def test_a_project_file_does_not_displace_the_profiles_in_a_home_file(
566 self, config_dirs: tuple[Path, Path]
567 ) -> None:
568 """The failing case from #1040, which used to refuse to start.
569
570 A `profiles` table used to replace another file's outright while the
571 `default_profile` naming one of them survived, so the two contradicted
572 each other and both commands exited 2.
573 """
574 cwd, home = config_dirs
575 (home / ".harlequin.toml").write_text(
576 'default_profile = "personal"\n'
577 "[profiles.personal]\n"
578 'adapter = "duckdb"\n'
579 "[profiles.shared]\n"
580 'adapter = "sqlite"\n'
581 )
582 (cwd / ".harlequin.toml").write_text('[profiles.project]\nadapter = "sqlite"\n')
583
584 config = load_config(config_path=None)
585
586 assert sorted(config.profiles) == ["personal", "project", "shared"]
587 assert config.default_profile == "personal"
588 assert load_profile(config_path=None, profile_name=None) == {
589 "adapter": "duckdb"
590 }
591
592 def test_the_nearest_file_that_defines_a_profile_is_the_one_that_defines_it(
593 self, config_dirs: tuple[Path, Path]
594 ) -> None:
595 """A profile is one file's, whole: its keys are not merged with another's.
596
597 Half a connection from each of two files is not a connection either of
598 them describes, and it is not something a reader of either can predict.
599 """
600 cwd, home = config_dirs
601 (home / ".harlequin.toml").write_text(
602 "[profiles.prod]\n"
603 'adapter = "postgres"\n'
604 'conn_str = ["postgres://prod"]\n'
605 "[profiles.other]\n"
606 "limit = 10\n"
607 )
608 (cwd / ".harlequin.toml").write_text("[profiles.prod]\nlimit = 100\n")
609
610 assert load_profile(config_path=None, profile_name="prod") == {"limit": 100}
611 assert load_profile(config_path=None, profile_name="other") == {"limit": 10}
612
613 def test_the_nearest_file_that_names_a_default_is_the_one_that_names_it(
614 self, config_dirs: tuple[Path, Path]
615 ) -> None:
616 cwd, home = config_dirs
617 (home / ".harlequin.toml").write_text(
618 'default_profile = "personal"\n[profiles.personal]\nlimit = 1\n'
619 )
620 (cwd / ".harlequin.toml").write_text(
621 'default_profile = "project"\n[profiles.project]\nlimit = 2\n'
622 )
623
624 assert load_config(config_path=None).default_profile == "project"
625 assert load_profile(config_path=None, profile_name=None) == {"limit": 2}
626
627 def test_a_default_named_in_one_file_can_be_defined_in_another(
628 self, config_dirs: tuple[Path, Path]
629 ) -> None:
630 """And the nearer file's copy of it still wins.
631
632 The name is not known until the file that sets `default_profile` is
633 read, so the files read before it are held rather than skipped.
634 """
635 cwd, home = config_dirs
636 (home / ".harlequin.toml").write_text(
637 'default_profile = "prod"\n[profiles.prod]\nlimit = 1\n'
638 )
639 (cwd / ".harlequin.toml").write_text("[profiles.prod]\nlimit = 2\n")
640
641 assert load_profile(config_path=None, profile_name=None) == {"limit": 2}
642
643 def test_keymaps_merge_by_name_too(self, config_dirs: tuple[Path, Path]) -> None:
644 cwd, home = config_dirs
645 (home / ".harlequin.toml").write_text(
646 '[[keymaps.mine]]\nkeys = "w"\naction = "results_viewer.cursor_up"\n'
647 '[[keymaps.theirs]]\nkeys = "s"\naction = "results_viewer.cursor_down"\n'
648 )
649 (cwd / ".harlequin.toml").write_text(
650 '[[keymaps.mine]]\nkeys = "a"\naction = "results_viewer.cursor_left"\n'
651 )
652
653 _, keymaps = load_profile_and_keymaps(config_path=None, profile_name=None)
654
655 by_name = {keymap.name: keymap for keymap in keymaps}
656 assert sorted(by_name) == ["mine", "theirs"]
657 assert by_name["mine"].bindings[0].keys == "a"
658
659 def test_an_explicit_config_path_outranks_every_discovered_file(
660 self, config_dirs: tuple[Path, Path], tmp_path: Path
661 ) -> None:
662 cwd, home = config_dirs
663 (cwd / ".harlequin.toml").write_text("[profiles.prod]\nlimit = 1\n")
664 explicit = tmp_path / "explicit.toml"
665 explicit.write_text("[profiles.prod]\nlimit = 2\n")
666
667 assert load_profile(config_path=explicit, profile_name="prod") == {"limit": 2}
668
669
670 class TestReadingNoMoreThanItMust:
671 """Files are read nearest first, so the far ones often need not be read.
672
673 Each of these puts something unreadable in a file that must not be reached
674 -- a file that is opened at all takes the test down with it.
675 """
676
677 def test_a_profile_found_near_stops_the_search(
678 self, config_dirs: tuple[Path, Path]
679 ) -> None:
680 cwd, home = config_dirs
681 (cwd / ".harlequin.toml").write_text("[profiles.prod]\nlimit = 1\n")
682 (home / ".harlequin.toml").write_text("this is not toml at all [[[")
683
684 assert load_profile(config_path=None, profile_name="prod") == {"limit": 1}
685
686 def test_the_default_profile_stops_the_search_too(
687 self, config_dirs: tuple[Path, Path]
688 ) -> None:
689 cwd, home = config_dirs
690 (cwd / ".harlequin.toml").write_text(
691 'default_profile = "prod"\n[profiles.prod]\nlimit = 1\n'
692 )
693 (home / ".harlequin.toml").write_text("this is not toml at all [[[")
694
695 assert load_profile(config_path=None, profile_name=None) == {"limit": 1}
696
697 def test_the_profile_named_None_reads_nothing_at_all(
698 self, config_dirs: tuple[Path, Path]
699 ) -> None:
700 """`-P None` asks for Harlequin's defaults, and that is answerable here."""
701 cwd, _ = config_dirs
702 (cwd / ".harlequin.toml").write_text("this is not toml at all [[[")
703
704 assert load_profile(config_path=None, profile_name="None") == {}
705 assert resolve_profile(config_path=None, profile_name="None") == ("None", {})
706
707 def test_resolving_a_profile_names_the_one_it_resolved_to(
708 self, config_dirs: tuple[Path, Path]
709 ) -> None:
710 """The name `load_profile()` works out and discards, which is what
711 `hsql --info` reports as the profile a run would use."""
712 cwd, home = config_dirs
713 (home / ".harlequin.toml").write_text(
714 'default_profile = "personal"\n[profiles.personal]\nlimit = 1\n'
715 )
716 (cwd / ".harlequin.toml").write_text("[profiles.project]\nlimit = 2\n")
717
718 assert resolve_profile(config_path=None, profile_name=None) == (
719 "personal",
720 {"limit": 1},
721 )
722 assert resolve_profile(config_path=None, profile_name="project") == (
723 "project",
724 {"limit": 2},
725 )
726
727 def test_resolving_a_profile_is_the_same_walk_load_profile_takes(
728 self, config_dirs: tuple[Path, Path]
729 ) -> None:
730 """One walk and one early stop, so the two cannot disagree about which
731 file answered."""
732 cwd, home = config_dirs
733 (cwd / ".harlequin.toml").write_text(
734 'default_profile = "near"\n[profiles.near]\nlimit = 1\n'
735 )
736 (home / ".harlequin.toml").write_text("this is not toml at all [[[")
737
738 name, profile = resolve_profile(config_path=None, profile_name=None)
739 assert name == "near"
740 assert profile == load_profile(config_path=None, profile_name=None)
741
742 def test_resolving_a_name_nothing_defines_raises(
743 self, config_dirs: tuple[Path, Path]
744 ) -> None:
745 cwd, _ = config_dirs
746 (cwd / ".harlequin.toml").write_text("[profiles.here]\nlimit = 1\n")
747
748 with pytest.raises(HarlequinConfigError) as exc_info:
749 resolve_profile(config_path=None, profile_name="gone")
750 assert "gone" in exc_info.value.msg
751
752 def test_a_file_it_did_reach_is_still_validated(
753 self, config_dirs: tuple[Path, Path]
754 ) -> None:
755 cwd, home = config_dirs
756 (cwd / ".harlequin.toml").write_text(
757 "nonsense = 1\n[profiles.prod]\nlimit = 1\n"
758 )
759 (home / ".harlequin.toml").write_text("this is not toml at all [[[")
760
761 with pytest.raises(HarlequinConfigError) as exc_info:
762 load_profile(config_path=None, profile_name="prod")
763 assert "nonsense" in exc_info.value.msg
764
765 def test_reading_the_whole_config_still_reads_the_whole_config(
766 self, config_dirs: tuple[Path, Path]
767 ) -> None:
768 """`load_config()` is the document, so it has no reason to stop early."""
769 cwd, home = config_dirs
770 (cwd / ".harlequin.toml").write_text("[profiles.prod]\nlimit = 1\n")
771 (home / ".harlequin.toml").write_text("this is not toml at all [[[")
772
773 with pytest.raises(HarlequinConfigError):
774 load_config(config_path=None)
775
776
777 class TestParsingAgainstAnAdapter:
778 """The second pass: a profile's keys against the options its adapter declares.
779
780 Nothing else in the stack can do this -- an adapter takes supersets of what
781 it declares, so a key it has never heard of reaches its constructor and is
782 dropped there in silence.
783 """
784
785 OPTIONS = [
786 FlagOption(name="read_only", description="x"),
787 TextOption(name="port", description="x"),
788 ListOption(name="extension", description="x"),
789 SelectOption(name="mode", description="x", choices=["ro", "rw"]),
790 ]
791 COMMAND_OPTIONS = {"adapter", "conn_str", "limit", *TUI_ONLY_KEYS}
792
793 def parse(self, profile: Profile, adapter: str = "duckdb") -> Profile:
794 return parse_profile_options(
795 profile,
796 adapter=adapter,
797 adapter_options=self.OPTIONS,
798 command_options=self.COMMAND_OPTIONS,
799 )
800
801 @pytest.mark.parametrize(
802 "written,meant",
803 [
804 ("reed_only", "read_only"),
805 # TOML allows a dash in a key and Harlequin's options never have one
806 ("read-only", "read_only"),
807 # a near miss for one of the command's own keys, not the adapter's
808 ("keymap_names", "keymap_name"),
809 ],
810 )
811 def test_a_misspelled_option_is_refused_and_the_spelling_suggested(
812 self, written: str, meant: str
813 ) -> None:
814 with pytest.raises(HarlequinConfigError) as exc_info:
815 self.parse({written: True})
816 message = exc_info.value.msg
817 assert written in message
818 assert meant in message
819 assert "duckdb" in message
820
821 @pytest.mark.parametrize(
822 "profile",
823 [
824 {"read_only": True, "port": "5432", "mode": "ro"},
825 {"extension": ["httpfs", "spatial"]},
826 {"limit": 100, "conn_str": ["my.db"]}, # keys a command owns
827 {"theme": "fruity", "keymap_name": ["vscode"]}, # keys the IDE owns
828 ],
829 )
830 def test_what_a_profile_may_hold(self, profile: Profile) -> None:
831 assert self.parse(profile) == profile
832
833 @pytest.mark.parametrize(
834 "written,parsed",
835 [
836 ({"port": 5432}, {"port": "5432"}), # the type a TOML file reaches for
837 ({"read_only": "true"}, {"read_only": True}),
838 ({"read_only": 1}, {"read_only": True}),
839 ({"mode": "RO"}, {"mode": "ro"}), # click matches choices this way
840 ],
841 )
842 def test_a_value_arrives_as_the_type_its_option_declares(
843 self, written: Profile, parsed: Profile
844 ) -> None:
845 assert self.parse(written) == parsed
846
847 @pytest.mark.parametrize(
848 "profile,words",
849 [
850 ({"mode": "reed-only"}, ["mode", "'ro'", "'rw'"]),
851 ({"read_only": "yes"}, ["read_only", "boolean"]),
852 ({"extension": "httpfs"}, ["extension", "array"]),
853 ({"port": True}, ["port", "string"]),
854 ],
855 )
856 def test_a_value_the_option_cannot_take(
857 self, profile: Profile, words: list[str]
858 ) -> None:
859 with pytest.raises(HarlequinConfigError) as exc_info:
860 self.parse(profile)
861 assert all(word in exc_info.value.msg for word in words)
862
863 def test_an_adapter_that_declares_nothing_takes_no_options(self) -> None:
864 assert parse_profile_options(
865 {"limit": 100},
866 adapter="fake",
867 adapter_options=None,
868 command_options=self.COMMAND_OPTIONS,
869 ) == {"limit": 100}
870 with pytest.raises(HarlequinConfigError):
871 parse_profile_options(
872 {"anything": 1},
873 adapter="fake",
874 adapter_options=None,
875 command_options=self.COMMAND_OPTIONS,
876 )
877
878
879 class TestProvenance:
880 """Which file each merged value came from, recorded by the merge itself.
881
882 A second pass over the same files to work out where a value came from
883 could disagree with the merge that produced it, and the disagreement would
884 show up as `--config show` naming the wrong file -- which is worse than not
885 reporting one, because a reader would edit it.
886 """
887
888 def test_it_names_the_winning_file_and_the_ones_it_beat(
889 self, config_dirs: tuple[Path, Path]
890 ) -> None:
891 cwd, home = config_dirs
892 (home / ".harlequin.toml").write_text(
893 'default_profile = "personal"\n'
894 "[profiles.personal]\n"
895 'adapter = "duckdb"\n'
896 "[profiles.shared]\n"
897 'adapter = "sqlite"\n'
898 "[[keymaps.arrows]]\n"
899 'keys = "ctrl+j"\n'
900 'action = "cursor_down"\n'
901 )
902 (cwd / ".harlequin.toml").write_text(
903 'default_profile = "project"\n[profiles.shared]\nadapter = "duckdb"\n'
904 )
905
906 provenance = Provenance()
907 config = load_config(config_path=None, provenance=provenance)
908
909 assert provenance.files == [cwd / ".harlequin.toml", home / ".harlequin.toml"]
910 # nearest first, so the first entry is the definition that won
911 assert provenance.default_profile == [
912 cwd / ".harlequin.toml",
913 home / ".harlequin.toml",
914 ]
915 assert config.default_profile == "project"
916 assert provenance.profiles["shared"] == [
917 cwd / ".harlequin.toml",
918 home / ".harlequin.toml",
919 ]
920 assert provenance.profiles["personal"] == [home / ".harlequin.toml"]
921 assert provenance.keymaps["arrows"] == [home / ".harlequin.toml"]
922
923 def test_it_records_only_files_that_define_something(
924 self, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
925 ) -> None:
926 """A `pyproject.toml` with no section of ours was read and says nothing.
927
928 Every Python project has one in the working directory, so a report that
929 listed it would list it for almost everybody, and the file a reader
930 went looking in would have nothing in it.
931 """
932 cwd, home = config_dirs
933 monkeypatch.setattr(
934 "harlequin.config._search_directories",
935 lambda: [(cwd, ("pyproject.toml", ".harlequin.toml")), (home, ())],
936 )
937 (cwd / "pyproject.toml").write_text('[project]\nname = "not-ours"\n')
938 (cwd / ".harlequin.toml").write_text('[profiles.one]\nadapter = "sqlite"\n')
939
940 provenance = Provenance()
941 load_config(config_path=None, provenance=provenance)
942
943 assert provenance.files == [cwd / ".harlequin.toml"]
944
945 def test_the_winning_file_is_the_one_the_merge_took_the_value_from(
946 self, config_dirs: tuple[Path, Path]
947 ) -> None:
948 """The property that makes this worth reporting at all."""
949 cwd, home = config_dirs
950 (home / ".harlequin.toml").write_text(
951 "[profiles.shared]\nlimit = 1\n[profiles.only-home]\nlimit = 2\n"
952 )
953 (cwd / ".harlequin.toml").write_text("[profiles.shared]\nlimit = 3\n")
954
955 provenance = Provenance()
956 config = load_config(config_path=None, provenance=provenance)
957
958 for name, profile in config.profiles.items():
959 winner = provenance.profiles[name][0]
960 assert profile == load_config(config_path=winner).profiles[name]
961
962 def test_nothing_that_does_not_ask_for_it_pays_for_it(
963 self, config_dirs: tuple[Path, Path]
964 ) -> None:
965 """The merge is the same merge with the recorder left out."""
966 cwd, home = config_dirs
967 (home / ".harlequin.toml").write_text(
968 'default_profile = "a"\n[profiles.a]\nlimit = 1\n[profiles.b]\nlimit = 2\n'
969 )
970 (cwd / ".harlequin.toml").write_text("[profiles.b]\nlimit = 3\n")
971
972 assert load_config(config_path=None) == load_config(
973 config_path=None, provenance=Provenance()
974 )
975
976
977 def adapter_declaring(
978 options: Sequence[AbstractOption] | None, *, read_only: bool = True
979 ) -> type[HarlequinAdapter]:
980 """An adapter class for the seam `validate_config_files()` reads.
981
982 The class rather than its options, because a profile can be wrong about
983 what its adapter can do as well as about what it takes.
984 """
985
986 class FakeAdapter(HarlequinAdapter):
987 ADAPTER_OPTIONS = None if options is None else list(options)
988 IMPLEMENTS_READ_ONLY = read_only
989
990 def __init__(self, conn_str: Sequence[str], **options: Any) -> None:
991 raise NotImplementedError
992
993 def connect(self) -> HarlequinConnection:
994 raise NotImplementedError
995
996 return FakeAdapter
997
998
999 class TestValidatingEveryConfigFile:
1000 """`validate_config_files()`: the reader a problem does not stop.
1001
1002 Every other reader here raises at the first thing it cannot use, because it
1003 is on its way to a database. This one is not going anywhere, so it opens
1004 every file and reports what each of them says.
1005 """
1006
1007 OPTIONS: list[AbstractOption] = [
1008 FlagOption(name="read_only", description="x"),
1009 TextOption(name="port", description="x"),
1010 ]
1011 COMMAND_OPTIONS = {"adapter", "conn_str", "limit", *TUI_ONLY_KEYS}
1012
1013 def validate(
1014 self,
1015 adapter_class: Callable[[str], type[HarlequinAdapter] | None] | None = None,
1016 ) -> list[ConfigProblem]:
1017 return validate_config_files(
1018 None,
1019 adapter_class=adapter_class or (lambda _: adapter_declaring(self.OPTIONS)),
1020 command_options=self.COMMAND_OPTIONS,
1021 )
1022
1023 def test_a_config_with_nothing_wrong_has_nothing_to_report(
1024 self, config_dirs: tuple[Path, Path]
1025 ) -> None:
1026 cwd, home = config_dirs
1027 (home / ".harlequin.toml").write_text(
1028 'default_profile = "prod"\n[profiles.prod]\nread_only = true\nlimit = 10\n'
1029 )
1030 (cwd / ".harlequin.toml").write_text("[profiles.dev]\nport = 5432\n")
1031
1032 assert self.validate() == []
1033
1034 def test_a_read_only_the_adapter_cannot_do_is_a_problem(
1035 self, config_dirs: tuple[Path, Path]
1036 ) -> None:
1037 """The one key a profile can be wrong about without misspelling
1038 anything: every command refuses to connect under it."""
1039 cwd, _ = config_dirs
1040 (cwd / ".harlequin.toml").write_text("[profiles.prod]\nread_only = true\n")
1041
1042 (problem,) = self.validate(
1043 adapter_class=lambda _: adapter_declaring(self.OPTIONS, read_only=False)
1044 )
1045 assert problem.key == "profiles.prod.read_only"
1046 assert "read-only" in problem.message
1047
1048 def test_a_read_only_the_adapter_can_do_is_not(
1049 self, config_dirs: tuple[Path, Path]
1050 ) -> None:
1051 cwd, _ = config_dirs
1052 (cwd / ".harlequin.toml").write_text(
1053 "[profiles.prod]\nread_only = true\n[profiles.dev]\nread_only = false\n"
1054 )
1055
1056 assert self.validate() == []
1057
1058 def test_a_file_it_cannot_parse_does_not_end_the_run(
1059 self, config_dirs: tuple[Path, Path]
1060 ) -> None:
1061 """The difference from every other reader, in one assertion.
1062
1063 `load_config()` raises at the first file here and never opens the second
1064 one; this reports the file it could not parse *and* what is wrong with
1065 the one behind it.
1066 """
1067 cwd, home = config_dirs
1068 (cwd / ".harlequin.toml").write_text("this is not toml\n")
1069 (home / ".harlequin.toml").write_text("[profiles.prod]\nreed_only = true\n")
1070
1071 with pytest.raises(HarlequinConfigError):
1072 load_config(config_path=None)
1073
1074 assert [problem.path for problem in self.validate()] == [
1075 cwd / ".harlequin.toml",
1076 home / ".harlequin.toml",
1077 ]
1078
1079 def test_the_parser_is_the_only_thing_that_knows_a_line(
1080 self, config_dirs: tuple[Path, Path]
1081 ) -> None:
1082 """A line where tomllib gave one, and none where nothing did.
1083
1084 A number that was not read out of a parser is a number a reader goes to
1085 and finds nothing at.
1086 """
1087 cwd, home = config_dirs
1088 (cwd / ".harlequin.toml").write_text('[profiles.prod]\nport = "5432"\noops\n')
1089 (home / ".harlequin.toml").write_text("[profiles.dev]\nreed_only = true\n")
1090
1091 unparseable, unknown_option = self.validate()
1092 assert unparseable.line == 3
1093 assert unparseable.key is None
1094 assert unknown_option.line is None
1095
1096 def test_a_profile_is_checked_in_every_file_that_defines_it(
1097 self, config_dirs: tuple[Path, Path]
1098 ) -> None:
1099 """What validating before merging buys, and why it is per file.
1100
1101 The nearer file supplies `shared` whole, so the home file's copy of it
1102 is not what any invocation runs -- and it is still a table its author
1103 will edit, so it is still worth being told about.
1104 """
1105 cwd, home = config_dirs
1106 (home / ".harlequin.toml").write_text("[profiles.shared]\nreed_only = true\n")
1107 (cwd / ".harlequin.toml").write_text("[profiles.shared]\nread_only = true\n")
1108
1109 (problem,) = self.validate()
1110 assert problem.path == home / ".harlequin.toml"
1111 assert problem.key == "profiles.shared.reed_only"
1112
1113 def test_every_unknown_option_in_a_profile_is_reported(
1114 self, config_dirs: tuple[Path, Path]
1115 ) -> None:
1116 """A profile with three typos has three problems, not one, twice."""
1117 cwd, _ = config_dirs
1118 (cwd / ".harlequin.toml").write_text(
1119 "[profiles.prod]\nreed_only = true\nprt = 5432\nhost = 'localhost'\n"
1120 )
1121
1122 assert [problem.key for problem in self.validate()] == [
1123 "profiles.prod.host",
1124 "profiles.prod.prt",
1125 "profiles.prod.reed_only",
1126 ]
1127
1128 def test_an_adapter_that_will_not_load_belongs_to_the_profile(
1129 self, config_dirs: tuple[Path, Path]
1130 ) -> None:
1131 """A name nothing installed provides ends the profile, not the report."""
1132 cwd, _ = config_dirs
1133 (cwd / ".harlequin.toml").write_text(
1134 '[profiles.gone]\nadapter = "no-such-adapter"\n'
1135 "[profiles.fine]\nread_only = true\n"
1136 )
1137
1138 def adapter_class(name: str) -> type[HarlequinAdapter] | None:
1139 if name == "no-such-adapter":
1140 raise HarlequinConfigError("No installed plug-in provides one.")
1141 return adapter_declaring(self.OPTIONS)
1142
1143 (problem,) = self.validate(adapter_class=adapter_class)
1144 assert problem.key == "profiles.gone.adapter"
1145
1146 def test_a_default_that_names_no_profile_belongs_to_the_merge(
1147 self, config_dirs: tuple[Path, Path]
1148 ) -> None:
1149 """Reported against the file that set the key, which the merge knows.
1150
1151 No single file is wrong here -- naming a profile another file defines is
1152 exactly what `default_profile` is for -- so it is the one check that
1153 waits until every file has been read.
1154 """
1155 cwd, home = config_dirs
1156 (home / ".harlequin.toml").write_text('default_profile = "gone"\n')
1157 (cwd / ".harlequin.toml").write_text("[profiles.here]\nread_only = true\n")
1158
1159 (problem,) = self.validate()
1160 assert problem.path == home / ".harlequin.toml"
1161 assert problem.key == "default_profile"
1162 assert "gone" in problem.message
1163
1164 def test_a_default_a_farther_file_defines_is_not_a_problem(
1165 self, config_dirs: tuple[Path, Path]
1166 ) -> None:
1167 cwd, home = config_dirs
1168 (cwd / ".harlequin.toml").write_text('default_profile = "prod"\n')
1169 (home / ".harlequin.toml").write_text("[profiles.prod]\nread_only = true\n")
1170
1171 assert self.validate() == []
1172
1173
1174 class TestInterpolatingEnvironmentVariables:
1175 """`${VAR}` in a config file, and everything that is not one.
1176
1177 Read-path only, which is the half of this that can write a plaintext
1178 password into a user's file if it is wrong -- so the file itself is
1179 asserted to still say what its author typed.
1180 """
1181
1182 def config(self, tmp_path: Path, body: str) -> Path:
1183 path = tmp_path / ".harlequin.toml"
1184 path.write_text(body)
1185 return path
1186
1187 def profile(self, tmp_path: Path, body: str) -> Profile:
1188 return load_profile(
1189 config_path=self.config(tmp_path, f"[profiles.prod]\n{body}"),
1190 profile_name="prod",
1191 )
1192
1193 def test_a_variable_is_read_from_the_environment(
1194 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1195 ) -> None:
1196 monkeypatch.setenv("MYPASSWORD", "hunter2")
1197 assert self.profile(tmp_path, 'password = "${MYPASSWORD}"') == {
1198 "password": "hunter2"
1199 }
1200
1201 def test_a_variable_is_substituted_where_it_stands(
1202 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1203 ) -> None:
1204 """A DSN is the case this feature is for, and it is not the whole value."""
1205 monkeypatch.setenv("MYPASSWORD", "hunter2")
1206 assert self.profile(
1207 tmp_path, 'conn_str = ["postgresql://me:${MYPASSWORD}@db:5432/prod"]'
1208 ) == {"conn_str": ["postgresql://me:hunter2@db:5432/prod"]}
1209
1210 def test_a_default_is_what_an_unset_variable_reads_as(
1211 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1212 ) -> None:
1213 monkeypatch.delenv("MYHOST", raising=False)
1214 assert self.profile(tmp_path, 'host = "${MYHOST:-localhost}"') == {
1215 "host": "localhost"
1216 }
1217
1218 def test_a_variable_that_is_set_beats_its_default(
1219 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1220 ) -> None:
1221 monkeypatch.setenv("MYHOST", "warehouse")
1222 assert self.profile(tmp_path, 'host = "${MYHOST:-localhost}"') == {
1223 "host": "warehouse"
1224 }
1225
1226 def test_a_variable_set_to_nothing_takes_its_default(
1227 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1228 ) -> None:
1229 """What `:-` means to a shell, and the reading a caller can predict."""
1230 monkeypatch.setenv("MYHOST", "")
1231 assert self.profile(tmp_path, 'host = "${MYHOST:-localhost}"') == {
1232 "host": "localhost"
1233 }
1234
1235 def test_a_default_may_be_nothing(
1236 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1237 ) -> None:
1238 monkeypatch.delenv("MYOPTIONS", raising=False)
1239 assert self.profile(tmp_path, 'options = "${MYOPTIONS:-}"') == {"options": ""}
1240
1241 @pytest.mark.parametrize(
1242 "written,expected",
1243 [
1244 ("$${HOME}", "${HOME}"),
1245 ("{HOME}", "{HOME}"),
1246 ("$HOME", "$HOME"),
1247 ("${not a var}", "${not a var}"),
1248 ("${HOME", "${HOME"),
1249 ("100$", "100$"),
1250 ("p@ss{w0rd}$", "p@ss{w0rd}$"),
1251 ],
1252 )
1253 def test_what_is_not_a_substitution_is_left_alone(
1254 self,
1255 tmp_path: Path,
1256 monkeypatch: pytest.MonkeyPatch,
1257 written: str,
1258 expected: str,
1259 ) -> None:
1260 """Nothing anyone has in a password today needs escaping.
1261
1262 `$${` is the escape for the one spelling that does, and every other
1263 arrangement of the same characters is text.
1264 """
1265 monkeypatch.setenv("HOME", "/home/someone")
1266 assert self.profile(tmp_path, f'password = "{written}"') == {
1267 "password": expected
1268 }
1269
1270 def test_every_string_in_the_profile_is_read(
1271 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1272 ) -> None:
1273 """Through arrays and tables, and over values rather than keys."""
1274 monkeypatch.setenv("HARLEQUIN_TEST_VAR", "resolved")
1275 assert self.profile(
1276 tmp_path,
1277 'conn_str = ["one_${HARLEQUIN_TEST_VAR}", "two_${HARLEQUIN_TEST_VAR}"]\n'
1278 "[profiles.prod.nested]\n"
1279 'key = "${HARLEQUIN_TEST_VAR}"\n',
1280 ) == {
1281 "conn_str": ["one_resolved", "two_resolved"],
1282 "nested": {"key": "resolved"},
1283 }
1284
1285 def test_a_profile_an_invocation_is_not_running_is_not_read(
1286 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1287 ) -> None:
1288 """The rule `default_profile` follows: a key an invocation overrode is
1289 not a key to refuse it over.
1290
1291 A team's config file names a variable each of them keeps in their own
1292 environment, and the one querying the dev database has never had it set.
1293 """
1294 monkeypatch.delenv("HARLEQUIN_TEST_VAR", raising=False)
1295 path = self.config(
1296 tmp_path,
1297 'default_profile = "dev"\n'
1298 "[profiles.dev]\n"
1299 'conn_str = ["dev.db"]\n'
1300 "[profiles.prod]\n"
1301 'password = "${HARLEQUIN_TEST_VAR}"\n',
1302 )
1303 assert load_profile(config_path=path, profile_name=None) == {
1304 "conn_str": ["dev.db"]
1305 }
1306 assert load_profile_and_keymaps(config_path=path, profile_name="dev")[0] == {
1307 "conn_str": ["dev.db"]
1308 }
1309 with pytest.raises(HarlequinConfigError):
1310 load_profile(config_path=path, profile_name="prod")
1311
1312 def test_a_document_that_is_being_reported_on_is_not_resolved(
1313 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1314 ) -> None:
1315 """`--config show` and the debug screen report on files, so they report
1316 what the files say -- and neither is stopped by an unset variable."""
1317 monkeypatch.delenv("HARLEQUIN_TEST_VAR", raising=False)
1318 path = self.config(
1319 tmp_path, '[profiles.prod]\npassword = "${HARLEQUIN_TEST_VAR}"\n'
1320 )
1321 config = load_config(config_path=path)
1322 assert config.profiles["prod"] == {"password": "${HARLEQUIN_TEST_VAR}"}
1323
1324 def test_a_number_is_still_a_number(
1325 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1326 ) -> None:
1327 monkeypatch.setenv("HARLEQUIN_TEST_VAR", "1")
1328 assert self.profile(tmp_path, "limit = 10\nread_only = true") == {
1329 "limit": 10,
1330 "read_only": True,
1331 }
1332
1333 def test_an_unset_variable_names_itself_the_key_and_the_file(
1334 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1335 ) -> None:
1336 """An error rather than an empty string.
1337
1338 A password that silently became `""` is an authentication error three
1339 layers away from the config file that caused it.
1340 """
1341 monkeypatch.delenv("HARLEQUIN_TEST_VAR", raising=False)
1342 path = self.config(
1343 tmp_path, '[profiles.prod]\npassword = "${HARLEQUIN_TEST_VAR}"\n'
1344 )
1345 with pytest.raises(HarlequinConfigError) as excinfo:
1346 load_profile(config_path=path, profile_name="prod")
1347 assert "HARLEQUIN_TEST_VAR" in excinfo.value.msg
1348 assert "profiles.prod.password" in excinfo.value.msg
1349 assert str(path) in excinfo.value.msg
1350
1351 def test_an_unset_variable_in_an_array_names_where_it_is(
1352 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1353 ) -> None:
1354 monkeypatch.delenv("HARLEQUIN_TEST_VAR", raising=False)
1355 path = self.config(
1356 tmp_path,
1357 '[profiles.prod]\nconn_str = ["fine.db", "${HARLEQUIN_TEST_VAR}"]\n',
1358 )
1359 with pytest.raises(HarlequinConfigError) as excinfo:
1360 load_profile(config_path=path, profile_name="prod")
1361 assert "profiles.prod.conn_str[1]" in excinfo.value.msg
1362
1363 def test_an_unset_variable_is_a_problem_validation_reports_and_reads_past(
1364 self, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
1365 ) -> None:
1366 """The reader a problem does not stop finds the rest of them too."""
1367 monkeypatch.delenv("HARLEQUIN_TEST_VAR", raising=False)
1368 cwd, home = config_dirs
1369 (cwd / ".harlequin.toml").write_text(
1370 '[profiles.prod]\npassword = "${HARLEQUIN_TEST_VAR}"\n'
1371 )
1372 (home / ".harlequin.toml").write_text("[profiles.dev]\nreed_only = true\n")
1373
1374 unset, misspelled = validate_config_files(
1375 None,
1376 adapter_class=lambda _: adapter_declaring(
1377 [
1378 FlagOption(name="read_only", description="x"),
1379 TextOption(name="password", description="x"),
1380 ]
1381 ),
1382 command_options={"adapter", *TUI_ONLY_KEYS},
1383 )
1384 assert unset.path == cwd / ".harlequin.toml"
1385 assert unset.key == "profiles.prod.password"
1386 assert "HARLEQUIN_TEST_VAR" in unset.message
1387 assert misspelled.key == "profiles.dev.reed_only"
1388
1389 def test_the_file_the_write_path_reads_says_what_its_author_typed(
1390 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1391 ) -> None:
1392 """The one place getting the layering wrong writes a secret to disk.
1393
1394 `harlequin --config` reads this, edits it, and writes it back, so a
1395 value resolved here is a resolved password in the user's file.
1396 """
1397 monkeypatch.setenv("MYPASSWORD", "hunter2")
1398 path = self.config(tmp_path, '[profiles.prod]\npassword = "${MYPASSWORD}"\n')
1399 raw = ConfigFile(path).relevant_config
1400 assert raw["profiles"]["prod"]["password"] == "${MYPASSWORD}"