Coverage for tests / test_others.py: 100%
289 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1import os 1abcdefghij
2import subprocess 1abcdefghij
3import sys 1abcdefghij
4import typing 1abcdefghij
5from pathlib import Path 1abcdefghij
6from typing import Annotated, Any 1abcdefghij
7from unittest import mock 1abcdefghij
9import pytest 1abcdefghij
10import typer 1abcdefghij
11import typer._completion_shared 1abcdefghij
12import typer.completion 1abcdefghij
13from typer import _click 1abcdefghij
14from typer.main import solve_typer_info_defaults, solve_typer_info_help 1abcdefghij
15from typer.models import TyperInfo 1abcdefghij
16from typer.testing import CliRunner 1abcdefghij
18from .utils import requires_completion_permission 1abcdefghij
20runner = CliRunner() 1abcdefghij
23def test_help_from_info(): 1abcdefghij
24 # Mainly for coverage/completeness
25 value = solve_typer_info_help(TyperInfo()) 1abcdefghij
26 assert value is None 1abcdefghij
29def test_defaults_from_info(): 1abcdefghij
30 # Mainly for coverage/completeness
31 value = solve_typer_info_defaults(TyperInfo()) 1abcdefghij
32 assert value 1abcdefghij
35@requires_completion_permission 1abcdefghij
36def test_install_invalid_shell(): 1abcdefghij
37 app = typer.Typer() 1abcdefghij
39 @app.command() 1abcdefghij
40 def main(): 1abcdefghij
41 print("Hello World") 1abcdefghij
43 with mock.patch.object( 1abcdefghij
44 typer._completion_shared, "_get_shell_name", return_value="xshell"
45 ):
46 result = runner.invoke(app, ["--install-completion"]) 1abcdefghij
47 assert "Shell xshell is not supported." in result.stdout 1abcdefghij
48 result = runner.invoke(app) 1abcdefghij
49 assert "Hello World" in result.stdout 1abcdefghij
52def test_callback_too_many_parameters(): 1abcdefghij
53 app = typer.Typer() 1abcdefghij
55 def name_callback(ctx, param, val1, val2): 1abcdefghij
56 pass # pragma: no cover
58 @app.command() 1abcdefghij
59 def main(name: str = typer.Option(..., callback=name_callback)): 1abcdefghij
60 pass # pragma: no cover
62 with pytest.raises(_click.ClickException) as exc_info: 1abcdefghij
63 runner.invoke(app, ["--name", "Camila"]) 1abcdefghij
64 assert ( 1abcdefghij
65 exc_info.value.message == "Too many CLI parameter callback function parameters"
66 )
69def test_callback_2_untyped_parameters(): 1abcdefghij
70 app = typer.Typer() 1abcdefghij
72 def name_callback(ctx, value): 1abcdefghij
73 print(f"info name is: {ctx.info_name}") 1abcdefghij
74 print(f"value is: {value}") 1abcdefghij
76 @app.command() 1abcdefghij
77 def main(name: str = typer.Option(..., callback=name_callback)): 1abcdefghij
78 print("Hello World") 1abcdefghij
80 result = runner.invoke(app, ["--name", "Camila"]) 1abcdefghij
81 assert "info name is: main" in result.stdout 1abcdefghij
82 assert "value is: Camila" in result.stdout 1abcdefghij
85@pytest.mark.parametrize( 1abcdefghij
86 ("param_hint", "option_decls", "expected_message"),
87 [
88 ("--name", (), "Invalid value for --name"),
89 (None, ("--name", "-n"), "Invalid value for '--name' / '-n'"),
90 ],
91)
92def test_bad_parameter_callback( 1abcdefghij
93 param_hint: str | None, option_decls: tuple[str, ...], expected_message: str
94) -> None:
95 app = typer.Typer() 1abcdefghij
97 def my_bad(value: str) -> str: 1abcdefghij
98 kwargs = {"param_hint": param_hint} if param_hint is not None else {} 1abcdefghij
99 raise typer.BadParameter("custom validation failed", **kwargs) 1abcdefghij
101 @app.command() 1abcdefghij
102 def main(name: str = typer.Option(..., *option_decls, callback=my_bad)) -> None: 1abcdefghij
103 typer.echo(name) # pragma: no cover
105 result = runner.invoke(app, ["--name", "Camila"]) 1abcdefghij
106 assert result.exit_code == 2 1abcdefghij
107 assert expected_message in result.stderr 1abcdefghij
108 assert "custom validation failed" in result.stderr 1abcdefghij
111def test_bad_parameter_main() -> None: 1abcdefghij
112 app = typer.Typer() 1abcdefghij
114 @app.command() 1abcdefghij
115 def main() -> None: 1abcdefghij
116 raise typer.BadParameter("custom validation failed") 1abcdefghij
118 result = runner.invoke(app, []) 1abcdefghij
119 assert result.exit_code == 2 1abcdefghij
120 assert "Invalid value: custom validation failed" in result.stderr 1abcdefghij
123@pytest.mark.parametrize( 1abcdefghij
124 ("kw", "msg"),
125 [
126 (
127 {"param_hint": ["--name", "-n"], "param_type": "parameter"},
128 "Missing parameter '--name' / '-n'.",
129 ),
130 ({"param_type": "value"}, "Missing value."),
131 ],
132)
133def test_missing_parameter_msg(kw: dict[str, object], msg: str) -> None: 1abcdefghij
134 app = typer.Typer(rich_markup_mode=None) 1abcdefghij
136 @app.command() 1abcdefghij
137 def main() -> None: 1abcdefghij
138 raise typer._click.exceptions.MissingParameter(**kw) 1abcdefghij
140 result = runner.invoke(app, []) 1abcdefghij
141 assert result.exit_code == 2 1abcdefghij
142 assert msg in result.stderr 1abcdefghij
145def test_missing_parameter_callback_msg() -> None: 1abcdefghij
146 def my_cb(ctx: typer.Context, param: typer.CallbackParam, value: str) -> str: 1abcdefghij
147 raise typer._click.exceptions.MissingParameter( 1abcdefghij
148 message="My bad", ctx=ctx, param=param, param_type="parameter"
149 )
151 app = typer.Typer(rich_markup_mode=None) 1abcdefghij
153 @app.command() 1abcdefghij
154 def main( 1abcdefghij
155 mode: Annotated[
156 typing.Literal["alpha", "beta"],
157 typer.Option(..., "--mode", callback=my_cb),
158 ],
159 ) -> None:
160 typer.echo(mode) # pragma: no cover
162 result = runner.invoke(app, ["--mode", "alpha"]) 1abcdefghij
163 assert result.exit_code == 2 1abcdefghij
164 assert "Missing parameter '--mode'." in result.stderr 1abcdefghij
165 assert "My bad. Choose from:" in result.stderr 1abcdefghij
166 assert "alpha" in result.stderr 1abcdefghij
167 assert "beta" in result.stderr 1abcdefghij
168 result_msg = runner.invoke(app, ["--mode", "alpha"], standalone_mode=False) 1abcdefghij
169 assert isinstance(result_msg.exception, typer._click.exceptions.MissingParameter) 1abcdefghij
170 assert str(result_msg.exception) == "My bad" 1abcdefghij
173def test_missing_parameter_str() -> None: 1abcdefghij
174 def my_cb(ctx: typer.Context, param: typer.CallbackParam, value: str) -> str: 1abcdefghij
175 raise typer._click.exceptions.MissingParameter(ctx=ctx, param=param) 1abcdefghij
177 app = typer.Typer() 1abcdefghij
179 @app.command() 1abcdefghij
180 def main(mode: str = typer.Option(..., "--mode", callback=my_cb)) -> None: 1abcdefghij
181 typer.echo(mode) # pragma: no cover
183 result2 = runner.invoke(app, ["--mode", "alpha"], standalone_mode=False) 1abcdefghij
184 assert isinstance(result2.exception, typer._click.exceptions.MissingParameter) 1abcdefghij
185 assert str(result2.exception) == "Missing parameter: mode" 1abcdefghij
188def test_click_exception_show_default_file() -> None: 1abcdefghij
189 app = typer.Typer(rich_markup_mode=None) 1abcdefghij
191 @app.command() 1abcdefghij
192 def main() -> None: 1abcdefghij
193 raise typer._click.ClickException("custom click failure") 1abcdefghij
195 result = runner.invoke(app, []) 1abcdefghij
196 assert result.exit_code == 1 1abcdefghij
197 assert "custom click" in result.stderr 1abcdefghij
198 assert "failure" in result.stderr 1abcdefghij
201def test_no_args_is_help_show() -> None: 1abcdefghij
202 app = typer.Typer(rich_markup_mode=None) 1abcdefghij
204 @app.callback(invoke_without_command=True, no_args_is_help=True) 1abcdefghij
205 def main() -> None: 1abcdefghij
206 return None # pragma: no cover
208 result = runner.invoke(app, []) 1abcdefghij
209 assert result.exit_code == 2 1abcdefghij
210 assert "Usage:" in result.stderr 1abcdefghij
211 assert "Show this message and exit." in result.stderr 1abcdefghij
214def test_callback_3_untyped_parameters(): 1abcdefghij
215 app = typer.Typer() 1abcdefghij
217 def name_callback(ctx, param, value): 1abcdefghij
218 print(f"info name is: {ctx.info_name}") 1abcdefghij
219 print(f"param name is: {param.name}") 1abcdefghij
220 print(f"value is: {value}") 1abcdefghij
222 @app.command() 1abcdefghij
223 def main(name: str = typer.Option(..., callback=name_callback)): 1abcdefghij
224 print("Hello World") 1abcdefghij
226 result = runner.invoke(app, ["--name", "Camila"]) 1abcdefghij
227 assert "info name is: main" in result.stdout 1abcdefghij
228 assert "param name is: name" in result.stdout 1abcdefghij
229 assert "value is: Camila" in result.stdout 1abcdefghij
232def test_callback_4_list_none(): 1abcdefghij
233 app = typer.Typer() 1abcdefghij
235 def names_callback(ctx, param, values: list[str] | None): 1abcdefghij
236 if values is None: 1abcdefghij
237 return values 1abcdefghij
238 return [value.upper() for value in values] 1abcdefghij
240 @app.command() 1abcdefghij
241 def main( 1abcdefghij
242 names: list[str] | None = typer.Option(None, "--name", callback=names_callback),
243 ):
244 if names is None: 1abcdefghij
245 print("Hello World") 1abcdefghij
246 else:
247 print(f"Hello {', '.join(names)}") 1abcdefghij
249 result = runner.invoke(app, ["--name", "Sideshow", "--name", "Bob"]) 1abcdefghij
250 assert "Hello SIDESHOW, BOB" in result.stdout 1abcdefghij
252 result = runner.invoke(app, []) 1abcdefghij
253 assert "Hello World" in result.stdout 1abcdefghij
256def test_multiple_bool_flags() -> None: 1abcdefghij
257 app = typer.Typer() 1abcdefghij
259 @app.command() 1abcdefghij
260 def main(choices: list[bool] = typer.Option([], "--accept/--reject")) -> None: 1abcdefghij
261 print(choices) 1abcdefghij
263 result = runner.invoke(app, ["--accept", "--reject", "--accept"]) 1abcdefghij
264 assert result.exit_code == 0 1abcdefghij
265 assert "[True, False, True]" in result.stdout 1abcdefghij
268def test_empty_list_default_generator(): 1abcdefghij
269 def empty_list() -> list[str]: 1abcdefghij
270 return [] 1abcdefghij
272 app = typer.Typer() 1abcdefghij
274 @app.command() 1abcdefghij
275 def main( 1abcdefghij
276 names: Annotated[list[str], typer.Option(default_factory=empty_list)],
277 ):
278 print(names) 1abcdefghij
280 result = runner.invoke(app) 1abcdefghij
281 assert "[]" in result.output 1abcdefghij
284def test_option_envvar(): 1abcdefghij
285 app = typer.Typer() 1abcdefghij
287 @app.command() 1abcdefghij
288 def main(user: Annotated[str, typer.Option(envvar="ME")]): 1abcdefghij
289 print(f"Hello {user}") 1abcdefghij
291 result = runner.invoke(app, env={"ME": "rick"}) 1abcdefghij
292 assert result.exit_code == 0 1abcdefghij
293 assert "Hello rick" in result.output 1abcdefghij
296def test_option_envvar_list(): 1abcdefghij
297 app = typer.Typer() 1abcdefghij
299 @app.command() 1abcdefghij
300 def main(users: Annotated[list[str], typer.Option(envvar="ME")]): 1abcdefghij
301 for u in users: 1abcdefghij
302 print(f"Hello {u}") 1abcdefghij
304 result = runner.invoke(app, env={"ME": "rick morty"}) 1abcdefghij
305 assert result.exit_code == 0 1abcdefghij
306 assert "Hello rick" in result.output 1abcdefghij
307 assert "Hello morty" in result.output 1abcdefghij
310def test_option_envvar_list_path(tmp_path: Path) -> None: 1abcdefghij
311 first = tmp_path / "a.txt" 1abcdefghij
312 second = tmp_path / "b.txt" 1abcdefghij
313 first.write_text("a", encoding="utf-8") 1abcdefghij
314 second.write_text("b", encoding="utf-8") 1abcdefghij
315 app = typer.Typer() 1abcdefghij
317 @app.command() 1abcdefghij
318 def main(configs: Annotated[list[Path], typer.Option(envvar="MYFILES")]): 1abcdefghij
319 print([path.name for path in configs]) 1abcdefghij
321 result = runner.invoke(app, env={"MYFILES": f"{first}{os.path.pathsep}{second}"}) 1abcdefghij
322 assert result.exit_code == 0, result.output 1abcdefghij
323 assert result.output.strip() == "['a.txt', 'b.txt']" 1abcdefghij
326def test_option_envvar_list_file(tmp_path: Path) -> None: 1abcdefghij
327 first = tmp_path / "a.txt" 1abcdefghij
328 second = tmp_path / "b.txt" 1abcdefghij
329 first.write_text("one", encoding="utf-8") 1abcdefghij
330 second.write_text("two", encoding="utf-8") 1abcdefghij
331 app = typer.Typer() 1abcdefghij
333 @app.command() 1abcdefghij
334 def main(files: Annotated[list[typer.FileText], typer.Option(envvar="FILES")]): 1abcdefghij
335 print([file.read() for file in files]) 1abcdefghij
337 result = runner.invoke(app, env={"FILES": f"{first}{os.path.pathsep}{second}"}) 1abcdefghij
338 assert result.exit_code == 0, result.output 1abcdefghij
339 assert result.output.strip() == "['one', 'two']" 1abcdefghij
342def test_option_envvar_list_path_options(tmp_path: Path) -> None: 1abcdefghij
343 first = tmp_path / "first dir" / "a.txt" 1abcdefghij
344 second = tmp_path / "second dir" / "b.txt" 1abcdefghij
345 first.parent.mkdir(parents=True, exist_ok=True) 1abcdefghij
346 second.parent.mkdir(parents=True, exist_ok=True) 1abcdefghij
347 first.write_text("a", encoding="utf-8") 1abcdefghij
348 second.write_text("b", encoding="utf-8") 1abcdefghij
349 app = typer.Typer() 1abcdefghij
351 @app.command() 1abcdefghij
352 def main( 1abcdefghij
353 configs: Annotated[
354 list[Any], typer.Option(envvar="MYFILES", resolve_path=True)
355 ],
356 ):
357 print([Path(str(path)).name for path in configs]) 1abcdefghij
359 result = runner.invoke(app, env={"MYFILES": f"{first}{os.path.pathsep}{second}"}) 1abcdefghij
360 assert result.exit_code == 0, result.output 1abcdefghij
361 assert result.output.strip() == "['a.txt', 'b.txt']" 1abcdefghij
364def test_completion_argument(): 1abcdefghij
365 file_path = Path(__file__).parent / "assets/completion_argument.py" 1abcdefghij
366 result = subprocess.run( 1abcdefghij
367 [sys.executable, "-m", "coverage", "run", str(file_path), "E"],
368 capture_output=True,
369 encoding="utf-8",
370 env={
371 **os.environ,
372 "_COMPLETION_ARGUMENT.PY_COMPLETE": "complete_zsh",
373 "_TYPER_COMPLETE_ARGS": "completion_argument.py E",
374 "_TYPER_COMPLETE_TESTING": "True",
375 },
376 )
377 assert "Emma" in result.stdout or "_files" in result.stdout 1abcdefghij
378 assert "ctx: completion_argument" in result.stderr 1abcdefghij
379 assert "arg is: name" in result.stderr 1abcdefghij
380 assert "incomplete is: E" in result.stderr 1abcdefghij
383def test_completion_untyped_parameters(): 1abcdefghij
384 file_path = Path(__file__).parent / "assets/completion_no_types.py" 1abcdefghij
385 result = subprocess.run( 1abcdefghij
386 [sys.executable, "-m", "coverage", "run", str(file_path)],
387 capture_output=True,
388 encoding="utf-8",
389 env={
390 **os.environ,
391 "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",
392 "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",
393 },
394 )
395 assert "info name is: completion_no_types.py" in result.stderr 1abcdefghij
396 assert "args is: []" in result.stderr 1abcdefghij
397 assert "incomplete is: Ca" in result.stderr 1abcdefghij
398 assert '"Camila":"The reader of books."' in result.stdout 1abcdefghij
399 assert '"Carlos":"The writer of scripts."' in result.stdout 1abcdefghij
401 result = subprocess.run( 1abcdefghij
402 [sys.executable, "-m", "coverage", "run", str(file_path)],
403 capture_output=True,
404 encoding="utf-8",
405 )
406 assert "Hello World" in result.stdout 1abcdefghij
409def test_completion_untyped_parameters_different_order_correct_names(): 1abcdefghij
410 file_path = Path(__file__).parent / "assets/completion_no_types_order.py" 1abcdefghij
411 result = subprocess.run( 1abcdefghij
412 [sys.executable, "-m", "coverage", "run", str(file_path)],
413 capture_output=True,
414 encoding="utf-8",
415 env={
416 **os.environ,
417 "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",
418 "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",
419 },
420 )
421 assert "info name is: completion_no_types_order.py" in result.stderr 1abcdefghij
422 assert "args is: []" in result.stderr 1abcdefghij
423 assert "incomplete is: Ca" in result.stderr 1abcdefghij
424 assert '"Camila":"The reader of books."' in result.stdout 1abcdefghij
425 assert '"Carlos":"The writer of scripts."' in result.stdout 1abcdefghij
427 result = subprocess.run( 1abcdefghij
428 [sys.executable, "-m", "coverage", "run", str(file_path)],
429 capture_output=True,
430 encoding="utf-8",
431 )
432 assert "Hello World" in result.stdout 1abcdefghij
435def test_autocompletion_too_many_parameters(): 1abcdefghij
436 app = typer.Typer() 1abcdefghij
438 def name_callback(ctx, args, incomplete, val2): 1abcdefghij
439 pass # pragma: no cover
441 @app.command() 1abcdefghij
442 def main(name: str = typer.Option(..., autocompletion=name_callback)): 1abcdefghij
443 pass # pragma: no cover
445 with pytest.raises(_click.ClickException) as exc_info: 1abcdefghij
446 runner.invoke(app, ["--name", "Camila"]) 1abcdefghij
447 assert exc_info.value.message == "Invalid autocompletion callback parameters: val2" 1abcdefghij
450def test_forward_references(): 1abcdefghij
451 app = typer.Typer() 1abcdefghij
453 @app.command() 1abcdefghij
454 def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False): 1abcdefghij
455 print(f"arg1: {type(arg1)} {arg1}") 1abcdefghij
456 print(f"arg2: {type(arg2)} {arg2}") 1abcdefghij
457 print(f"arg3: {type(arg3)} {arg3}") 1abcdefghij
458 print(f"arg4: {type(arg4)} {arg4}") 1abcdefghij
459 print(f"arg5: {type(arg5)} {arg5}") 1abcdefghij
461 result = runner.invoke(app, ["Hello", "2", "invalid"]) 1abcdefghij
463 assert "Invalid value for 'arg3'" in result.output 1abcdefghij
464 assert "Input should be a valid integer" in result.output 1abcdefghij
465 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"]) 1abcdefghij
466 assert ( 1abcdefghij
467 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"
468 in result.stdout
469 )
472def test_context_settings_inheritance_single_command(): 1abcdefghij
473 app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}) 1abcdefghij
475 @app.command() 1abcdefghij
476 def main(name: str): 1abcdefghij
477 pass # pragma: no cover
479 result = runner.invoke(app, ["main", "-h"]) 1abcdefghij
480 assert "Show this message and exit." in result.stdout 1abcdefghij
483def test_options_metadata_typer_default(): 1abcdefghij
484 app = typer.Typer(options_metavar="[options]") 1abcdefghij
486 @app.command() 1abcdefghij
487 def c1(): 1abcdefghij
488 pass # pragma: no cover
490 @app.command(options_metavar="[OPTS]") 1abcdefghij
491 def c2(): 1abcdefghij
492 pass # pragma: no cover
494 result = runner.invoke(app, ["c1", "--help"]) 1abcdefghij
495 assert "Usage: root c1 [options]" in result.stdout 1abcdefghij
497 result = runner.invoke(app, ["c2", "--help"]) 1abcdefghij
498 assert "Usage: root c2 [OPTS]" in result.stdout 1abcdefghij