Debian Codegraph @

tests/unit_tests/test_cli_reference.py

raw
1 """The CLI reference the site publishes, and the guarantee that it is current.
2
3 `docs/generated/hsql-reference.md` is a build artifact: nothing reads it at run
4 time, and the release workflow is what carries it to harlequin.sh. So this is
5 the only thing that notices when hsql grows an option, renames one, or changes
6 what it takes, and the committed page goes on saying what used to be true.
7
8 It also checks the two things a generated page can still get wrong: a table
9 cell that breaks its table, and a document built from what happens to be
10 installed rather than from the command.
11 """
12
13 from __future__ import annotations
14
15 import importlib.util
16 import re
17 from pathlib import Path
18 from types import ModuleType
19
20 import pytest
21
22 from harlequin.hsql import output
23 from harlequin.hsql.diagnostics import ExitCode
24
25 REPO_ROOT = Path(__file__).resolve().parents[2]
26 GENERATOR_PATH = REPO_ROOT / "scripts" / "write_cli_reference.py"
27 REFERENCE_PATH = REPO_ROOT / "docs" / "generated" / "hsql-reference.md"
28
29 FIX = "uv run python scripts/write_cli_reference.py"
30 """What to run when the committed reference and the generator disagree."""
31
32
33 @pytest.fixture(scope="module")
34 def generator() -> ModuleType:
35 """The generator, loaded from `scripts/`, which is not an importable package."""
36 spec = importlib.util.spec_from_file_location("write_cli_reference", GENERATOR_PATH)
37 assert spec is not None and spec.loader is not None
38 module = importlib.util.module_from_spec(spec)
39 spec.loader.exec_module(module)
40 return module
41
42
43 @pytest.fixture(scope="module")
44 def generated(generator: ModuleType) -> str:
45 text: str = generator.build_reference()
46 return text
47
48
49 @pytest.fixture(scope="module")
50 def committed() -> str:
51 return REFERENCE_PATH.read_text(encoding="utf-8")
52
53
54 def test_the_committed_reference_is_what_the_generator_writes(
55 generated: str, committed: str
56 ) -> None:
57 assert committed == generated, f"the CLI reference is out of date: {FIX}"
58
59
60 def test_every_option_hsql_has_is_a_row(generated: str) -> None:
61 """The point of generating it: nothing hand-written can be left behind."""
62 from harlequin.hsql.cli import bare_command
63 from harlequin.hsql.modes.spec import command_document
64
65 for option in command_document(bare_command())["options"]:
66 for decl in option["decls"]:
67 assert f"`{decl}`" in generated, f"{decl} is missing from the reference"
68
69
70 def test_the_adapters_installed_here_are_not_written_down(generated: str) -> None:
71 """A published page describes the command, not the machine that built it.
72
73 `-a` takes an enum of what is installed, so a reference generated on a box
74 with postgres on it would tell every reader that postgres is an option.
75 """
76 from harlequin.plugins import adapter_names
77
78 values = _row(generated, "`-a`, `--adapter`")[2]
79 assert values == "`NAME`"
80 assert not [name for name in adapter_names() if name in values]
81
82
83 def test_the_choices_an_option_does_have_are_written_down(generated: str) -> None:
84 """The other half of the one above: dropping the enum is one option's rule."""
85 assert _row(generated, "`--color`")[2] == "`auto`, `always`, `never`"
86
87
88 def test_every_format_is_a_row_with_the_suffix_it_writes(generated: str) -> None:
89 """`-o DIRECTORY` names files by these, so a wrong one is a wrong filename."""
90 for name in output.format_names():
91 suffix = output.suffix(name)
92 assert _row(generated, f"`{name}`")[2] == (f"`{suffix}`" if suffix else "")
93
94
95 def test_every_exit_code_is_described(generated: str, generator: ModuleType) -> None:
96 """A code with no meaning beside it fails the generator, so this is what
97 catches the one that was added without one."""
98 described = generator.EXIT_CODES
99 assert set(described) == set(ExitCode)
100 for code in ExitCode:
101 assert f"| `{code.value}` | {described[code]} |" in generated
102
103
104 def test_no_cell_breaks_the_table_it_is_in(generated: str) -> None:
105 """An unescaped pipe silently splits a row into one column too many.
106
107 `--result all|last|N` is the cell that would, so this counts the columns
108 every row actually has rather than trusting the cells that produced them.
109 """
110 for table in _tables(generated):
111 widths = {len(row) for row in table}
112 assert len(widths) == 1, f"a row of {table[0]} has the wrong width: {widths}"
113
114
115 def test_the_page_is_markdown_a_reader_can_land_in(generated: str) -> None:
116 """It is published as a page of its own, so it carries its own title."""
117 assert generated.startswith("<!-- Generated by scripts/write_cli_reference.py")
118 assert "\n# hsql\n" in generated
119 assert generated.endswith("\n")
120 assert "\r" not in generated
121
122
123 def _tables(page: str) -> list[list[list[str]]]:
124 """Every markdown table on the page, as rows of cells. A pipe a cell
125 escaped is part of that cell, which is the whole point of escaping it."""
126 tables: list[list[list[str]]] = []
127 for line in page.splitlines():
128 if not line.startswith("|"):
129 tables.append([])
130 continue
131 if not tables or not tables[-1]:
132 tables.append([])
133 tables[-1].append([cell.strip() for cell in re.split(r"(?<!\\)\|", line)[1:-1]])
134 return [table for table in tables if table]
135
136
137 def _row(page: str, first_cell: str) -> list[str]:
138 """The one row of one table whose first cell is this."""
139 rows = [row for table in _tables(page) for row in table if row[0] == first_cell]
140 assert len(rows) == 1, f"expected one row for {first_cell}, found {len(rows)}"
141 return rows[0]