import re from pathlib import Path import click import pytest from unshackle.commands.dl import dl from unshackle.commands.serve import serve CLI_REFERENCE = Path(__file__).parents[2] / "docs" / "guide" / "cli-reference.md" COMMANDS = [pytest.param("dl", dl.cli, id="dl"), pytest.param("serve", serve, id="serve")] def section(command: str) -> str: text = CLI_REFERENCE.read_text(encoding="utf-8") start = text.index(f"## `{command}`") return text[start : text.index("\n## ", start)] def table_flags(command: str) -> set[str]: """The flags in the first cell of each table row of one command's section of the CLI reference.""" return { flag for line in section(command).splitlines() if line.startswith("|") for flag in re.findall(r"`(--?[a-zA-Z][\w-]*)[` ]", line.split("|")[1]) } def option_flags(command: click.Command) -> set[str]: return { flag for param in command.params if param.param_type_name == "option" and not getattr(param, "hidden", False) for flag in (*param.opts, *param.secondary_opts) } @pytest.mark.parametrize(("name", "command"), COMMANDS) def test_every_option_is_in_the_cli_reference(name: str, command: click.Command) -> None: assert option_flags(command) - table_flags(name) == set() @pytest.mark.parametrize(("name", "command"), COMMANDS) def test_every_flag_in_the_cli_reference_is_an_option(name: str, command: click.Command) -> None: """Table flags of any length, and long flags anywhere in the section: a short flag in prose can be a value.""" long_flags = set(re.findall(r"`(--[a-zA-Z][\w-]*)", section(name))) assert (table_flags(name) | long_flags) - option_flags(command) == set()