| 1 |
r"""Shell-completion test harness. |
| 2 |
|
| 3 |
Each shell exposes two capabilities: |
| 4 |
|
| 5 |
* ``validate_script_syntax()`` - runs ``{bash,zsh,fish} -n`` on the generated |
| 6 |
script. Already non-interactive. |
| 7 |
* ``get_completions(partial)`` - returns the list of suggestions a user would |
| 8 |
see for a partial command line. |
| 9 |
|
| 10 |
* **Bash** - spawn ``bash -c``, source the completion script, populate |
| 11 |
``COMP_WORDS`` using a ``COMP_WORDBREAKS``-aware tokenizer (default |
| 12 |
``WORDBREAKS`` includes ``=`` and ``:``, which matters for ``--opt=value`` |
| 13 |
and ``host:port`` forms), invoke the registered ``_<prog>`` function, and |
| 14 |
print ``COMPREPLY``. No TTY, no timing. Bash 3.2-safe (the mac-stock |
| 15 |
version). |
| 16 |
* **Fish** - use fish's built-in ``complete -C '<partial>'`` flag. Prints |
| 17 |
``completion\tdescription`` one per line. Deterministic since fish 3.0. |
| 18 |
* **Zsh** - drive an interactive ``zsh -i`` via ``pexpect`` and ask it to |
| 19 |
*list* matches without modifying the line by sending the |
| 20 |
``list-choices`` widget (``\e\C-d``). Matches are screen-scraped between |
| 21 |
two prompt sentinels. Skipped if ``pexpect`` is unavailable. |
| 22 |
""" |
| 23 |
|
| 24 |
import os |
| 25 |
import re |
| 26 |
import subprocess |
| 27 |
import tempfile |
| 28 |
from abc import ABC, abstractmethod |
| 29 |
from pathlib import Path |
| 30 |
|
| 31 |
import pytest |
| 32 |
|
| 33 |
|
| 34 |
class CompletionTesterBase(ABC): |
| 35 |
"""Base class for shell completion testers.""" |
| 36 |
|
| 37 |
def __init__(self, completion_script: str, prog_name: str): |
| 38 |
self.completion_script = completion_script |
| 39 |
self.prog_name = prog_name |
| 40 |
|
| 41 |
@abstractmethod |
| 42 |
def validate_script_syntax(self) -> bool: |
| 43 |
"""Return True if the generated script is syntactically valid for this shell.""" |
| 44 |
|
| 45 |
@abstractmethod |
| 46 |
def get_completions(self, partial_command: str) -> list[str]: |
| 47 |
"""Return the completion suggestions a real shell would offer for ``partial_command``.""" |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
_BASH_FUNC_RE = re.compile(r"^complete -F (\S+) ", re.MULTILINE) |
| 54 |
|
| 55 |
|
| 56 |
class BashCompletionTester(CompletionTesterBase): |
| 57 |
"""Bash completion tester using a non-interactive ``bash -c`` driver.""" |
| 58 |
|
| 59 |
def validate_script_syntax(self) -> bool: |
| 60 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 61 |
comp_file = Path(tmpdir) / f"{self.prog_name}_completion.bash" |
| 62 |
comp_file.write_text(self.completion_script) |
| 63 |
result = subprocess.run( |
| 64 |
["bash", "-n", str(comp_file)], |
| 65 |
capture_output=True, |
| 66 |
text=True, |
| 67 |
timeout=5, |
| 68 |
) |
| 69 |
return result.returncode == 0 |
| 70 |
|
| 71 |
def get_completions(self, partial_command: str) -> list[str]: |
| 72 |
match = _BASH_FUNC_RE.search(self.completion_script) |
| 73 |
if not match: |
| 74 |
raise RuntimeError("Could not locate 'complete -F <fn>' line in generated bash script") |
| 75 |
func_name = match.group(1) |
| 76 |
|
| 77 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 78 |
comp_file = Path(tmpdir) / f"{self.prog_name}_completion.bash" |
| 79 |
comp_file.write_text(self.completion_script) |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
driver = ( |
| 87 |
'source "$1"\n' |
| 88 |
'COMP_LINE="$2"\n' |
| 89 |
"COMP_POINT=${#COMP_LINE}\n" |
| 90 |
"COMP_WORDS=()\n" |
| 91 |
"COMPREPLY=()\n" |
| 92 |
"_word=''\n" |
| 93 |
"for ((_k=0; _k<${#COMP_LINE}; _k++)); do\n" |
| 94 |
' _ch="${COMP_LINE:$_k:1}"\n' |
| 95 |
' case "$_ch" in\n' |
| 96 |
" ' '|$'\\t'|$'\\n')\n" |
| 97 |
' [[ -n "$_word" ]] && { COMP_WORDS+=("$_word"); _word=""; }\n' |
| 98 |
" ;;\n" |
| 99 |
" '\"'|\"'\"|'<'|'>'|'='|';'|'|'|'&'|'('|':')\n" |
| 100 |
' [[ -n "$_word" ]] && { COMP_WORDS+=("$_word"); _word=""; }\n' |
| 101 |
' COMP_WORDS+=("$_ch")\n' |
| 102 |
" ;;\n" |
| 103 |
" *)\n" |
| 104 |
' _word+="$_ch"\n' |
| 105 |
" ;;\n" |
| 106 |
" esac\n" |
| 107 |
"done\n" |
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
'if [[ "${COMP_LINE: -1}" == " " || "${COMP_LINE: -1}" == $\'\\t\' ]]; then\n' |
| 112 |
' [[ -n "$_word" ]] && COMP_WORDS+=("$_word")\n' |
| 113 |
' COMP_WORDS+=("")\n' |
| 114 |
"else\n" |
| 115 |
' COMP_WORDS+=("$_word")\n' |
| 116 |
"fi\n" |
| 117 |
"COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 ))\n" |
| 118 |
f'"{func_name}" "$3" "${{COMP_WORDS[COMP_CWORD]}}" "${{COMP_WORDS[COMP_CWORD-1]:-}}" >/dev/null\n' |
| 119 |
'printf "%s\\n" "${COMPREPLY[@]}"\n' |
| 120 |
) |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
result = subprocess.run( |
| 128 |
["bash", "-c", driver, "_", str(comp_file), partial_command, self.prog_name], |
| 129 |
capture_output=True, |
| 130 |
text=True, |
| 131 |
timeout=5, |
| 132 |
) |
| 133 |
if result.returncode != 0: |
| 134 |
raise RuntimeError( |
| 135 |
f"bash driver failed (exit {result.returncode}): {result.stderr.strip() or result.stdout.strip()}" |
| 136 |
) |
| 137 |
return [line for line in result.stdout.splitlines() if line] |
| 138 |
|
| 139 |
|
| 140 |
def _check_bash_available() -> bool: |
| 141 |
try: |
| 142 |
result = subprocess.run(["bash", "--version"], capture_output=True, text=True, timeout=2) |
| 143 |
return result.returncode == 0 and "bash" in result.stdout.lower() |
| 144 |
except (subprocess.SubprocessError, FileNotFoundError): |
| 145 |
return False |
| 146 |
|
| 147 |
|
| 148 |
@pytest.fixture(scope="session") |
| 149 |
def bash_available(): |
| 150 |
return _check_bash_available() |
| 151 |
|
| 152 |
|
| 153 |
@pytest.fixture |
| 154 |
def bash_tester(bash_available): |
| 155 |
if not bash_available: |
| 156 |
pytest.skip("bash not available") |
| 157 |
|
| 158 |
def _make_tester(app, prog_name="testapp"): |
| 159 |
script = app.generate_completion(prog_name=prog_name, shell="bash") |
| 160 |
return BashCompletionTester(script, prog_name) |
| 161 |
|
| 162 |
return _make_tester |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
class FishCompletionTester(CompletionTesterBase): |
| 169 |
"""Fish completion tester using the built-in non-interactive ``complete -C`` flag.""" |
| 170 |
|
| 171 |
def validate_script_syntax(self) -> bool: |
| 172 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 173 |
comp_file = Path(tmpdir) / f"{self.prog_name}.fish" |
| 174 |
comp_file.write_text(self.completion_script) |
| 175 |
result = subprocess.run( |
| 176 |
["fish", "-n", str(comp_file)], |
| 177 |
capture_output=True, |
| 178 |
text=True, |
| 179 |
timeout=5, |
| 180 |
) |
| 181 |
return result.returncode == 0 |
| 182 |
|
| 183 |
def get_completions(self, partial_command: str) -> list[str]: |
| 184 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 185 |
comp_file = Path(tmpdir) / f"{self.prog_name}.fish" |
| 186 |
comp_file.write_text(self.completion_script) |
| 187 |
|
| 188 |
|
| 189 |
or |
| 190 |
|
| 191 |
script = "source $argv[1]; complete -C $argv[2]" |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
result = subprocess.run( |
| 196 |
["fish", "-c", script, str(comp_file), partial_command], |
| 197 |
capture_output=True, |
| 198 |
text=True, |
| 199 |
timeout=5, |
| 200 |
) |
| 201 |
if result.returncode != 0: |
| 202 |
raise RuntimeError( |
| 203 |
f"fish driver failed (exit {result.returncode}): {result.stderr.strip() or result.stdout.strip()}" |
| 204 |
) |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
ld |
| 210 |
|
| 211 |
|
| 212 |
current_word = "" if partial_command.endswith(" ") else partial_command.rsplit(maxsplit=1)[-1] |
| 213 |
eq_prefix = current_word[: current_word.rindex("=") + 1] if "=" in current_word else "" |
| 214 |
|
| 215 |
completions = [] |
| 216 |
for line in result.stdout.splitlines(): |
| 217 |
if not line: |
| 218 |
continue |
| 219 |
token = line.split("\t", 1)[0] |
| 220 |
if eq_prefix and token.startswith(eq_prefix): |
| 221 |
token = token[len(eq_prefix) :] |
| 222 |
completions.append(token) |
| 223 |
return completions |
| 224 |
|
| 225 |
|
| 226 |
def _check_fish_available() -> bool: |
| 227 |
try: |
| 228 |
result = subprocess.run(["fish", "--version"], capture_output=True, text=True, timeout=2) |
| 229 |
return result.returncode == 0 and "fish" in result.stdout.lower() |
| 230 |
except (subprocess.SubprocessError, FileNotFoundError): |
| 231 |
return False |
| 232 |
|
| 233 |
|
| 234 |
@pytest.fixture(scope="session") |
| 235 |
def fish_available(): |
| 236 |
return _check_fish_available() |
| 237 |
|
| 238 |
|
| 239 |
@pytest.fixture |
| 240 |
def fish_tester(fish_available): |
| 241 |
if not fish_available: |
| 242 |
pytest.skip("fish not available") |
| 243 |
|
| 244 |
def _make_tester(app, prog_name="testapp"): |
| 245 |
script = app.generate_completion(prog_name=prog_name, shell="fish") |
| 246 |
return FishCompletionTester(script, prog_name) |
| 247 |
|
| 248 |
return _make_tester |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
_ZSH_ANSI_RE = re.compile(r"\x1b\[[\d;?]*[a-zA-Z]|\x1b[=>()][a-zA-Z0-9]?|\x1b[=>]|\r|\x07|\x0e|\x0f") |
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
_ZSH_COLUMN_GAP = re.compile(r" {2,}") |
| 260 |
|
| 261 |
|
| 262 |
def _zsh_unescape_match(token: str) -> str: |
| 263 |
r"""Reverse the ``\X``-style display escape zsh applies to listed matches.""" |
| 264 |
out: list[str] = [] |
| 265 |
i = 0 |
| 266 |
while i < len(token): |
| 267 |
if token[i] == "\\" and i + 1 < len(token): |
| 268 |
out.append(token[i + 1]) |
| 269 |
i += 2 |
| 270 |
else: |
| 271 |
out.append(token[i]) |
| 272 |
i += 1 |
| 273 |
return "".join(out) |
| 274 |
|
| 275 |
|
| 276 |
class ZshCompletionTester(CompletionTesterBase): |
| 277 |
r"""Zsh completion tester driven via ``pexpect``. |
| 278 |
|
| 279 |
zsh's completion helpers (``_arguments``, ``_describe``, ``_files``) only |
| 280 |
run inside a real zle widget context, so the driver spawns an interactive |
| 281 |
``zsh -i`` in a pty. To get matches without zsh inserting / cycling |
| 282 |
through them, the partial line is followed by the ``list-choices`` widget |
| 283 |
(``\e\C-d``), which lists matches in place and leaves the buffer |
| 284 |
untouched. Output is screen-scraped between two prompt sentinels and |
| 285 |
stripped of ANSI. |
| 286 |
|
| 287 |
Notes |
| 288 |
----- |
| 289 |
* Skipped if ``pexpect`` is not importable (e.g. Windows). |
| 290 |
* The TERM is forced to ``dumb`` to minimize control-byte noise. |
| 291 |
* ``ZDOTDIR`` is pointed at a temp dir so the host's ``.zshrc`` cannot |
| 292 |
perturb completion (custom widgets, ``zstyle`` settings, oh-my-zsh). |
| 293 |
""" |
| 294 |
|
| 295 |
def validate_script_syntax(self) -> bool: |
| 296 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 297 |
comp_file = Path(tmpdir) / f"_cyclopts_{self.prog_name}" |
| 298 |
comp_file.write_text(self.completion_script) |
| 299 |
result = subprocess.run( |
| 300 |
["zsh", "-n", str(comp_file)], |
| 301 |
capture_output=True, |
| 302 |
text=True, |
| 303 |
timeout=5, |
| 304 |
) |
| 305 |
return result.returncode == 0 |
| 306 |
|
| 307 |
def get_completions(self, partial_command: str) -> list[str]: |
| 308 |
try: |
| 309 |
import pexpect |
| 310 |
except ImportError: |
| 311 |
pytest.skip("pexpect not available") |
| 312 |
|
| 313 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 314 |
td = Path(tmpdir) |
| 315 |
(td / f"_cyclopts_{self.prog_name}").write_text(self.completion_script) |
| 316 |
|
| 317 |
(td / ".zshrc").write_text( |
| 318 |
"PROMPT='ZTEST> '\n" |
| 319 |
f"fpath=({td} $fpath)\n" |
| 320 |
"autoload -Uz compinit && compinit -u\n" |
| 321 |
|
| 322 |
|
| 323 |
"unsetopt MENU_COMPLETE AUTO_MENU AUTO_LIST\n" |
| 324 |
"setopt NO_BEEP NO_LIST_BEEP\n" |
| 325 |
|
| 326 |
"zstyle ':completion:*' format ''\n" |
| 327 |
"zstyle ':completion:*:descriptions' format ''\n" |
| 328 |
"zstyle ':completion:*:messages' format ''\n" |
| 329 |
"zstyle ':completion:*:warnings' format ''\n" |
| 330 |
"zstyle ':completion:*' verbose no\n" |
| 331 |
"zstyle ':completion:*' group-name ''\n" |
| 332 |
"zstyle ':completion:*' list-prompt ''\n" |
| 333 |
) |
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
We |
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
env_vars = { |
| 342 |
"HOME": str(td), |
| 343 |
"ZDOTDIR": str(td), |
| 344 |
"PATH": os.environ.get("PATH", "/usr/bin:/bin:/usr/local/bin"), |
| 345 |
"TERM": "dumb", |
| 346 |
} |
| 347 |
child = pexpect.spawn( |
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
"zsh --no-globalrcs -i", |
| 353 |
encoding="utf-8", |
| 354 |
env=env_vars, |
| 355 |
timeout=5, |
| 356 |
dimensions=(40, 400), |
| 357 |
) |
| 358 |
try: |
| 359 |
child.expect("ZTEST> ", timeout=4) |
| 360 |
child.send(partial_command) |
| 361 |
child.send("\x1b\x04") |
| 362 |
try: |
| 363 |
child.expect("ZTEST> ", timeout=1.5) |
| 364 |
except pexpect.TIMEOUT: |
| 365 |
pass |
| 366 |
output = child.before or "" |
| 367 |
finally: |
| 368 |
child.close(force=True) |
| 369 |
|
| 370 |
cleaned = _ZSH_ANSI_RE.sub("", output) |
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
lines = cleaned.split("\n") |
| 376 |
matches: list[str] = [] |
| 377 |
for line in lines[1:]: |
| 378 |
line = line.rstrip() |
| 379 |
if not line: |
| 380 |
continue |
| 381 |
for token in _ZSH_COLUMN_GAP.split(line): |
| 382 |
token = token.strip() |
| 383 |
if token: |
| 384 |
matches.append(_zsh_unescape_match(token)) |
| 385 |
return matches |
| 386 |
|
| 387 |
|
| 388 |
def _check_zsh_available() -> bool: |
| 389 |
try: |
| 390 |
result = subprocess.run(["zsh", "--version"], capture_output=True, text=True, timeout=2) |
| 391 |
return result.returncode == 0 and "zsh" in result.stdout.lower() |
| 392 |
except (subprocess.SubprocessError, FileNotFoundError): |
| 393 |
return False |
| 394 |
|
| 395 |
|
| 396 |
@pytest.fixture(scope="session") |
| 397 |
def zsh_available(): |
| 398 |
return _check_zsh_available() |
| 399 |
|
| 400 |
|
| 401 |
@pytest.fixture |
| 402 |
def zsh_tester(zsh_available): |
| 403 |
if not zsh_available: |
| 404 |
pytest.skip("zsh not available") |
| 405 |
|
| 406 |
def _make_tester(app, prog_name="testapp"): |
| 407 |
script = app.generate_completion(prog_name=prog_name, shell="zsh") |
| 408 |
return ZshCompletionTester(script, prog_name) |
| 409 |
|
| 410 |
return _make_tester |