Coverage for tests/test_annotated.py: 100%

54 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 18:26 +0000

1import typer 1habfcgde

2from typer.testing import CliRunner 1habfcgde

3from typing_extensions import Annotated 1habfcgde

4 

5from .utils import needs_py310 1habfcgde

6 

7runner = CliRunner() 1habfcgde

8 

9 

10def test_annotated_argument_with_default(): 1habfcgde

11 app = typer.Typer() 1habfcgde

12 

13 @app.command() 1habfcgde

14 def cmd(val: Annotated[int, typer.Argument()] = 0): 1habfcgde

15 print(f"hello {val}") 1habfcgde

16 

17 result = runner.invoke(app) 1habfcgde

18 assert result.exit_code == 0, result.output 1habfcgde

19 assert "hello 0" in result.output 1habfcgde

20 

21 result = runner.invoke(app, ["42"]) 1habfcgde

22 assert result.exit_code == 0, result.output 1habfcgde

23 assert "hello 42" in result.output 1habfcgde

24 

25 

26@needs_py310 1habfcgde

27def test_annotated_argument_in_string_type_with_default(): 1abfcgde

28 app = typer.Typer() 1abcde

29 

30 @app.command() 1abcde

31 def cmd(val: "Annotated[int, typer.Argument()]" = 0): 1abcde

32 print(f"hello {val}") 1abcde

33 

34 result = runner.invoke(app) 1abcde

35 assert result.exit_code == 0, result.output 1abcde

36 assert "hello 0" in result.output 1abcde

37 

38 result = runner.invoke(app, ["42"]) 1abcde

39 assert result.exit_code == 0, result.output 1abcde

40 assert "hello 42" in result.output 1abcde

41 

42 

43def test_annotated_argument_with_default_factory(): 1habfcgde

44 app = typer.Typer() 1habfcgde

45 

46 def make_string(): 1habfcgde

47 return "I made it" 1habfcgde

48 

49 @app.command() 1habfcgde

50 def cmd(val: Annotated[str, typer.Argument(default_factory=make_string)]): 1habfcgde

51 print(val) 1habfcgde

52 

53 result = runner.invoke(app) 1habfcgde

54 assert result.exit_code == 0, result.output 1habfcgde

55 assert "I made it" in result.output 1habfcgde

56 

57 result = runner.invoke(app, ["overridden"]) 1habfcgde

58 assert result.exit_code == 0, result.output 1habfcgde

59 assert "overridden" in result.output 1habfcgde

60 

61 

62def test_annotated_option_with_argname_doesnt_mutate_multiple_calls(): 1habfcgde

63 app = typer.Typer() 1habfcgde

64 

65 @app.command() 1habfcgde

66 def cmd(force: Annotated[bool, typer.Option("--force")] = False): 1habfcgde

67 if force: 1habfcgde

68 print("Forcing operation") 1habfcgde

69 else: 

70 print("Not forcing") 1habfcgde

71 

72 result = runner.invoke(app) 1habfcgde

73 assert result.exit_code == 0, result.output 1habfcgde

74 assert "Not forcing" in result.output 1habfcgde

75 

76 result = runner.invoke(app, ["--force"]) 1habfcgde

77 assert result.exit_code == 0, result.output 1habfcgde

78 assert "Forcing operation" in result.output 1habfcgde