Debian Codegraph @

tests/completion/test_fish.py

raw symbols SCIP
1 """Tests for fish completion script generation."""
2
3 from typing import Annotated, Literal
4
5 import pytest
6
7 from cyclopts import App, Parameter
8 from cyclopts.completion.fish import generate_completion_script
9
10 from .apps import (
11 app_basic,
12 app_disabled_negative,
13 app_enum,
14 app_list_path,
15 app_markup,
16 app_negative,
17 app_nested,
18 app_path,
19 app_rst,
20 )
21
22
23 def test_generate_completion_script_invalid_prog_name():
24 """Test that invalid prog_name raises ValueError."""
25 with pytest.raises(ValueError, match="Invalid prog_name"):
26 generate_completion_script(app_basic, "invalid prog")
27
28 with pytest.raises(ValueError, match="Invalid prog_name"):
29 generate_completion_script(app_basic, "")
30
31 with pytest.raises(ValueError, match="Invalid prog_name"):
32 generate_completion_script(app_basic, "prog$name")
33
34
35 def test_generate_completion_script_creates_script():
36 """Test that fish completion generates a script."""
37 script = generate_completion_script(app_basic, "basic")
38 assert script
39 assert "# Fish completion for basic" in script
40 assert "complete -c basic" in script
41
42
43 def test_basic_option_completion(fish_tester):
44 """Test basic option name completion."""
45 tester = fish_tester(app_basic, "basic")
46
47 assert "--verbose" in tester.completion_script or "-l verbose" in tester.completion_script
48 assert "--count" in tester.completion_script or "-l count" in tester.completion_script
49 assert "--help" in tester.completion_script or "-l help" in tester.completion_script
50
51
52 def test_command_completion(fish_tester):
53 """Test command completion."""
54 tester = fish_tester(app_basic, "basic")
55
56 assert "deploy" in tester.completion_script
57
58
59 def test_literal_value_completion(fish_tester):
60 """Test Literal type value completion."""
61 tester = fish_tester(app_basic, "basic")
62
63 assert "dev" in tester.completion_script
64 assert "staging" in tester.completion_script
65 assert "prod" in tester.completion_script
66
67
68 def test_enum_value_completion(fish_tester):
69 """Test Enum type value completion."""
70 tester = fish_tester(app_enum, "enumapp")
71
72 assert "fast" in tester.completion_script
73 assert "slow" in tester.completion_script
74
75
76 def test_nested_subcommand_completion(fish_tester):
77 """Test nested subcommand completion."""
78 tester = fish_tester(app_nested, "nested")
79
80 assert "config" in tester.completion_script
81 assert "get" in tester.completion_script
82 assert "set" in tester.completion_script
83
84
85 def test_path_completion_action(fish_tester):
86 """Test that Path types trigger file completion."""
87 tester = fish_tester(app_path, "pathapp")
88
89 assert tester.validate_script_syntax()
90 assert "-F" in tester.completion_script or "__fish_complete_directories" in tester.completion_script
91
92
93 def test_negative_flag_completion(fish_tester):
94 """Test negative flag handling."""
95 tester = fish_tester(app_negative, "negapp")
96
97 script = tester.completion_script
98 assert "--verbose" in script or "-l verbose" in script
99 assert "--no-verbose" in script or "-l no-verbose" in script
100 assert "--colors" in script or "-l colors" in script
101 assert "--no-colors" in script or "-l no-colors" in script
102
103
104 def test_disabled_negative_flag_completion(fish_tester):
105 """Test that negative flags are not generated when disabled via App default_parameter."""
106 tester = fish_tester(app_disabled_negative, "disabledneg")
107
108 script = tester.completion_script
109 assert "--param" in script or "-l param" in script
110 assert "--empty-param" not in script
111 assert "-l empty-param" not in script
112
113
114 def test_script_syntax_validation(fish_tester):
115 """Test that generated script has valid fish syntax."""
116 tester = fish_tester(app_basic, "basic")
117
118 assert tester.validate_script_syntax()
119
120
121 def test_completion_command_format(fish_tester):
122 """Test that completion uses correct fish command format."""
123 tester = fish_tester(app_basic, "myapp")
124
125 assert "complete -c myapp" in tester.completion_script
126
127
128 def test_special_characters_in_choices(fish_tester):
129 """Test that special characters in choices are properly escaped."""
130 app = App(name="special")
131
132 @app.default
133 def main(
134 value: Annotated[
135 Literal["normal", "with space", "with'quote", "with$dollar"],
136 Parameter(help="Test value"),
137 ] = "normal",
138 ):
139 """Test app with special characters."""
140 pass
141
142 tester = fish_tester(app, "special")
143 assert tester.validate_script_syntax()
144
145
146 def test_help_descriptions(fish_tester):
147 """Test that help descriptions appear in completions."""
148 tester = fish_tester(app_basic, "basic")
149
150 assert "Enable verbose output" in tester.completion_script
151 assert "Deploy to environment" in tester.completion_script
152
153
154 def test_subcommand_conditions(fish_tester):
155 """Test that subcommands use proper fish conditions."""
156 tester = fish_tester(app_nested, "nested")
157
158 assert (
159 "__fish_use_subcommand" in tester.completion_script or "__fish_seen_subcommand_from" in tester.completion_script
160 )
161
162
163 def test_description_escaping(fish_tester):
164 """Test that descriptions with special chars are properly escaped."""
165 app = App(name="escape_test")
166
167 @app.default
168 def main(
169 param1: Annotated[str, Parameter(help="Test 'single' quotes")] = "",
170 param2: Annotated[str, Parameter(help='Test "double" quotes')] = "",
171 param3: Annotated[str, Parameter(help="Test $variable and `backticks`")] = "",
172 ):
173 """Test app."""
174
175 tester = fish_tester(app, "escape_test")
176 assert tester.validate_script_syntax()
177
178
179 def test_special_chars_in_literal_choices(fish_tester):
180 """Test that Literal choices with special characters are properly escaped."""
181 app = App(name="special_choices")
182
183 @app.default
184 def main(
185 choice: Annotated[Literal["foo bar", "baz()", "test[1]"], Parameter()] = "foo bar",
186 ):
187 """Test app with special chars in choices."""
188
189 tester = fish_tester(app, "special_choices")
190 assert tester.validate_script_syntax()
191
192
193 def test_unicode_in_descriptions(fish_tester):
194 """Test that Unicode characters in descriptions are handled properly."""
195 app = App(name="unicode_test")
196
197 @app.default
198 def main(
199 emoji: Annotated[str, Parameter(help="Enable 🚀 rocket mode")] = "",
200 chinese: Annotated[str, Parameter(help="中文描述")] = "",
201 arabic: Annotated[str, Parameter(help="وصف بالعربية")] = "",
202 ):
203 """Test app with Unicode."""
204
205 tester = fish_tester(app, "unicode_test")
206 assert "🚀" in tester.completion_script or "rocket mode" in tester.completion_script
207 assert tester.validate_script_syntax()
208
209
210 def test_deeply_nested_commands(fish_tester):
211 """Test completion for deeply nested commands (3+ levels)."""
212 root = App(name="root")
213 level1 = App(name="level1")
214 level2 = App(name="level2")
215 level3 = App(name="level3")
216
217 @level3.command
218 def action(value: str):
219 """Perform action at level 3."""
220 pass
221
222 level2.command(level3)
223 level1.command(level2)
224 root.command(level1)
225
226 tester = fish_tester(root, "root")
227
228 assert "level1" in tester.completion_script
229 assert "level2" in tester.completion_script
230 assert "level3" in tester.completion_script
231 assert "action" in tester.completion_script
232 assert tester.validate_script_syntax()
233
234
235 def test_nested_command_disambiguation(fish_tester):
236 """Test that nested commands are properly disambiguated.
237
238 This test verifies that the helper function correctly distinguishes between
239 commands with overlapping names (e.g., 'config get' vs 'admin get').
240 """
241 root = App(name="myapp")
242
243 config = App(name="config")
244 admin = App(name="admin")
245
246 @config.command(name="get")
247 def config_get(key: Annotated[str, Parameter(help="Config key")] = ""):
248 """Get config value."""
249 pass
250
251 @config.command(name="set")
252 def config_set(key: str = "", value: str = ""):
253 """Set config value."""
254 pass
255
256 @admin.command(name="get")
257 def admin_get(user: Annotated[str, Parameter(help="Username")] = ""):
258 """Get admin user."""
259 pass
260
261 root.command(config)
262 root.command(admin)
263
264 tester = fish_tester(root, "myapp")
265
266 script = tester.completion_script
267
268 assert "__fish_myapp_using_command" in script, "Helper function should be generated"
269
270 assert "'__fish_myapp_using_command config'" in script, "Should use helper for config path"
271 assert "'__fish_myapp_using_command admin'" in script, "Should use helper for admin path"
272
273 config_get_lines = [line for line in script.split("\n") if "config" in line.lower() and "get" in line.lower()]
274 admin_get_lines = [line for line in script.split("\n") if "admin" in line.lower() and "get" in line.lower()]
275
276 assert any("config key" in line.lower() or "config" in line for line in config_get_lines), (
277 "Config get should have config-specific completions"
278 )
279
280 assert any("username" in line.lower() or "admin" in line for line in admin_get_lines), (
281 "Admin get should have admin-specific completions"
282 )
283
284 assert tester.validate_script_syntax()
285
286
287 def test_helper_function_generation(fish_tester):
288 """Test that helper function is only generated when needed."""
289 root_only = App(name="rootonly")
290
291 @root_only.default
292 def main(verbose: bool = False):
293 """Root only app."""
294 pass
295
296 tester_root = fish_tester(root_only, "rootonly")
297 assert "__fish_rootonly_using_command" not in tester_root.completion_script, "No helper for root-only app"
298
299 nested = App(name="nested")
300 sub = App(name="sub")
301
302 @sub.default
303 def action():
304 """Sub action."""
305 pass
306
307 nested.command(sub)
308
309 tester_nested = fish_tester(nested, "nested")
310 assert "__fish_nested_using_command" in tester_nested.completion_script, "Helper should be generated for nested app"
311
312
313 def test_flag_vs_option_distinction(fish_tester):
314 """Test that flags and options are distinguished correctly.
315
316 Flags should not have -r (require parameter), while options should.
317 """
318 app = App(name="flagtest")
319
320 @app.default
321 def main(
322 verbose: Annotated[bool, Parameter(help="Enable verbose")] = False,
323 count: Annotated[int, Parameter(help="Count")] = 1,
324 ):
325 """Test app."""
326
327 tester = fish_tester(app, "flagtest")
328
329 lines = tester.completion_script.split("\n")
330
331 verbose_lines = [line for line in lines if "verbose" in line.lower()]
332 count_lines = [line for line in lines if "count" in line]
333
334 has_verbose_flag_only = any("-l verbose" in line and "-r" not in line for line in verbose_lines)
335 has_count_with_r = any("-l count" in line and "-r" in line for line in count_lines)
336
337 assert has_verbose_flag_only, "Verbose flag should not require parameter"
338 assert has_count_with_r, "Count option should require parameter"
339
340
341 def test_optional_path_completion(fish_tester):
342 """Test that Optional[Path] and Path | None generate file completion."""
343 tester = fish_tester(app_path, "pathapp")
344
345 assert "-F" in tester.completion_script or "__fish_complete_directories" in tester.completion_script
346
347
348 def test_no_file_completion_for_strings(fish_tester):
349 """Test that string options don't default to file completion."""
350 app = App(name="strtest")
351
352 @app.default
353 def main(
354 name: Annotated[str, Parameter(help="Name")] = "default",
355 ):
356 """Test app."""
357
358 tester = fish_tester(app, "strtest")
359 assert tester.validate_script_syntax()
360
361
362 def test_help_version_flags_in_subcommands(fish_tester):
363 """Test that help and version flags appear in subcommand completions."""
364 tester = fish_tester(app_basic, "basic")
365
366 script_lines = tester.completion_script.split("\n")
367
368 deploy_section = []
369 in_deploy = False
370 for line in script_lines:
371 if "deploy" in line:
372 in_deploy = True
373 if in_deploy:
374 deploy_section.append(line)
375 if "__fish_seen_subcommand_from deploy" in line:
376 for i in range(len(script_lines)):
377 if i > script_lines.index(line):
378 deploy_section.append(script_lines[i])
379 if "__fish_seen_subcommand_from" in script_lines[i] and "deploy" not in script_lines[i]:
380 break
381 break
382
383 deploy_text = "\n".join(deploy_section)
384
385 assert "--help" in deploy_text or "-l help" in deploy_text
386
387
388 def test_empty_iterable_flag_completion(fish_tester):
389 """Test that --empty-* flags for list parameters are treated as flags.
390
391 Regression test for issue where --empty-items on list[str] parameters
392 would expect a value instead of being treated as a flag.
393 """
394 app = App(name="listapp")
395
396 @app.command
397 def process(
398 items: Annotated[list[str], Parameter(help="Items to process")],
399 tags: Annotated[list[str] | None, Parameter(help="Optional tags")] = None,
400 ):
401 """Process items."""
402 pass
403
404 tester = fish_tester(app, "listapp")
405
406 assert "--items" in tester.completion_script or "-l items" in tester.completion_script
407 assert "--empty-items" in tester.completion_script or "-l empty-items" in tester.completion_script
408 assert "--tags" in tester.completion_script or "-l tags" in tester.completion_script
409 assert "--empty-tags" in tester.completion_script or "-l empty-tags" in tester.completion_script
410
411 lines = tester.completion_script.split("\n")
412 empty_items_lines = [line for line in lines if "empty-items" in line]
413
414 for line in empty_items_lines:
415 if "-l empty-items" in line:
416 assert "-r" not in line, "Negative flags should not require parameter (-r)"
417
418 assert tester.validate_script_syntax()
419
420
421 def test_helper_function_skips_option_values(fish_tester):
422 """Test that helper function correctly identifies and skips option values.
423
424 Critical bug fix test: ensures that when building command path,
425 the helper function skips values for options that take arguments.
426 Without this, 'myapp --config file.yaml subcommand' would incorrectly
427 extract [file.yaml, subcommand] instead of [subcommand].
428 """
429 app = App(name="myapp")
430 sub = App(name="sub")
431
432 @sub.default
433 def action():
434 """Subcommand action."""
435 pass
436
437 @app.default
438 def main(
439 config: Annotated[str, Parameter(help="Config file path")],
440 verbose: bool = False,
441 ):
442 """Main app."""
443 pass
444
445 app.command(sub)
446
447 tester = fish_tester(app, "myapp")
448 script = tester.completion_script
449
450 assert "options_with_values" in script, "Helper should track options that take values"
451 assert "--config" in script or "config" in script
452
453 lines = script.split("\n")
454 options_line = None
455 for line in lines:
456 if "options_with_values" in line and "set -l" in line:
457 options_line = line
458 break
459
460 assert options_line is not None, "Should have a line setting options_with_values"
461 assert "--config" in options_line or "config" in options_line, "Should include --config in options_with_values"
462 assert "--verbose" not in options_line, "Flags should not be in options_with_values"
463
464 skip_check = [line for line in lines if "skip_next" in line]
465 assert len(skip_check) > 0, "Helper should use skip_next logic to skip option values"
466
467 assert tester.validate_script_syntax()
468
469
470 def test_markdown_markup_stripped_from_descriptions(fish_tester):
471 """Test that markdown markup is stripped from help descriptions.
472
473 Ensures that **bold**, *italic*, `code`, and other markdown syntax
474 is properly removed from completion descriptions.
475 """
476 tester = fish_tester(app_markup, "markupapp")
477 script = tester.completion_script
478
479 assert "Enable verbose output with extra details" in script, "Should contain plain text version"
480 assert "**verbose**" not in script, "Should not contain markdown bold syntax"
481 assert "`extra`" not in script, "Should not contain markdown code syntax"
482
483 assert "Choose execution mode: fast or slow" in script, "Should contain plain text version"
484 assert "*execution*" not in script, "Should not contain markdown italic syntax"
485 assert "**fast**" not in script, "Should not contain markdown bold in mode description"
486 assert "**slow**" not in script, "Should not contain markdown bold in mode description"
487
488 assert "Target environment like dev or prod" in script, "Should contain plain text version"
489 assert "`environment`" not in script, "Should not contain markdown code in env description"
490 assert "**dev**" not in script, "Should not contain markdown bold in env description"
491 assert "**prod**" not in script, "Should not contain markdown bold in env description"
492
493 assert "Deploy to environment" in script, "Should contain plain text command description"
494 assert "`environment`" not in script, "Should not contain markdown code in command description"
495
496 assert tester.validate_script_syntax()
497
498
499 def test_rst_markup_stripped_from_descriptions(fish_tester):
500 """Test that RST markup is stripped from help descriptions.
501
502 Ensures that **bold**, ``code``, and other RST syntax
503 is properly removed from completion descriptions.
504 """
505 tester = fish_tester(app_rst, "rstapp")
506 script = tester.completion_script
507
508 assert "Enable verbose output with code samples" in script, "Should contain plain text version"
509 assert "**verbose**" not in script, "Should not contain RST bold syntax"
510 assert "``code``" not in script, "Should not contain RST code syntax (double backticks)"
511
512 assert "Choose execution mode: fast or slow" in script, "Should contain plain text version"
513 assert "*execution*" not in script, "Should not contain RST italic syntax"
514 assert "**fast**" not in script, "Should not contain RST bold in mode description"
515 assert "**slow**" not in script, "Should not contain RST bold in mode description"
516
517 assert tester.validate_script_syntax()
518
519
520 def test_literal_with_show_choices_false(fish_tester):
521 """Test that Literal with show_choices=False still provides completions.
522
523 Regression test: When show_choices=False is set on a Literal parameter,
524 the choices should still be available for shell completion, even though
525 they are hidden from the help text.
526 """
527 app = App(name="deploy")
528
529 @app.default
530 def main(
531 env: Annotated[
532 Literal["dev", "staging", "prod"],
533 Parameter(help="Environment to deploy to", show_choices=False),
534 ],
535 ):
536 """Deploy to environment."""
537 pass
538
539 tester = fish_tester(app, "deploy")
540 script = tester.completion_script
541
542 # Choices should be in completion script even with show_choices=False
543 assert "dev" in script
544 assert "staging" in script
545 assert "prod" in script
546
547
548 def test_command_with_multiple_names_and_aliases(fish_tester):
549 """Test that commands registered with multiple names/aliases all appear in completions.
550
551 Regression test for groups_from_app() deduplication - ensures all registered
552 names are included in completion scripts.
553 """
554 app = App(name="myapp")
555 sub = App()
556
557 @sub.default
558 def action(value: str = ""):
559 """Perform an action."""
560 pass
561
562 app.command(sub, name="foo", alias=["bar", "baz"])
563
564 tester = fish_tester(app, "myapp")
565 script = tester.completion_script
566
567 assert "foo" in script, "Primary name should be in completion script"
568 assert "bar" in script, "First alias should be in completion script"
569 assert "baz" in script, "Second alias should be in completion script"
570
571 assert tester.validate_script_syntax()
572
573
574 def test_list_path_completion(fish_tester):
575 """Test that list[Path] arguments generate file completion.
576
577 Regression test for issue #654: list[Path] arguments should use
578 file completion (-F) just like Path arguments.
579 """
580 tester = fish_tester(app_list_path, "listpath")
581 script = tester.completion_script
582
583 assert "-F" in script, "list[Path] should generate file completion"
584 assert tester.validate_script_syntax()
585
586
587 def test_fish_path_completion_reflects_caller_cwd(fish_tester):
588 """Path completion must inspect the caller's cwd, not the harness tmpdir.
589
590 Reproduces the Copilot finding: ``FishCompletionTester.get_completions()``
591 forces ``cwd=`` to the temporary directory holding the comp-script, so a
592 test that ``os.chdir()``-es into a target directory before calling
593 ``get_completions()`` has the chdir overridden by the driver. Path
594 completion then lists files from the comp-script's tmpdir instead of the
595 intended directory. The driver should inherit the caller's cwd.
596 """
597 import os
598 import tempfile
599 from pathlib import Path as _Path
600
601 app = App(name="pcwd")
602
603 @app.default
604 def m(output: Annotated[_Path, Parameter(help="Out")] = _Path()):
605 """Path keyword."""
606
607 tester = fish_tester(app, "pcwd")
608 with tempfile.TemporaryDirectory() as td:
609 (_Path(td) / "myfile.txt").write_text("x")
610 cwd = _Path.cwd()
611 try:
612 os.chdir(td)
613 completions = tester.get_completions("pcwd --output ")
614 finally:
615 os.chdir(cwd)
616
617 # Fish may return either bare basenames or full paths; accept either.
618 assert any("myfile.txt" in c for c in completions), (
619 f"expected 'myfile.txt' from caller cwd, got {completions!r} (driver likely overrode cwd to its own tmpdir)"
620 )