Debian Codegraph @

tests/completion/test_zsh.py

raw symbols SCIP
1 import re
2 from pathlib import Path
3 from typing import Annotated, Literal
4
5 import pytest
6
7 from cyclopts import App, Parameter
8 from cyclopts.completion.zsh import generate_completion_script
9
10 from .apps import (
11 app_basic,
12 app_disabled_negative,
13 app_enum,
14 app_list_annotated_path,
15 app_list_path,
16 app_markup,
17 app_negative,
18 app_nested,
19 app_path,
20 app_rst,
21 )
22
23
24 def test_basic_option_completion(zsh_tester):
25 """Test basic option name completion."""
26 tester = zsh_tester(app_basic, "basic")
27
28 assert "--verbose" in tester.completion_script
29 assert "--count" in tester.completion_script
30 assert "--help" in tester.completion_script
31
32
33 def test_command_completion(zsh_tester):
34 """Test command completion."""
35 tester = zsh_tester(app_basic, "basic")
36
37 assert "deploy" in tester.completion_script
38
39
40 def test_literal_value_completion(zsh_tester):
41 """Test Literal type value completion."""
42 tester = zsh_tester(app_basic, "basic")
43
44 assert "dev" in tester.completion_script
45 assert "staging" in tester.completion_script
46 assert "prod" in tester.completion_script
47
48
49 def test_enum_value_completion(zsh_tester):
50 """Test Enum type value completion."""
51 tester = zsh_tester(app_enum, "enumapp")
52
53 assert "fast" in tester.completion_script
54 assert "slow" in tester.completion_script
55
56
57 def test_nested_subcommand_completion(zsh_tester):
58 """Test nested subcommand completion."""
59 tester = zsh_tester(app_nested, "nested")
60
61 assert "config" in tester.completion_script
62 assert "get" in tester.completion_script
63 assert "set" in tester.completion_script
64
65
66 def test_negative_flag_completion(zsh_tester):
67 """Test negative flag completion."""
68 tester = zsh_tester(app_negative, "negapp")
69
70 assert "--no-verbose" in tester.completion_script
71 assert "--no-colors" in tester.completion_script
72
73
74 def test_disabled_negative_flag_completion(zsh_tester):
75 """Test that negative flags are not generated when disabled via App default_parameter."""
76 tester = zsh_tester(app_disabled_negative, "disabledneg")
77
78 assert "--param" in tester.completion_script
79 assert "--empty-param" not in tester.completion_script
80
81
82 def test_help_descriptions(zsh_tester):
83 """Test that help descriptions appear in completions."""
84 tester = zsh_tester(app_basic, "basic")
85
86 assert "Enable verbose output" in tester.completion_script
87 assert "Deploy to environment" in tester.completion_script
88
89
90 def test_script_syntax_valid(zsh_tester):
91 """Test that generated script has valid zsh syntax."""
92 tester = zsh_tester(app_basic, "basic")
93
94 assert tester.validate_script_syntax()
95
96
97 def test_compdef_header(zsh_tester):
98 """Test that script has proper #compdef header."""
99 tester = zsh_tester(app_basic, "basic")
100
101 assert tester.completion_script.startswith("#compdef basic")
102
103
104 def test_path_completion(zsh_tester):
105 """Test that Path types generate file completion."""
106 tester = zsh_tester(app_path, "pathapp")
107
108 assert "_files" in tester.completion_script
109
110
111 def test_optional_path_completion(zsh_tester):
112 """Test that Optional[Path] and Path | None generate file completion.
113
114 Value-bearing options carry a ``*`` prefix so the option can repeat
115 (required for collection-typed options like ``list[Path]``). The
116 option name has no ``=`` suffix by default β€” TAB-completion inserts
117 ``--opt`` plus a space rather than ``--opt=``. ``Parameter(requires_equals=True)``
118 flips this on and is exercised separately.
119 """
120 tester = zsh_tester(app_path, "pathapp")
121
122 assert "'*--output[Output file]:output:_files'" in tester.completion_script
123
124
125 def test_nested_command_uses_correct_word_index(zsh_tester):
126 """Test that nested commands use $words[1] for subcommand dispatch."""
127 tester = zsh_tester(app_nested, "nested")
128
129 script_lines = tester.completion_script.split("\n")
130 words_checks = [line for line in script_lines if "case $words[1] in" in line]
131
132 assert len(words_checks) >= 2, "Should have multiple case $words[1] checks for nested commands"
133
134
135 def test_invalid_prog_name():
136 """Test that invalid prog names raise ValueError."""
137 with pytest.raises(ValueError, match="Invalid prog_name"):
138 generate_completion_script(app_basic, "foo bar")
139
140 with pytest.raises(ValueError, match="Invalid prog_name"):
141 generate_completion_script(app_basic, "test;rm -rf /")
142
143 with pytest.raises(ValueError, match="Invalid prog_name"):
144 generate_completion_script(app_basic, "")
145
146
147 def test_description_escaping(zsh_tester):
148 """Test that descriptions with special chars are properly escaped.
149
150 Note: Backticks are now treated as markdown code syntax and stripped,
151 so they no longer appear in the completion script.
152 """
153 app = App(name="escape_test")
154
155 @app.default
156 def main(
157 param1: Annotated[str, Parameter(help="Test 'single' quotes")] = "",
158 param2: Annotated[str, Parameter(help='Test "double" quotes')] = "",
159 param3: Annotated[str, Parameter(help="Test $variable and `backticks`")] = "",
160 param4: Annotated[str, Parameter(help="Test [brackets] here")] = "",
161 ):
162 """Test app."""
163
164 tester = zsh_tester(app, "escape_test")
165
166 assert r"'\'' " in tester.completion_script or "'\\''" in tester.completion_script
167 assert "\\$" in tester.completion_script
168 # Backticks are now stripped as markdown code syntax
169 assert "backticks" in tester.completion_script
170 assert "\\`" not in tester.completion_script
171 assert r"\[" in tester.completion_script
172 assert r"\]" in tester.completion_script
173
174
175 def test_special_chars_in_literal_choices(zsh_tester):
176 """Test that Literal choices with special characters are properly escaped.
177
178 Choice-bearing specs are emitted with double-quoted outer strings (so a
179 literal ``'`` can be embedded) which means each backslash from the inner
180 choice-list-parser layer is doubled by the outer DQ layer. The runtime
181 behavior is verified separately in ``test_choice_with_*`` below.
182 """
183 app = App(name="special_choices")
184
185 @app.default
186 def main(
187 choice: Annotated[Literal["foo bar", "baz()", "test[1]", "back\\slash"], Parameter()] = "foo bar",
188 ):
189 """Test app with special chars in choices."""
190
191 tester = zsh_tester(app, "special_choices")
192
193 # After the two-layer escape ("" outer + choice-list parser): every
194 # backslash from layer 1 is doubled.
195 assert r"foo\\ bar" in tester.completion_script
196 assert r"baz\\(\\)" in tester.completion_script
197 assert r"test\\[1\\]" in tester.completion_script
198 # User-supplied backslash gets layer-1 ``\\\\`` then DQ-doubled to ``\\\\\\\\``
199 assert r"back\\\\slash" in tester.completion_script
200
201
202 def test_unicode_in_descriptions(zsh_tester):
203 """Test that Unicode characters in descriptions are handled properly."""
204 app = App(name="unicode_test")
205
206 @app.default
207 def main(
208 emoji: Annotated[str, Parameter(help="Enable πŸš€ rocket mode")] = "",
209 chinese: Annotated[str, Parameter(help="中文描述")] = "",
210 arabic: Annotated[str, Parameter(help="وءف Ψ¨Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©")] = "",
211 ):
212 """Test app with Unicode."""
213
214 tester = zsh_tester(app, "unicode_test")
215
216 assert "πŸš€" in tester.completion_script or "rocket mode" in tester.completion_script
217 assert tester.validate_script_syntax()
218
219
220 def test_deeply_nested_commands(zsh_tester):
221 """Test completion for deeply nested commands (3+ levels)."""
222 root = App(name="root")
223 level1 = App(name="level1")
224 level2 = App(name="level2")
225 level3 = App(name="level3")
226
227 @level3.command
228 def action(value: str):
229 """Perform action at level 3."""
230 pass
231
232 level2.command(level3)
233 level1.command(level2)
234 root.command(level1)
235
236 tester = zsh_tester(root, "root")
237
238 assert "level1" in tester.completion_script
239 assert "level2" in tester.completion_script
240 assert "level3" in tester.completion_script
241 assert "action" in tester.completion_script
242 assert tester.validate_script_syntax()
243
244
245 def test_no_trailing_colons_in_specs(zsh_tester):
246 """Test that argument specs don't have trailing colons when action is empty.
247
248 Regression test for issue where specs like '1:description:' or '*:args:'
249 would cause zsh eval errors. When there's no completion action, the spec
250 should be '1:description' or '*:args' (no trailing colon).
251 """
252 app = App(name="notrail")
253
254 @app.command
255 def run(
256 pos1: Annotated[str, Parameter(help="First positional")],
257 pos2: Annotated[int, Parameter(help="Second positional")],
258 *args: Annotated[str, Parameter(help="Variadic args")],
259 ):
260 """Command with positionals."""
261 pass
262
263 @app.default
264 def main(
265 flag: Annotated[str, Parameter(help="A non-path option")],
266 ):
267 """Main command."""
268 pass
269
270 tester = zsh_tester(app, "notrail")
271
272 # Check for problematic trailing colons (but not in file/directory actions)
273 for line in tester.completion_script.split("\n"):
274 stripped = line.strip()
275 # Skip comments and lines with valid actions
276 if stripped.startswith("#") or ":_files" in line or ":_directories" in line:
277 continue
278 # Check for trailing :' patterns (ignoring quote escaping)
279 if line.rstrip().endswith(":'") or line.rstrip().endswith(":' \\"):
280 if "'\\'':" not in line: # Not part of quote escaping in descriptions
281 raise AssertionError(f"Found trailing colon in spec: {line}")
282
283 assert tester.validate_script_syntax()
284
285
286 def test_colon_escaping_in_descriptions(zsh_tester):
287 """Test that colons in descriptions are escaped to prevent field separator issues.
288
289 Regression test for issue where colons in positional argument descriptions
290 like ':app_object' would be treated as field separators in specs like
291 '1:message:action', causing unmatched quote errors.
292 """
293 app = App(name="colontest")
294
295 @app.command
296 def run(
297 script: Annotated[str, Parameter(help="Path with ':app' notation")],
298 ):
299 """Command with colon in description."""
300 pass
301
302 tester = zsh_tester(app, "colontest")
303
304 assert r"\:" in tester.completion_script
305 assert tester.validate_script_syntax()
306
307
308 def test_run_command_only_special_for_cyclopts(zsh_tester):
309 """Test that 'run' command only gets dynamic completion for cyclopts CLI, not user apps.
310
311 Regression test for issue where any app with a 'run' command would get
312 dynamic completion instead of normal static completion.
313 """
314 app = App(name="myapp")
315
316 @app.command
317 def run(
318 script: Annotated[str, Parameter(help="Script to execute")],
319 verbose: Annotated[bool, Parameter(help="Verbose mode")] = False,
320 ):
321 """Run a script."""
322 pass
323
324 tester = zsh_tester(app, "myapp")
325
326 # Should generate normal static completion, not dynamic completion
327 # Dynamic completion has "local script_path", "local -a completions", etc.
328 assert "local script_path" not in tester.completion_script
329 assert "_complete run" not in tester.completion_script
330
331 # Should have normal argument specs for the run command
332 assert "--verbose" in tester.completion_script or "verbose" in tester.completion_script.lower()
333 assert tester.validate_script_syntax()
334
335
336 def test_cyclopts_run_command_has_dynamic_completion(zsh_tester):
337 """Test that cyclopts CLI's 'run' command gets dynamic completion."""
338 from cyclopts.cli import app as cyclopts_app
339
340 tester = zsh_tester(cyclopts_app, "cyclopts")
341
342 # Should have dynamic completion for the run command
343 assert "local script_path" in tester.completion_script
344 assert "_complete run" in tester.completion_script
345 assert tester.validate_script_syntax()
346
347
348 def test_empty_iterable_flag_completion(zsh_tester):
349 """Test that --empty-* flags for list parameters are treated as flags.
350
351 Regression test for issue where --empty-items on list[str] parameters
352 would expect a value instead of being treated as a flag.
353 """
354 app = App(name="listapp")
355
356 @app.command
357 def process(
358 items: Annotated[list[str], Parameter(help="Items to process")],
359 tags: Annotated[list[str] | None, Parameter(help="Optional tags")] = None,
360 count: Annotated[int, Parameter(help="Count")] = 1,
361 ):
362 """Process items."""
363 pass
364
365 tester = zsh_tester(app, "listapp")
366
367 # Both positive and negative flags should be present
368 assert "--items" in tester.completion_script
369 assert "--empty-items" in tester.completion_script
370 assert "--tags" in tester.completion_script
371 assert "--empty-tags" in tester.completion_script
372 assert "--count" in tester.completion_script
373
374 # Negative flags should be formatted as flags (no trailing :action)
375 # They should have the format '--empty-items[description]' not '--empty-items[description]:empty-items'
376 assert "'--empty-items[Items to process]'" in tester.completion_script
377 assert "'--empty-tags[Optional tags]'" in tester.completion_script
378
379 # Positive names should expect values (have :action or :name suffix).
380 # Match both the plain and ``*``-prefixed (repeatable) spec forms.
381 lines_with_items = [
382 line for line in tester.completion_script.split("\n") if "--items[" in line and "empty" not in line
383 ]
384 assert any(":items:" in line or ":items'" in line for line in lines_with_items), (
385 "Positive --items flag should expect a value"
386 )
387
388 assert tester.validate_script_syntax()
389
390
391 def test_positional_or_keyword_literal_completion(zsh_tester):
392 """Test that POSITIONAL_OR_KEYWORD Literal arguments generate positional completion.
393
394 Regression test for issue where 'cyclopts-demo deploy d<TAB>' should complete
395 to 'dev' but no completions were shown. The environment parameter is
396 POSITIONAL_OR_KEYWORD (not positional-only) and has Literal choices.
397 """
398 from typing import Literal
399
400 app = App(name="testapp")
401
402 @app.command
403 def deploy(
404 environment: Literal["dev", "staging", "production"],
405 region: Literal["us-east-1", "us-west-2"] = "us-east-1",
406 ):
407 """Deploy to environment.
408
409 Parameters
410 ----------
411 environment : Literal["dev", "staging", "production"]
412 Target environment.
413 region : Literal["us-east-1", "us-west-2"]
414 AWS region.
415 """
416 pass
417
418 tester = zsh_tester(app, "testapp")
419
420 # In nested context, positionals are now included as specs in _arguments
421 # Positions are '1:' and '2:' (not '2:' and '3:') because after *::arg:->args,
422 # $words[1] is the subcommand and positionals start at position 1.
423 # Choice-bearing specs use double-quoted outer to allow embedding ``'``.
424 assert '"1:Target environment.:(dev staging production)"' in tester.completion_script
425 assert '"2:AWS region.:(us-east-1 us-west-2)"' in tester.completion_script
426
427 # Should have choices for both positionals
428 assert "dev" in tester.completion_script
429 assert "staging" in tester.completion_script
430 assert "production" in tester.completion_script
431 assert "us-east-1" in tester.completion_script
432 assert "us-west-2" in tester.completion_script
433
434 # Should also have keyword spec for --environment
435 assert "--environment" in tester.completion_script
436
437 assert tester.validate_script_syntax()
438
439
440 def test_help_version_flags_in_subcommands(zsh_tester):
441 """Test that help and version flags appear in subcommand completions.
442
443 Regression test for issue where --help and --version were only available
444 in the root command but not in subcommands.
445 """
446 tester = zsh_tester(app_basic, "basic")
447
448 script_lines = tester.completion_script.split("\n")
449
450 # Walk from the deploy case label to its closing ``;;``. Track
451 # nested ``case ... in / esac`` so the eq-form pre-pass's inner
452 # ``;;`` markers don't terminate the scan early.
453 in_deploy = False
454 case_depth = 0
455 deploy_section = []
456 for line in script_lines:
457 if "deploy)" in line and not in_deploy:
458 in_deploy = True
459 if in_deploy:
460 deploy_section.append(line)
461 if re.search(r"\bcase\b.*\bin\b", line):
462 case_depth += 1
463 elif re.search(r"\besac\b", line):
464 case_depth -= 1
465 elif ";;" in line and case_depth == 0:
466 break
467
468 deploy_text = "\n".join(deploy_section)
469
470 assert "--help[Display this message and exit.]" in deploy_text
471 assert "-h[Display this message and exit.]" in deploy_text
472 assert "--version[Display application version.]" in deploy_text
473
474
475 def test_nested_command_disambiguation(zsh_tester):
476 """Test that nested commands are properly disambiguated.
477
478 This test verifies that the helper function correctly distinguishes between
479 commands with overlapping names (e.g., 'config get' vs 'admin get').
480 """
481 root = App(name="myapp")
482
483 config = App(name="config")
484 admin = App(name="admin")
485
486 @config.command(name="get")
487 def config_get(key: Annotated[str, Parameter(help="Config key")] = ""):
488 """Get config value."""
489 pass
490
491 @config.command(name="set")
492 def config_set(key: str = "", value: str = ""):
493 """Set config value."""
494 pass
495
496 @admin.command(name="get")
497 def admin_get(user: Annotated[str, Parameter(help="Username")] = ""):
498 """Get admin user."""
499 pass
500
501 root.command(config)
502 root.command(admin)
503
504 tester = zsh_tester(root, "myapp")
505
506 script = tester.completion_script
507
508 config_lines = [line for line in script.split("\n") if "config" in line.lower()]
509 admin_lines = [line for line in script.split("\n") if "admin" in line.lower()]
510
511 assert any("config" in line for line in config_lines), "Should have config-specific completions"
512 assert any("admin" in line for line in admin_lines), "Should have admin-specific completions"
513
514 assert tester.validate_script_syntax()
515
516
517 def test_helper_function_generation(zsh_tester):
518 """Test that command path detection logic is generated when needed."""
519 root_only = App(name="rootonly")
520
521 @root_only.default
522 def main(verbose: bool = False):
523 """Root only app."""
524 pass
525
526 tester_root = zsh_tester(root_only, "rootonly")
527 script_root = tester_root.completion_script
528
529 nested = App(name="nested")
530 sub = App(name="sub")
531
532 @sub.default
533 def action():
534 """Sub action."""
535 pass
536
537 nested.command(sub)
538
539 tester_nested = zsh_tester(nested, "nested")
540 script_nested = tester_nested.completion_script
541
542 assert len(script_nested) > len(script_root), "Nested app should have more complex completion logic"
543
544
545 def test_no_file_completion_for_strings(zsh_tester):
546 """Test that string options don't default to file completion."""
547 app = App(name="strtest")
548
549 @app.default
550 def main(
551 name: Annotated[str, Parameter(help="Name")] = "default",
552 ):
553 """Test app."""
554
555 tester = zsh_tester(app, "strtest")
556 assert tester.validate_script_syntax()
557
558
559 def test_helper_function_skips_option_values(zsh_tester):
560 """Test that helper function correctly identifies and skips option values.
561
562 Critical bug fix test: ensures that when building command path,
563 the helper function skips values for options that take arguments.
564 Without this, 'myapp --config file.yaml subcommand' would incorrectly
565 extract [file.yaml, subcommand] instead of [subcommand].
566 """
567 app = App(name="myapp")
568 sub = App(name="sub")
569
570 @sub.default
571 def action():
572 """Subcommand action."""
573 pass
574
575 @app.default
576 def main(
577 config: Annotated[str, Parameter(help="Config file path")],
578 verbose: bool = False,
579 ):
580 """Main app."""
581 pass
582
583 app.command(sub)
584
585 tester = zsh_tester(app, "myapp")
586 script = tester.completion_script
587
588 assert "--config" in script or "config" in script
589 assert tester.validate_script_syntax()
590
591
592 def test_markdown_markup_stripped_from_descriptions(zsh_tester):
593 """Test that markdown markup is stripped from help descriptions.
594
595 Ensures that **bold**, *italic*, `code`, and other markdown syntax
596 is properly removed from completion descriptions.
597 """
598 tester = zsh_tester(app_markup, "markupapp")
599 script = tester.completion_script
600
601 assert "Enable verbose output with extra details" in script, "Should contain plain text version"
602 assert "**verbose**" not in script, "Should not contain markdown bold syntax"
603 assert "`extra`" not in script, "Should not contain markdown code syntax"
604
605 # Note: zsh escapes colons with backslashes in descriptions
606 assert "Choose execution mode" in script and "fast or slow" in script, "Should contain plain text version"
607 assert "*execution*" not in script, "Should not contain markdown italic syntax"
608 assert "**fast**" not in script, "Should not contain markdown bold in mode description"
609 assert "**slow**" not in script, "Should not contain markdown bold in mode description"
610
611 assert "Target environment like dev or prod" in script, "Should contain plain text version"
612 assert "`environment`" not in script, "Should not contain markdown code in env description"
613 assert "**dev**" not in script, "Should not contain markdown bold in env description"
614 assert "**prod**" not in script, "Should not contain markdown bold in env description"
615
616 assert "Deploy to environment" in script, "Should contain plain text command description"
617
618 assert tester.validate_script_syntax()
619
620
621 def test_rst_markup_stripped_from_descriptions(zsh_tester):
622 """Test that RST markup is stripped from help descriptions.
623
624 Ensures that **bold**, ``code``, and other RST syntax
625 is properly removed from completion descriptions.
626 """
627 tester = zsh_tester(app_rst, "rstapp")
628 script = tester.completion_script
629
630 assert "Enable verbose output with code samples" in script, "Should contain plain text version"
631 assert "**verbose**" not in script, "Should not contain RST bold syntax"
632 assert "``code``" not in script, "Should not contain RST code syntax (double backticks)"
633
634 assert "Choose execution mode" in script and "fast or slow" in script, "Should contain plain text version"
635 assert "*execution*" not in script, "Should not contain RST italic syntax"
636 assert "**fast**" not in script, "Should not contain RST bold in mode description"
637 assert "**slow**" not in script, "Should not contain RST bold in mode description"
638
639 assert tester.validate_script_syntax()
640
641
642 def test_no_direct_function_call(zsh_tester):
643 """Test that completion script doesn't call the completion function directly.
644
645 Regression test for issue where the script ended with '_progname "$@"' which
646 caused "_arguments:comparguments:327: can only be called from completion function"
647 error when the completion file was sourced during shell startup.
648
649 The #compdef directive is sufficient to register the completion function;
650 a direct call is unnecessary and causes errors since _arguments can only be
651 called within a completion context.
652 """
653 tester = zsh_tester(app_basic, "basic")
654 script = tester.completion_script
655
656 # Should not have a direct call to the completion function
657 assert '_basic "$@"' not in script, "Should not directly call the completion function"
658
659 # Script should end with the closing brace (no compdef needed - #compdef directive suffices)
660 lines = script.rstrip().split("\n")
661 assert lines[-1] == "}", "Script should end with closing brace"
662
663 # Should have the #compdef directive for autoload compatibility
664 assert script.startswith("#compdef basic"), "Should have #compdef directive"
665
666 assert tester.validate_script_syntax()
667
668
669 def test_literal_with_show_choices_false(zsh_tester):
670 """Test that Literal with show_choices=False still provides completions.
671
672 Regression test: When show_choices=False is set on a Literal parameter,
673 the choices should still be available for shell completion, even though
674 they are hidden from the help text.
675 """
676 app = App(name="deploy")
677
678 @app.default
679 def main(
680 env: Annotated[
681 Literal["dev", "staging", "prod"],
682 Parameter(help="Environment to deploy to", show_choices=False),
683 ],
684 ):
685 """Deploy to environment."""
686 pass
687
688 tester = zsh_tester(app, "deploy")
689 script = tester.completion_script
690
691 # Choices should be in completion script even with show_choices=False
692 assert "dev" in script
693 assert "staging" in script
694 assert "prod" in script
695
696
697 def test_command_with_multiple_names_and_aliases(zsh_tester):
698 """Test that commands registered with multiple names/aliases all appear in completions.
699
700 Regression test for groups_from_app() deduplication - ensures all registered
701 names are included in completion scripts.
702 """
703 app = App(name="myapp")
704 sub = App()
705
706 @sub.default
707 def action(value: str = ""):
708 """Perform an action."""
709 pass
710
711 app.command(sub, name="foo", alias=["bar", "baz"])
712
713 tester = zsh_tester(app, "myapp")
714 script = tester.completion_script
715
716 assert "foo" in script, "Primary name should be in completion script"
717 assert "bar" in script, "First alias should be in completion script"
718 assert "baz" in script, "Second alias should be in completion script"
719
720 assert tester.validate_script_syntax()
721
722
723 def test_nested_variadic_positional_completion(zsh_tester):
724 """Test that variadic positionals work in nested command contexts.
725
726 Variadic positionals (*args) should accept completion at multiple positions.
727 """
728 app = App(name="testapp")
729
730 @app.command
731 def process(
732 *files: Annotated[Path, Parameter(help="Files to process")],
733 ):
734 """Process multiple files.
735
736 Parameters
737 ----------
738 files : Path
739 Files to process.
740 """
741 pass
742
743 tester = zsh_tester(app, "testapp")
744 script = tester.completion_script
745
746 # Should use _files completion for Path positionals
747 assert "_files" in script, "Path positionals should use _files completion"
748
749 # For variadic, should have '*:desc:_files' spec
750 assert "'*:" in script, "Variadic positionals should use * spec"
751
752 assert tester.validate_script_syntax()
753
754
755 def test_list_path_completion(zsh_tester):
756 """Test that list[Path] arguments generate file completion.
757
758 Regression test for issue #654: list[Path] arguments should use
759 file completion (_files) just like Path arguments.
760 """
761 tester = zsh_tester(app_list_path, "listpath")
762 script = tester.completion_script
763
764 assert "_files" in script, "list[Path] should generate file completion"
765 assert tester.validate_script_syntax()
766
767
768 def test_list_path_positional_variadic(zsh_tester):
769 """Test that list[Path] positional generates variadic '*' spec, not just '1:'.
770
771 A list parameter that can consume multiple positional values should offer
772 file completion for ALL positions, not just the first.
773 """
774 tester = zsh_tester(app_list_path, "listpath")
775 script = tester.completion_script
776
777 assert "'*:" in script, "list[Path] positional should use variadic '*' spec for all positions"
778 assert "_files" in script
779 assert tester.validate_script_syntax()
780
781
782 def test_list_annotated_path_completion(zsh_tester):
783 """Test that list[Annotated[Path, ...]] arguments generate file completion.
784
785 When a type like ExistingFile (Annotated[Path, Parameter(...)]) is used
786 inside a collection like list[], the Annotated wrapper must be unwrapped
787 to detect the underlying Path type for completion.
788 """
789 tester = zsh_tester(app_list_annotated_path, "listannotatedpath")
790 script = tester.completion_script
791
792 assert "_files" in script, "list[ExistingFile] should generate file completion"
793 assert tester.validate_script_syntax()
794
795
796 def test_colon_in_command_name(zsh_tester):
797 """Test that colons in command names are properly escaped.
798
799 Regression test for issue #715: Command names containing colons like
800 'utility:ping' should have the colon escaped in zsh completion scripts
801 so that the full name is displayed, not just the part before the colon.
802
803 Colons need escaping both in _describe format and in case patterns because
804 zsh's completion system treats them specially when populating the $words array.
805 """
806 app = App(name="myapp")
807
808 sub = App()
809
810 @sub.default
811 def action(value: str = ""):
812 """Perform an action."""
813 pass
814
815 # Register command with colon in name
816 app.command(sub, name="utility:ping")
817
818 tester = zsh_tester(app, "myapp")
819 script = tester.completion_script
820
821 # The colon should be escaped in the _describe format
822 # 'utility\:ping:description' instead of 'utility:ping:description'
823 assert r"utility\:ping" in script, "Colon in command name should be escaped"
824
825 # The case pattern should also have the colon escaped for proper $words matching
826 assert r"utility\:ping)" in script, "Colon should be escaped in case pattern for $words matching"
827
828 assert tester.validate_script_syntax()
829
830
831 def test_special_chars_in_command_name(zsh_tester):
832 """Test that special characters in command names are properly escaped.
833
834 Tests escaping for various special characters that could appear in command names
835 and cause issues in zsh completion scripts.
836 """
837 app = App(name="myapp")
838
839 sub1 = App()
840
841 @sub1.default
842 def action1():
843 """Action with brackets."""
844 pass
845
846 # Register command with brackets in name (unusual but possible)
847 app.command(sub1, name="test[1]")
848
849 tester = zsh_tester(app, "myapp")
850 script = tester.completion_script
851
852 # Brackets should be escaped in the _describe format
853 assert r"test\[1\]" in script, "Brackets in command name should be escaped"
854
855 # In case patterns, brackets should also be escaped
856 assert r"test\[1\])" in script, "Brackets in case pattern should be escaped"
857
858 assert tester.validate_script_syntax()
859
860
861 def test_positional_without_help_uses_name_fallback(zsh_tester):
862 """Test that positional arguments without help text use parameter name as description.
863
864 Regression test: zsh _arguments requires non-empty descriptions for positional
865 specs to provide completions. When a parameter has no help text, the completion
866 script should fall back to using the parameter name as the description.
867
868 Without this fallback, '1::(choices)' is generated which silently breaks
869 completion, while '1:param_name:(choices)' works correctly.
870 """
871 app = App(name="testapp")
872
873 @app.command
874 def action(
875 choice: Literal["foo", "bar"], # No Parameter() annotation, no help text
876 /,
877 ):
878 """Do something."""
879 pass
880
881 tester = zsh_tester(app, "testapp")
882 script = tester.completion_script
883
884 # Should NOT have empty description '1::(foo bar)' or "1::(foo bar)"
885 assert "'1::(foo bar)'" not in script, "Should not have empty description in positional spec"
886 assert '"1::(foo bar)"' not in script, "Should not have empty description in positional spec"
887
888 # Should have parameter name as fallback. Choice-bearing specs use
889 # double-quoted outer; the format is `"1:description:(choices)"`.
890 positional_spec = re.search(r'"1:([^:]+):\(foo bar\)"', script)
891 assert positional_spec is not None, "Should have positional spec with choices"
892 description = positional_spec.group(1)
893 assert description, "Description should not be empty"
894 assert len(description) > 0, "Description should have content"
895
896 assert tester.validate_script_syntax()
897
898
899 # --- Choice values containing whitespace / shell metacharacters --------------
900 #
901 # End-to-end regression tests for tricky choice values surviving zsh's
902 # completion machinery. zsh's ``_arguments`` puts choices through *two*
903 # parsers: the outer shell quoting and the inner choice-list parser. The
904 # generator now uses double-quoted outer specs so a literal ``'`` can be
905 # embedded as ``\'``. Without that, ``Literal["a'b"]`` produced ``(eval):1:
906 # unmatched '`` at completion time.
907
908
909 def test_choice_with_whitespace(zsh_tester):
910 """A choice value containing a space stays a single completion."""
911 app = App(name="ws")
912
913 @app.default
914 def m(x: Literal["hello world", "normal"] = "normal", /):
915 """Whitespace in choice."""
916
917 tester = zsh_tester(app, "ws")
918 assert tester.validate_script_syntax()
919 completions = tester.get_completions("ws ")
920 assert "hello world" in completions
921 assert "hello" not in completions
922 assert "world" not in completions
923
924
925 def test_choice_with_single_quote(zsh_tester):
926 r"""A choice value containing a single quote does not break the script.
927
928 Regression test: previously ``Literal["a'b"]`` produced
929 ``'1:X:(... a'\\''b)'``. After the outer single-quote-end-restart
930 trick, ``_arguments``' choice-list parser saw an unbalanced ``'`` and
931 failed with ``(eval):1: unmatched '``.
932 """
933 app = App(name="sq")
934
935 @app.default
936 def m(x: Literal["a'b", "normal"] = "normal", /):
937 """Single quote in choice."""
938
939 tester = zsh_tester(app, "sq")
940 assert tester.validate_script_syntax()
941 completions = tester.get_completions("sq ")
942 assert "a'b" in completions
943 assert not any("unmatched" in c for c in completions)
944
945
946 def test_choice_with_backtick(zsh_tester):
947 """A choice value containing a backtick does not break the script."""
948 app = App(name="btk")
949
950 @app.default
951 def m(x: Literal["a`b", "normal"] = "normal", /):
952 """Backtick in choice."""
953
954 tester = zsh_tester(app, "btk")
955 assert tester.validate_script_syntax()
956 completions = tester.get_completions("btk ")
957 assert "a`b" in completions
958
959
960 def test_choice_with_dollar(zsh_tester):
961 """A choice value containing $ is not parameter-expanded."""
962 app = App(name="dol")
963
964 @app.default
965 def m(x: Literal["$home", "normal"] = "normal", /):
966 """Dollar in choice."""
967
968 tester = zsh_tester(app, "dol")
969 assert tester.validate_script_syntax()
970 completions = tester.get_completions("dol ")
971 assert "$home" in completions
972
973
974 def test_choice_value_after_keyword_option(zsh_tester):
975 """Tricky choices also survive the ``--opt <choice>`` value-completion path."""
976 app = App(name="optchoice")
977
978 @app.default
979 def m(env: Annotated[Literal["a b", "c'd", "e`f"], Parameter(help="env")] = "a b"):
980 """Tricky choices behind a keyword option."""
981
982 tester = zsh_tester(app, "optchoice")
983 assert tester.validate_script_syntax()
984 completions = tester.get_completions("optchoice --env ")
985 assert {"a b", "c'd", "e`f"} <= set(completions)
986
987
988 # --- --opt=value form: gated on Parameter.requires_equals ------------------
989 #
990 # The ``=`` suffix on a zsh ``_arguments`` option spec is load-bearing in
991 # two ways at once: it enables ``--opt=value`` value-completion AND it
992 # changes the *name* TAB-insert from ``--opt `` (trailing space) to
993 # ``--opt=`` (no space). zsh has no native syntax that decouples these.
994 #
995 # Because forced ``=`` insertion surprises most users and the space form
996 # is the more common across CLIs, the default (``requires_equals=False``)
997 # emits the plain spec β€” at the cost of ``--opt=value<TAB>``
998 # value-completion silently doing nothing. ``requires_equals=True`` opts
999 # back into the eq spec so completion mirrors what the parser accepts.
1000 #
1001 # Bash is unaffected by this trade-off β€” its eq-form completion goes
1002 # through ``_value_prev`` hopping over ``=`` and works regardless.
1003
1004
1005 def test_default_no_eq_in_spec_name(zsh_tester):
1006 """Default: no ``=`` suffix on the option name in the spec.
1007
1008 The ``--env`` option has Literal choices, so its spec uses a
1009 double-quoted outer string. The assertion checks for the ``=``-less
1010 form regardless of which quote style wraps the spec.
1011 """
1012 tester = zsh_tester(app_basic, "basic")
1013 script = tester.completion_script
1014 # Plain spec β€” TAB on the name will insert ``--env`` plus a space.
1015 assert '"*--env[' in script or "'*--env[" in script
1016 assert '"*--env=[' not in script
1017 assert "'*--env=[" not in script
1018
1019
1020 def test_default_space_form_value_completion(zsh_tester):
1021 """The space form must offer value completion regardless of ``requires_equals``."""
1022 tester = zsh_tester(app_basic, "basic")
1023 completions = tester.get_completions("basic deploy --env ")
1024 assert {"dev", "staging", "prod"} <= set(completions)
1025
1026
1027 def test_default_eq_form_value_completion_via_prepass(zsh_tester):
1028 """``--opt=value<TAB>`` works in the default case via the compset pre-pass.
1029
1030 Even with the plain (no-``=``) ``_arguments`` spec, a user who
1031 explicitly types ``--env=`` should still see value completions: the
1032 pre-pass intercepts the pattern, strips the ``--env=`` prefix, and
1033 dispatches to the choice list.
1034 """
1035 tester = zsh_tester(app_basic, "basic")
1036 completions = tester.get_completions("basic deploy --env=")
1037 assert {"dev", "staging", "prod"} <= set(completions)
1038
1039
1040 def test_default_eq_form_value_completion_partial(zsh_tester):
1041 """``--opt=d<TAB>`` narrows via the pre-pass."""
1042 tester = zsh_tester(app_basic, "basic")
1043 completions = tester.get_completions("basic deploy --env=d")
1044 assert "dev" in completions
1045 assert "staging" not in completions
1046 assert "prod" not in completions
1047
1048
1049 def test_default_eq_form_path_completion_via_prepass(zsh_tester):
1050 """Path-typed options also dispatch to ``_files`` from the pre-pass."""
1051 import os
1052 import tempfile
1053 from pathlib import Path as _Path
1054
1055 app = App(name="ekw")
1056
1057 @app.default
1058 def m(input_file: Annotated[_Path, Parameter(help="In")] = _Path()):
1059 """Path keyword."""
1060
1061 tester = zsh_tester(app, "ekw")
1062 with tempfile.TemporaryDirectory() as td:
1063 (_Path(td) / "sample.txt").write_text("x")
1064 cwd = _Path.cwd()
1065 try:
1066 os.chdir(td)
1067 completions = tester.get_completions("ekw --input-file=")
1068 finally:
1069 os.chdir(cwd)
1070 assert completions, f"expected file completion via pre-pass, got {completions!r}"
1071
1072
1073 def test_eq_form_prepass_compadd_no_stray_backslashes(zsh_tester):
1074 r"""Eq-form prepass ``compadd`` args must be POSIX-safe single-quoted.
1075
1076 Reproduces the Copilot review finding: choices are passed through
1077 ``_escape_completion_choice`` (which inserts ``\\`` escapes designed for
1078 ``_describe``'s inner parser) and then wrapped in *single quotes* for
1079 ``compadd``. Inside single quotes, backslashes are literal β€” so a choice
1080 like ``"foo bar"`` ends up as ``'foo\\ bar'`` and the user sees a
1081 completion containing a stray backslash. The fix is proper single-quote
1082 escaping (only ``'`` needs handling, via the ``'\\''`` end/restart trick).
1083 """
1084 app = App(name="eqp")
1085
1086 @app.default
1087 def m(env: Annotated[Literal["foo bar", "baz qux"], Parameter(help="E")] = "foo bar"):
1088 """Eq-form choices with spaces."""
1089
1090 tester = zsh_tester(app, "eqp")
1091 script = tester.completion_script
1092
1093 # Locate the prepass case branch for ``--env`` and the inner ``compadd`` line.
1094 lines = script.splitlines()
1095 in_env_case = False
1096 compadd_line = None
1097 for line in lines:
1098 stripped = line.strip()
1099 if stripped == "--env=*)":
1100 in_env_case = True
1101 continue
1102 if in_env_case:
1103 if stripped.startswith("compadd "):
1104 compadd_line = stripped
1105 break
1106 if stripped == ";;":
1107 break
1108
1109 assert compadd_line is not None, "no ``compadd`` line found in --env=*) prepass branch"
1110
1111 # Single-quoted compadd args must not contain literal backslash-escape
1112 # sequences β€” those would render as visible backslashes in the user's
1113 # completion menu.
1114 assert "\\ " not in compadd_line, (
1115 f"single-quoted compadd args contain literal '\\ ' (backslash-space): {compadd_line!r}"
1116 )
1117
1118
1119 def test_requires_equals_emits_eq_spec(zsh_tester):
1120 """``Parameter(requires_equals=True)`` opts back into the eq spec."""
1121 app = App(name="rqeq")
1122
1123 @app.default
1124 def m(env: Annotated[Literal["dev", "prod"], Parameter(requires_equals=True)] = "dev"):
1125 """Eq-required."""
1126
1127 tester = zsh_tester(app, "rqeq")
1128 script = tester.completion_script
1129 assert "*--env=[" in script
1130 # The pre-pass should NOT include this option β€” its eq-form is already
1131 # handled by the spec.
1132 assert "--env=*)" not in script
1133
1134
1135 def test_requires_equals_eq_form_value_completion(zsh_tester):
1136 """``--opt=<TAB>`` value completion works when ``requires_equals=True``."""
1137 app = App(name="rqeq")
1138
1139 @app.default
1140 def m(env: Annotated[Literal["dev", "prod"], Parameter(requires_equals=True)] = "dev"):
1141 """Eq-required."""
1142
1143 tester = zsh_tester(app, "rqeq")
1144 completions = tester.get_completions("rqeq --env=")
1145 assert {"dev", "prod"} <= set(completions)
1146
1147
1148 # --- Repeatable value-options ----------------------------------------------
1149 #
1150 # zsh's ``_arguments`` defaults each spec to single-use, so once an option
1151 # has been consumed it disappears from suggestions and its value can't be
1152 # completed again. Cyclopts now prefixes value-bearing specs with ``*`` so
1153 # the option may repeat β€” required for collection-typed options
1154 # (``list[X]``) and matches bash's behavior. Bool flags stay non-repeating.
1155
1156
1157 def test_value_option_repeatable_space_form(zsh_tester):
1158 """``--env dev --env<TAB>`` should still offer choices."""
1159 tester = zsh_tester(app_basic, "basic")
1160 completions = tester.get_completions("basic deploy --env dev --env ")
1161 assert {"dev", "staging", "prod"} <= set(completions)
1162
1163
1164 def test_collection_option_repeats(zsh_tester):
1165 """A ``list[Path]`` keyword option must accept repeated ``--file``.
1166
1167 Without ``*`` prefix on the spec, zsh would refuse to complete a second
1168 ``--file`` value, breaking the natural ``--file a --file b --file c``
1169 usage of collection-typed parameters.
1170
1171 Doubles as a regression test for issue #821: prog_name ``files`` happens
1172 to match zsh's built-in ``_files`` completion helper, so the generated
1173 autoload entry must be namespaced (e.g. ``_cyclopts_files``) β€” otherwise
1174 ``_arguments``'s ``:file:_files`` action recurses into our own function
1175 and zsh hits its recursion limit (visible on macOS as a captured error
1176 string, fatal pty EOF on aarch64 Linux/Nix).
1177 """
1178 import os
1179 import tempfile
1180 from pathlib import Path as _Path
1181
1182 app = App(name="files")
1183
1184 @app.default
1185 def m(file: Annotated[list[_Path], Parameter(help="files")] = []): # noqa: B006
1186 """Files."""
1187
1188 tester = zsh_tester(app, "files")
1189 with tempfile.TemporaryDirectory() as td:
1190 (_Path(td) / "first.txt").write_text("x")
1191 cwd = _Path.cwd()
1192 try:
1193 os.chdir(td)
1194 completions = tester.get_completions("files --file first.txt --file ")
1195 finally:
1196 os.chdir(cwd)
1197 # Assert the actual file appears β€” not just *some* output. Without a
1198 # tight assertion zsh's "recursion limit exceeded" error gets scraped
1199 # as a "completion" and the test silently passes.
1200 assert "first.txt" in completions, f"expected 'first.txt' in file completion on second --file, got {completions!r}"
1201
1202
1203 def test_multiple_iterable_positionals_emit_one_rest_spec(zsh_tester):
1204 """Functions with multiple ``list[X]`` positional-or-keyword params.
1205
1206 Regression test for ``_arguments:comparguments:327: doubled rest argument
1207 definition``: zsh allows at most one ``*:`` rest spec per command, but
1208 each iterable-typed positional was emitting one. Cyclopts now collapses
1209 them to a single rest spec (the first iterable, or the ``*args``
1210 var-positional if present); the others remain available via their
1211 ``--name`` keyword forms.
1212 """
1213 app = App(name="multi_iter")
1214
1215 @app.command
1216 def process(
1217 items: list[str],
1218 tags: list[str] | None = None,
1219 exclude: list[str] | None = None,
1220 ):
1221 """Process items.
1222
1223 Parameters
1224 ----------
1225 items
1226 Items to process.
1227 tags
1228 Tags to apply.
1229 exclude
1230 Items to exclude.
1231 """
1232
1233 tester = zsh_tester(app, "multi_iter")
1234 script = tester.completion_script
1235
1236 assert tester.validate_script_syntax()
1237
1238 # Exactly one rest-arg spec inside the process block.
1239 process_block = re.search(r"process\)(.*?);;", script, re.DOTALL)
1240 assert process_block is not None
1241 rest_specs = re.findall(r"'\*:[^']*'|\"\*:[^\"]*\"", process_block.group(1))
1242 assert len(rest_specs) == 1, f"expected one rest spec, found {rest_specs!r}"
1243
1244 # The collapsed-out positionals are still available as keyword options.
1245 assert "--tags[" in script
1246 assert "--exclude[" in script
1247
1248 # Real zsh accepts the script and offers ``--tags`` after ``--ta``.
1249 completions = tester.get_completions("multi_iter process --ta")
1250 assert "--tags" in completions
1251
1252
1253 def test_bool_flag_not_repeated(zsh_tester):
1254 """Bool flags stay single-use in zsh (matches zsh convention)."""
1255 tester = zsh_tester(app_basic, "basic")
1256 script = tester.completion_script
1257 # No ``*`` prefix on the verbose spec.
1258 assert "'--verbose[" in script
1259 assert "'*--verbose[" not in script
1260
1261
1262 # --- Naked-TAB at no-arg subcommand: known per-shell divergence -------------
1263 #
1264 # See the doc note at the top of test_behavior.py. zsh's ``_arguments``
1265 # always lists ``--help`` / ``--version`` whether or not the user has
1266 # typed a leading ``-``; bash gates them behind ``cur == -*``. The current
1267 # behavior is intentional and locked in here.
1268
1269
1270 def test_naked_tab_at_no_arg_subcommand_offers_help(zsh_tester):
1271 """Zsh always surfaces ``--help`` / ``--version`` via ``_arguments``."""
1272 app = App(name="probe")
1273
1274 @app.command
1275 def noarg():
1276 """No-arg subcommand."""
1277
1278 tester = zsh_tester(app, "probe")
1279 completions = tester.get_completions("probe noarg ")
1280 assert "--help" in completions
1281 assert "--version" in completions