1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
|
"""Tests to ensure CLI help examples are valid commands."""
from __future__ import annotations
import argparse
import subprocess
import pytest
from tmuxp.cli import create_parser
def _get_help_text(subcommand: str | None = None) -> str:
"""Get CLI help text without spawning subprocess.
Parameters
----------
subcommand : str | None
Subcommand name, or None for main help.
Returns
-------
str
The formatted help text.
"""
parser = create_parser()
if subcommand is None:
return parser.format_help()
# Access subparser via _subparsers._group_actions
subparsers = parser._subparsers
if subparsers is not None:
for action in subparsers._group_actions:
if isinstance(action, argparse._SubParsersAction):
choices = action.choices
if choices is not None and subcommand in choices:
return str(choices[subcommand].format_help())
return parser.format_help()
def extract_examples_from_help(help_text: str) -> list[str]:
r"""Extract example commands from help text.
Parameters
----------
help_text : str
The help output text to extract examples from.
Returns
-------
list[str]
List of extracted example commands.
Examples
--------
>>> text = "load:\n tmuxp load myproject\n\npositions:"
>>> extract_examples_from_help(text)
['tmuxp load myproject']
>>> text2 = "examples:\n tmuxp debug-info\n\noptions:"
>>> extract_examples_from_help(text2)
['tmuxp debug-info']
>>> text3 = "Field-scoped search:\n tmuxp search window:editor"
>>> extract_examples_from_help(text3)
['tmuxp search window:editor']
"""
examples = []
in_examples = False
for line in help_text.splitlines():
# Match example section headings:
# - "examples:" (default examples section)
# - "load examples:" (category headings with examples suffix)
# - "Field-scoped search:" (multi-word category headings)
# Exclude argparse sections like "positional arguments:", "options:"
stripped = line.strip()
is_section_heading = (
stripped.endswith(":")
and stripped not in ("positional arguments:", "options:")
and not stripped.startswith("-")
)
if is_section_heading:
in_examples = True
elif in_examples and line.startswith(" "):
cmd = line.strip()
if cmd.startswith("tmuxp"):
examples.append(cmd)
elif line and not line[0].isspace():
in_examples = False
return examples
def test_main_help_has_examples() -> None:
"""Main --help should have at least one example."""
help_text = _get_help_text()
examples = extract_examples_from_help(help_text)
assert len(examples) > 0, "Main --help should have at least one example"
def test_main_help_examples_are_valid_subcommands() -> None:
"""All examples in main --help should reference valid subcommands."""
help_text = _get_help_text()
examples = extract_examples_from_help(help_text)
# Extract valid subcommands from help output
valid_subcommands = {
"load",
"shell",
"import",
"convert",
"debug-info",
"ls",
"edit",
"freeze",
"search",
}
for example in examples:
parts = example.split()
if len(parts) >= 2:
subcommand = parts[1]
assert subcommand in valid_subcommands, (
f"Example '{example}' uses unknown subcommand '{subcommand}'"
)
@pytest.mark.parametrize(
"subcommand",
[
"load",
"shell",
"import",
"convert",
"debug-info",
"ls",
"edit",
"freeze",
"search",
],
)
def test_subcommand_help_has_examples(subcommand: str) -> None:
"""Each subcommand --help should have at least one example."""
help_text = _get_help_text(subcommand)
examples = extract_examples_from_help(help_text)
assert len(examples) > 0, f"{subcommand} --help should have at least one example"
def test_load_subcommand_examples_are_valid() -> None:
"""Load subcommand examples should have valid flags."""
help_text = _get_help_text("load")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp load"), f"Bad example format: {example}"
def test_freeze_subcommand_examples_are_valid() -> None:
"""Freeze subcommand examples should have valid flags."""
help_text = _get_help_text("freeze")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp freeze"), f"Bad example format: {example}"
def test_shell_subcommand_examples_are_valid() -> None:
"""Shell subcommand examples should have valid flags."""
help_text = _get_help_text("shell")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp shell"), f"Bad example format: {example}"
def test_convert_subcommand_examples_are_valid() -> None:
"""Convert subcommand examples should have valid flags."""
help_text = _get_help_text("convert")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp convert"), f"Bad example format: {example}"
def test_import_subcommand_examples_are_valid() -> None:
"""Import subcommand examples should have valid flags."""
help_text = _get_help_text("import")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp import"), f"Bad example format: {example}"
def test_edit_subcommand_examples_are_valid() -> None:
"""Edit subcommand examples should have valid flags."""
help_text = _get_help_text("edit")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp edit"), f"Bad example format: {example}"
def test_ls_subcommand_examples_are_valid() -> None:
"""Ls subcommand examples should have valid flags."""
help_text = _get_help_text("ls")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp ls"), f"Bad example format: {example}"
def test_debug_info_subcommand_examples_are_valid() -> None:
"""Debug-info subcommand examples should have valid flags."""
help_text = _get_help_text("debug-info")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp debug-info"), f"Bad example format: {example}"
def test_search_subcommand_examples_are_valid() -> None:
"""Search subcommand examples should have valid flags."""
help_text = _get_help_text("search")
examples = extract_examples_from_help(help_text)
# Verify each example has valid structure
for example in examples:
assert example.startswith("tmuxp search"), f"Bad example format: {example}"
def test_search_no_args_shows_help() -> None:
"""Running 'tmuxp search' with no args shows help.
Note: This test uses subprocess to verify actual CLI behavior and exit code.
"""
result = subprocess.run(
["tmuxp", "search"],
capture_output=True,
text=True,
)
# Should show help (usage line present)
assert "usage: tmuxp search" in result.stdout
# Should exit successfully (not error)
assert result.returncode == 0
def test_main_help_example_sections_have_examples_suffix() -> None:
"""Main --help should have section headings ending with 'examples:'."""
help_text = _get_help_text()
# Should have "load examples:", "freeze examples:", etc.
# NOT just "load:", "freeze:"
assert "load examples:" in help_text.lower()
assert "freeze examples:" in help_text.lower()
def test_main_help_examples_are_colorized(monkeypatch: pytest.MonkeyPatch) -> None:
"""Main --help should have colorized example sections when FORCE_COLOR is set."""
monkeypatch.delenv("NO_COLOR", raising=False)
monkeypatch.setenv("FORCE_COLOR", "1")
help_text = _get_help_text()
# Should contain ANSI escape codes for colorization
assert "\033[" in help_text, "Example sections should be colorized"
|