Debian Codegraph @

tests/completion/test_behavior.py

raw symbols SCIP
1 """Cross-shell behavioral contract tests.
2
3 Most tests in this directory assert on the **text of the generated completion
4 script** (string containment). That is fast and catches regressions in the
5 generators, but it does not answer the real question: *when the user presses
6 TAB, does the shell actually offer the right suggestions?*
7
8 This file runs the same behavioral scenarios across bash, zsh, and fish via
9 the non-interactive drivers in ``conftest.py``. Any per-shell divergence
10 surfaces immediately as a single failing parametrization.
11
12 Assertions use subset / exclusion (not exact equality) because shells
13 legitimately differ in ordering and in whether helper entries like ``--help``
14 surface at every depth.
15
16 Known divergences (intentional, not bugs):
17
18 * **Naked-TAB at a no-arg subcommand**: bash returns nothing; zsh's
19 ``_arguments`` always lists ``--help`` / ``--version``. Bash's
20 ``cur == -*`` gate is the right convention — typing space-TAB usually
21 means "show me commands or positional values," not "show me flags," and
22 mixing flags into that suggestion list clutters the UI. The current
23 per-shell behavior is locked in by ``test_naked_tab_*`` in
24 ``test_bash.py`` / ``test_zsh.py``.
25 * **``--opt=value`` form** is now supported in both shells (Group C), but
26 the cross-shell scenario list below excludes it because each shell
27 reaches it through a different code path and the *space* form alone
28 exercises the binding logic well enough.
29 """
30
31 from __future__ import annotations
32
33 import pytest
34
35 from .apps import (
36 app_basic,
37 app_disabled_negative,
38 app_enum,
39 app_list_path,
40 app_multiple_positionals,
41 app_negative,
42 app_nested,
43 app_positional_literal,
44 app_positional_path,
45 app_three_positionals,
46 app_two_iterables,
47 )
48
49 # Each scenario:
50 # id - human-readable name (used as pytest id)
51 # app - App object
52 # prog_name - program name (matches what the generator was invoked with)
53 # partial - the command-line fragment the user has typed
54 # contains - suggestions that MUST appear (subset check)
55 # excludes - suggestions that MUST NOT appear (exclusion check)
56 SCENARIOS = [
57 # 1. Root-level subcommands listed.
58 (
59 "root-subcommands",
60 app_basic,
61 "basic",
62 "basic ",
63 {"deploy"},
64 set(),
65 ),
66 # 2. Subcommand prefix filters correctly.
67 (
68 "subcommand-prefix",
69 app_basic,
70 "basic",
71 "basic de",
72 {"deploy"},
73 set(),
74 ),
75 # 3. Long-flag prefix.
76 (
77 "flag-prefix",
78 app_basic,
79 "basic",
80 "basic --v",
81 {"--verbose"},
82 set(),
83 ),
84 # 4. All top-level options when user has typed just "-".
85 (
86 "all-flags",
87 app_basic,
88 "basic",
89 "basic -",
90 {"--verbose", "--count"},
91 set(),
92 ),
93 # 5. Negative form of a bool flag.
94 (
95 "negative-flag",
96 app_negative,
97 "negapp",
98 "negapp --no-",
99 {"--no-colors"},
100 set(),
101 ),
102 # 6. Literal choices after an option that takes a value.
103 (
104 "literal-option-value",
105 app_basic,
106 "basic",
107 "basic deploy --env ",
108 {"dev", "staging", "prod"},
109 set(),
110 ),
111 # 7. Literal positional (positional-only).
112 (
113 "literal-positional",
114 app_positional_literal,
115 "poslit",
116 "poslit command ",
117 {"foo", "bar", "baz"},
118 set(),
119 ),
120 # 8. Position-aware multi-positional: second arg has different choices.
121 (
122 "multi-positional-second",
123 app_multiple_positionals,
124 "multipos",
125 "multipos command-multi red ",
126 {"cat", "dog"},
127 {"red", "blue"},
128 ),
129 # 9. Nested subcommand discovery.
130 (
131 "nested-subcommand",
132 app_nested,
133 "nested",
134 "nested config ",
135 {"get", "set"},
136 set(),
137 ),
138 # 10. Path-typed positional triggers file completion (shell-specific).
139 # We can't assert specific filenames, so we only assert the driver
140 # returns *some* non-empty result when a file exists in cwd.
141 (
142 "path-positional",
143 app_positional_path,
144 "pathpos",
145 "pathpos process ",
146 None, # special-cased in the test body
147 set(),
148 ),
149 # 11. Enum values.
150 (
151 "enum-value",
152 app_enum,
153 "enumapp",
154 "enumapp --speed ",
155 {"fast", "slow"},
156 set(),
157 ),
158 # 12. Disabled-negatives + list-of-literal.
159 (
160 "list-of-literal",
161 app_disabled_negative,
162 "disabledneg",
163 "disabledneg build --param ",
164 {"apple", "banana", "cherry"},
165 set(),
166 ),
167 # 13. --help is always available at the root.
168 (
169 "help-at-root",
170 app_basic,
171 "basic",
172 "basic --h",
173 {"--help"},
174 set(),
175 ),
176 # 14. --opt=value form. Each shell reaches value-completion through a
177 # different code path (bash: COMP_WORDBREAK splits on '=' so the script
178 # walks back through ``$prev``; zsh: ``_arguments`` parses ``--env=`` as
179 # a single token; fish: ``complete -C`` does the right thing natively).
180 # Excluded historically out of caution — this is exactly where per-shell
181 # divergence regressions hide.
182 (
183 "equals-form-option-value",
184 app_basic,
185 "basic",
186 "basic deploy --env=p",
187 {"prod"},
188 set(),
189 ),
190 # 15. --help works at a nested command depth, not just the root.
191 (
192 "help-at-nested-depth",
193 app_nested,
194 "nested",
195 "nested config --h",
196 {"--help"},
197 set(),
198 ),
199 # 16. Position-aware multi-positional: third slot has its own choices.
200 # Scenario #8 only verifies the second slot — this catches off-by-one
201 # regressions deeper in the cycle.
202 (
203 "multi-positional-third",
204 app_three_positionals,
205 "multipos3",
206 "multipos3 command-multi3 red cat ",
207 {"small", "large"},
208 {"red", "blue", "cat", "dog"},
209 ),
210 # 17. Iterable positional (``list[Path]``) keeps offering completions
211 # past the first slot — a regression net for the rest-owner logic.
212 # Path completion is shell-specific, so we only assert non-empty (same
213 # convention as scenario #10).
214 (
215 "iterable-positional-rest",
216 app_list_path,
217 "listpath",
218 "listpath a.txt ",
219 None,
220 set(),
221 ),
222 # 18. Two iterable positionals back-to-back. The "first iterable wins
223 # the rest spec" rule (commits 1bc65e8 / 3302dc7) prevents a doubled
224 # rest spec from being emitted. With the bug present, scripts either
225 # fail to parse or silently produce wrong completions at the rest slot.
226 (
227 "two-iterables-rest-owner",
228 app_two_iterables,
229 "twoiter",
230 "twoiter collect a.txt b.txt ",
231 None,
232 set(),
233 ),
234 ]
235
236
237 @pytest.fixture(params=["bash", "zsh", "fish"])
238 def shell_tester_factory(request):
239 """Pick the right tester factory for this shell parametrization.
240
241 Resolves the target shell's fixture lazily via ``getfixturevalue`` so a
242 missing shell (e.g. fish absent locally) skips only its own
243 parametrizations, not every row in the matrix.
244 """
245 return request.getfixturevalue(f"{request.param}_tester")
246
247
248 @pytest.mark.parametrize(
249 ("scenario_id", "app", "prog_name", "partial", "contains", "excludes"),
250 SCENARIOS,
251 ids=[s[0] for s in SCENARIOS],
252 )
253 def test_behavior(
254 scenario_id,
255 app,
256 prog_name,
257 partial,
258 contains,
259 excludes,
260 shell_tester_factory,
261 ):
262 tester = shell_tester_factory(app, prog_name)
263
264 # Path-completion scenarios opt in with ``contains=None``. Different
265 # shells format file completions differently (fish: full path, bash:
266 # basename, zsh: a mix), so exact content checks would be brittle —
267 # we only assert the driver returns a non-empty result with a real
268 # file in cwd.
269 if contains is None:
270 import os
271 import tempfile
272 from pathlib import Path as _Path
273
274 with tempfile.TemporaryDirectory() as tmpdir:
275 (_Path(tmpdir) / "sample.txt").write_text("x")
276 cwd = _Path.cwd()
277 try:
278 os.chdir(tmpdir)
279 results = tester.get_completions(partial)
280 finally:
281 os.chdir(cwd)
282 assert results, f"[{scenario_id}] expected some file-completion result for {partial!r}, got nothing"
283 return
284
285 results = tester.get_completions(partial)
286
287 missing = contains - set(results)
288 assert not missing, (
289 f"[{scenario_id}] expected completions {missing} missing from shell output. partial={partial!r} got={results!r}"
290 )
291
292 leaked = excludes & set(results)
293 assert not leaked, (
294 f"[{scenario_id}] completions {leaked} should NOT have been offered. partial={partial!r} got={results!r}"
295 )