Coverage for tests / test_core.py: 100%
257 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
1from typing import Annotated 1abcdefghij
3import pytest 1abcdefghij
4import typer 1abcdefghij
5import typer._completion_shared 1abcdefghij
6import typer.completion 1abcdefghij
7from typer import _click 1abcdefghij
8from typer.core import TyperCommand, TyperGroup, _split_opt 1abcdefghij
9from typer.testing import CliRunner 1abcdefghij
11runner = CliRunner() 1abcdefghij
14def test_parameter_metavar() -> None: 1abcdefghij
15 app = typer.Typer(rich_markup_mode=None) 1abcdefghij
17 @app.command() 1abcdefghij
18 def cmd(name: Annotated[str, typer.Option(metavar="CUSTOM")]) -> None: 1abcdefghij
19 pass # pragma: no cover
21 result = runner.invoke(app, ["--help"]) 1abcdefghij
22 assert result.exit_code == 0 1abcdefghij
23 assert "--name CUSTOM" in result.output 1abcdefghij
26def test_tuple_argument_wrong_arity() -> None: 1abcdefghij
27 app = typer.Typer() 1abcdefghij
29 @app.command() 1abcdefghij
30 def cmd(value: tuple[str, str]): 1abcdefghij
31 pass # pragma: no cover
33 result = runner.invoke(app, ["only-one"]) 1abcdefghij
34 assert result.exit_code == 2 1abcdefghij
35 assert "takes 2 values" in result.output 1abcdefghij
38def test_tuple_argument_help() -> None: 1abcdefghij
39 app = typer.Typer(rich_markup_mode=None) 1abcdefghij
41 @app.command() 1abcdefghij
42 def cmd(value: tuple[str, str]) -> None: 1abcdefghij
43 pass # pragma: no cover
45 result = runner.invoke(app, ["--help"]) 1abcdefghij
46 assert result.exit_code == 0 1abcdefghij
47 assert "Arguments:" in result.output 1abcdefghij
48 assert "value... <str,str>" in result.output 1abcdefghij
51@pytest.mark.parametrize( 1abcdefghij
52 ("default_map", "env"),
53 [
54 (None, None),
55 ({"names": []}, None),
56 ({"names": ()}, None),
57 (None, {"NAMES": " "}),
58 ],
59)
60def test_required_list_option_missing( 1abcdefghij
61 default_map: dict[str, object] | None,
62 env: dict[str, str] | None,
63) -> None:
64 app = typer.Typer() 1abcdefghij
66 @app.command() 1abcdefghij
67 def cmd(names: list[str] = typer.Option(..., envvar="NAMES")) -> None: 1abcdefghij
68 pass # pragma: no cover
70 result = runner.invoke(app, [], default_map=default_map, env=env or {}) 1abcdefghij
71 assert result.exit_code == 2 1abcdefghij
72 assert "Missing option '--names'" in result.output 1abcdefghij
75def test_count_option() -> None: 1abcdefghij
76 app = typer.Typer() 1abcdefghij
78 @app.command() 1abcdefghij
79 def main(verbose: int = typer.Option(0, "--verbose", "-v", count=True)): 1abcdefghij
80 print(verbose) 1abcdefghij
82 result = runner.invoke(app, ["-vvv"]) 1abcdefghij
83 assert result.exit_code == 0 1abcdefghij
84 assert "3" in result.stdout 1abcdefghij
87def test_duplicate_declaration_raises() -> None: 1abcdefghij
88 app = typer.Typer() 1abcdefghij
90 @app.command() 1abcdefghij
91 def main(name: str = typer.Option(..., "name", "name")): 1abcdefghij
92 pass # pragma: no cover
94 with pytest.raises(TypeError, match="Name 'name' defined twice"): 1abcdefghij
95 typer.main.get_command(app) 1abcdefghij
98def test_invalid_boolean_flag_declaration_raises() -> None: 1abcdefghij
99 app = typer.Typer() 1abcdefghij
101 @app.command() 1abcdefghij
102 def main(flag: bool = typer.Option(False, "--flag/--flag")): 1abcdefghij
103 pass # pragma: no cover
105 with pytest.raises(ValueError, match="cannot use the same flag for true/false"): 1abcdefghij
106 typer.main.get_command(app) 1abcdefghij
109def test_option_error_hint() -> None: 1abcdefghij
110 app = typer.Typer() 1abcdefghij
112 @app.command() 1abcdefghij
113 def main(age: int = typer.Option(..., envvar="APP_NAME", show_envvar=True)): 1abcdefghij
114 pass # pragma: no cover
116 result = runner.invoke(app, ["--age", "not-int"]) 1abcdefghij
117 assert result.exit_code == 2 1abcdefghij
118 assert "(env var: 'APP_NAME')" in result.output 1abcdefghij
121def test_group_init() -> None: 1abcdefghij
122 group_no_commands = TyperGroup(name="root", commands=None) 1abcdefghij
123 assert group_no_commands.commands == {} 1abcdefghij
125 named = TyperCommand(name="named") 1abcdefghij
126 unnamed = TyperCommand(name=None) 1abcdefghij
127 group_command_sequence = TyperGroup(name="root", commands=[named, unnamed]) 1abcdefghij
128 assert group_command_sequence.commands == {"named": named} 1abcdefghij
131@pytest.mark.parametrize("with_result_callback", [False, True]) 1abcdefghij
132def test_group_result_callback(with_result_callback: bool) -> None: 1abcdefghij
133 called = {"child": False, "result_callback": False} 1abcdefghij
135 def child_callback() -> None: 1abcdefghij
136 called["child"] = True 1abcdefghij
137 return None 1abcdefghij
139 def result_callback(value, **kwargs): # type: ignore[no-untyped-def] 1abcdefghij
140 called["result_callback"] = True 1abcdefghij
141 return value 1abcdefghij
143 child = TyperCommand(name="child", callback=child_callback) 1abcdefghij
144 group = TyperGroup( 1abcdefghij
145 name="root",
146 commands={"child": child},
147 result_callback=result_callback if with_result_callback else None,
148 )
149 ctx = group.make_context("root", ["child"]) 1abcdefghij
151 result = group.invoke(ctx) 1abcdefghij
153 assert result is None 1abcdefghij
154 assert called["child"] is True 1abcdefghij
155 assert called["result_callback"] is with_result_callback 1abcdefghij
156 assert ctx.invoked_subcommand == "child" 1abcdefghij
159def test_group_add_command() -> None: 1abcdefghij
160 group = TyperGroup(name="root") 1abcdefghij
161 unnamed_command = TyperCommand(name=None) 1abcdefghij
163 with pytest.raises(TypeError, match="Command has no name."): 1abcdefghij
164 group.add_command(unnamed_command) 1abcdefghij
167def test_group_click_resolve_command() -> None: 1abcdefghij
168 child = TyperCommand(name="child") 1abcdefghij
169 group = TyperGroup(name="root", commands={"child": child}) 1abcdefghij
170 ctx = group.make_context("root", ["CHILD"], token_normalize_func=str.lower) 1abcdefghij
172 cmd_name, cmd, remaining = group._click_resolve_command(ctx, ["CHILD"]) 1abcdefghij
174 assert cmd_name == "child" 1abcdefghij
175 assert cmd is child 1abcdefghij
176 assert remaining == [] 1abcdefghij
179@pytest.mark.parametrize( 1abcdefghij
180 ("envvar", "auto_prefix", "set_env", "expected"),
181 [
182 ("APP_NAME", None, True, "my-precious"),
183 (None, "APP", True, "my-precious"),
184 (None, None, False, None),
185 ],
186)
187def test_option_resolve_envvar( 1abcdefghij
188 monkeypatch: pytest.MonkeyPatch,
189 envvar: str | None,
190 auto_prefix: str | None,
191 set_env: bool,
192 expected: str | None,
193) -> None:
194 context_settings = {"auto_envvar_prefix": auto_prefix} if auto_prefix else {} 1abcdefghij
195 app = typer.Typer(context_settings=context_settings) 1abcdefghij
197 @app.command() 1abcdefghij
198 def main(name: str = typer.Option("fallback", envvar=envvar)): 1abcdefghij
199 print(name) 1abcdefghij
201 if set_env: 1abcdefghij
202 monkeypatch.setenv("APP_NAME", "my-precious") 1abcdefghij
204 result = runner.invoke(app, []) 1abcdefghij
205 assert result.exit_code == 0 1abcdefghij
206 if expected is None: 1abcdefghij
207 assert "fallback" in result.stdout 1abcdefghij
208 else:
209 assert expected in result.stdout 1abcdefghij
212def test_option_resolve_envvar_list( 1abcdefghij
213 monkeypatch: pytest.MonkeyPatch,
214) -> None:
215 app = typer.Typer() 1abcdefghij
217 @app.command() 1abcdefghij
218 def main( 1abcdefghij
219 name: str = typer.Option("fallback", envvar=["APP_NAME_1", "APP_NAME_2"]),
220 ):
221 print(name) 1abcdefghij
223 monkeypatch.delenv("APP_NAME_1", raising=False) 1abcdefghij
224 monkeypatch.delenv("APP_NAME_2", raising=False) 1abcdefghij
226 result = runner.invoke(app, []) 1abcdefghij
227 assert result.exit_code == 0 1abcdefghij
228 assert "fallback" in result.stdout 1abcdefghij
231def test_context_auto_envvar() -> None: 1abcdefghij
232 app = typer.Typer(context_settings={"auto_envvar_prefix": "APP"}) 1abcdefghij
233 sub_app = typer.Typer() 1abcdefghij
235 @sub_app.command() 1abcdefghij
236 def clone(ctx: typer.Context) -> None: 1abcdefghij
237 print(ctx.auto_envvar_prefix) 1abcdefghij
239 app.add_typer(sub_app, name="beth") 1abcdefghij
241 result = runner.invoke(app, ["beth", "clone"]) 1abcdefghij
242 assert result.exit_code == 0 1abcdefghij
243 assert "APP_BETH_CLONE" in result.stdout 1abcdefghij
246def test_context_with_resource() -> None: 1abcdefghij
247 events: list[str] = [] 1abcdefghij
249 class DemoResource: 1abcdefghij
250 def __enter__(self) -> str: 1abcdefghij
251 events.append("enter") 1abcdefghij
252 return "pickle-rick" 1abcdefghij
254 def __exit__(self, *args: object) -> None: 1abcdefghij
255 events.append("exit") 1abcdefghij
257 app = typer.Typer() 1abcdefghij
259 @app.command() 1abcdefghij
260 def cmd(ctx: typer.Context) -> None: 1abcdefghij
261 value = ctx.with_resource(DemoResource()) 1abcdefghij
262 assert value == "pickle-rick" 1abcdefghij
263 assert events == ["enter"] 1abcdefghij
264 print("I'm a pickle") 1abcdefghij
266 result = runner.invoke(app) 1abcdefghij
268 assert result.exit_code == 0 1abcdefghij
269 assert "I'm a pickle" in result.stdout 1abcdefghij
270 assert events == ["enter", "exit"] 1abcdefghij
273def test_context_find_root() -> None: 1abcdefghij
274 app = typer.Typer() 1abcdefghij
275 sub_app = typer.Typer() 1abcdefghij
277 @sub_app.command() 1abcdefghij
278 def child(ctx: typer.Context) -> None: 1abcdefghij
279 root = ctx.find_root() 1abcdefghij
280 assert root.parent is None 1abcdefghij
281 assert root is ctx.parent.parent 1abcdefghij
282 print("ok") 1abcdefghij
284 app.add_typer(sub_app, name="sub") 1abcdefghij
286 result = runner.invoke(app, ["sub", "child"]) 1abcdefghij
287 assert result.exit_code == 0 1abcdefghij
288 assert "ok" in result.stdout 1abcdefghij
291def test_context_find_object() -> None: 1abcdefghij
292 class Marker: 1abcdefghij
293 pass 1abcdefghij
295 marker = Marker() 1abcdefghij
296 app = typer.Typer() 1abcdefghij
298 @app.callback() 1abcdefghij
299 def callback(ctx: typer.Context) -> None: 1abcdefghij
300 ctx.obj = marker 1abcdefghij
302 @app.command() 1abcdefghij
303 def child(ctx: typer.Context) -> None: 1abcdefghij
304 assert ctx.find_object(Marker) is marker 1abcdefghij
305 assert ctx.find_object(str) is None 1abcdefghij
306 print("ok") 1abcdefghij
308 result = runner.invoke(app, ["child"]) 1abcdefghij
309 assert result.exit_code == 0 1abcdefghij
310 assert "ok" in result.stdout 1abcdefghij
313def test_context_lookup_default_callable() -> None: 1abcdefghij
314 app = typer.Typer() 1abcdefghij
316 @app.command() 1abcdefghij
317 def child(ctx: typer.Context) -> None: 1abcdefghij
318 ctx.default_map = {"planet": lambda: "Earth"} 1abcdefghij
319 assert ctx.lookup_default("planet") == "Earth" 1abcdefghij
320 value = ctx.lookup_default("planet", call=False) 1abcdefghij
321 assert callable(value) 1abcdefghij
322 print("ok") 1abcdefghij
324 result = runner.invoke(app) 1abcdefghij
325 assert result.exit_code == 0 1abcdefghij
326 assert "ok" in result.stdout 1abcdefghij
329def test_context_abort() -> None: 1abcdefghij
330 app = typer.Typer() 1abcdefghij
332 @app.command() 1abcdefghij
333 def cmd(ctx: typer.Context) -> None: 1abcdefghij
334 ctx.abort() 1abcdefghij
336 result = runner.invoke(app, standalone_mode=False) 1abcdefghij
337 assert result.exit_code == 1 1abcdefghij
338 assert isinstance(result.exception, _click.core.Abort) 1abcdefghij
341def test_command_help_disabled() -> None: 1abcdefghij
342 app = typer.Typer() 1abcdefghij
344 @app.command(add_help_option=False) 1abcdefghij
345 def cmd() -> None: 1abcdefghij
346 pass # pragma: no cover
348 result = runner.invoke(app, ["--help"], standalone_mode=False) 1abcdefghij
349 assert result.exit_code == 1 1abcdefghij
350 assert isinstance(result.exception, _click.exceptions.NoSuchOption) 1abcdefghij
351 assert result.exception.option_name == "--help" 1abcdefghij
354def test_command_help_deprecated() -> None: 1abcdefghij
355 app = typer.Typer(rich_markup_mode=None, epilog="Built with love") 1abcdefghij
357 @app.command(short_help="Shorty", help="Regular help text.", deprecated=True) 1abcdefghij
358 def one() -> None: 1abcdefghij
359 pass # pragma: no cover
361 @app.command() 1abcdefghij
362 def two() -> None: 1abcdefghij
363 pass # pragma: no cover
365 result = runner.invoke(app, ["one", "--help"]) 1abcdefghij
366 assert result.exit_code == 0 1abcdefghij
367 assert "Regular help text. (DEPRECATED)" in result.output 1abcdefghij
369 result = runner.invoke(app, ["--help"]) 1abcdefghij
370 assert result.exit_code == 0 1abcdefghij
371 assert "Built with love" in result.output 1abcdefghij
372 assert "oneShorty(DEPRECATED)" in result.output.replace(" ", "") 1abcdefghij
375@pytest.mark.parametrize( 1abcdefghij
376 ("value", "expected_prefix", "expected_opt"),
377 [
378 ("--verbose", "--", "verbose"),
379 ("//verbose", "//", "verbose"),
380 ("-verbose", "-", "verbose"),
381 ("verbose", "", "verbose"),
382 ],
383)
384def test_split_opt(value: str, expected_prefix: str, expected_opt: str) -> None: 1abcdefghij
385 prefix, opt = _split_opt(value) 1abcdefghij
386 assert prefix == expected_prefix 1abcdefghij
387 assert opt == expected_opt 1abcdefghij
390def test_nargs_default_map(): 1abcdefghij
391 app = typer.Typer() 1abcdefghij
393 @app.command() 1abcdefghij
394 def main(names: list[str] = typer.Option(None)): 1abcdefghij
395 print(names) # pragma: no cover
397 result = runner.invoke(app, [], default_map={"names": "not-a-list"}) 1abcdefghij
398 assert result.exit_code == 2 1abcdefghij
399 assert "Invalid value" in result.output 1abcdefghij
402def test_parameter_name_casing(): 1abcdefghij
403 app = typer.Typer() 1abcdefghij
405 @app.command() 1abcdefghij
406 def main( 1abcdefghij
407 arg1: int,
408 arg2: int = 42,
409 arg3: int = typer.Argument(...),
410 ARG4: int = typer.Argument(42),
411 ARG5: int = typer.Option(...),
412 arg6: int = typer.Option(42),
413 arg7: int = typer.Argument(42, metavar="meta7"),
414 arg8: int = typer.Argument(metavar="ARG8"),
415 arg9: int = typer.Option(metavar="ARG9"),
416 ):
417 print( 1abcdefghij
418 f"arg1={arg1} arg2={arg2} arg3={arg3} ARG4={ARG4} ARG5={ARG5} "
419 f"arg6={arg6} arg7={arg7} arg8={arg8} arg9={arg9}"
420 )
422 result = runner.invoke( 1abcdefghij
423 app,
424 [
425 "1",
426 "3",
427 "4",
428 "7",
429 "8",
430 "--arg2",
431 "2",
432 "--ARG5",
433 "5",
434 "--arg6",
435 "6",
436 "--arg9",
437 "9",
438 ],
439 )
440 print(result.output) 1abcdefghij
441 print(result.stderr) 1abcdefghij
442 assert result.exit_code == 0 1abcdefghij
443 assert ( 1abcdefghij
444 "arg1=1 arg2=2 arg3=3 ARG4=4 ARG5=5 arg6=6 arg7=7 arg8=8 arg9=9"
445 in result.output
446 )
448 result = runner.invoke(app, ["1", "3", "4", "7", "8", "--ARG5", "5", "--arg9", "9"]) 1abcdefghij
449 assert result.exit_code == 0 1abcdefghij
450 assert ( 1abcdefghij
451 "arg1=1 arg2=42 arg3=3 ARG4=4 ARG5=5 arg6=42 arg7=7 arg8=8 arg9=9"
452 in result.output
453 )
455 result = runner.invoke(app, ["1", "3", "4", "7", "8", "--arg5", "5", "--arg9", "9"]) 1abcdefghij
456 assert result.exit_code != 0 1abcdefghij
457 assert "No such option: --arg5" in result.output 1abcdefghij
459 result = runner.invoke(app, ["1", "3", "4", "7", "8", "--ARG5", "5", "--ARG9", "9"]) 1abcdefghij
460 assert result.exit_code != 0 1abcdefghij
461 assert "No such option: --ARG9" in result.output 1abcdefghij