Coverage for tests / test_coercion.py: 100%

155 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-11-18 11:12 +0000

1import os 1abcdefghij

2from pathlib import Path 1abcdefghij

3 

4import pytest 1abcdefghij

5import typer 1abcdefghij

6from typer.core import _TyperParameter 1abcdefghij

7from typer.testing import CliRunner 1abcdefghij

8 

9runner = CliRunner() 1abcdefghij

10 

11 

12def test_coercion() -> None: 1abcdefghij

13 app = typer.Typer() 1abcdefghij

14 seen: dict[str, object] = {} 1abcdefghij

15 

16 @app.command() 1abcdefghij

17 def main(items: list[int], active: bool = False, val=42): 1abcdefghij

18 seen["items"] = items 1abcdefghij

19 seen["active"] = active 1abcdefghij

20 seen["val"] = val 1abcdefghij

21 

22 result = runner.invoke(app, ["1", "2", "--active", "--val", "7"]) 1abcdefghij

23 assert result.exit_code == 0, result.output 1abcdefghij

24 assert seen == {"items": [1, 2], "active": True, "val": 7} 1abcdefghij

25 

26 

27def test_coercion_invalid() -> None: 1abcdefghij

28 app = typer.Typer() 1abcdefghij

29 

30 @app.command() 1abcdefghij

31 def main(age: int): 1abcdefghij

32 pass # pragma: no cover 

33 

34 result = runner.invoke(app, ["not-an-int"]) 1abcdefghij

35 assert "Input should be a valid integer" in result.stderr 1abcdefghij

36 assert result.exit_code == 2 1abcdefghij

37 

38 

39def test_coercion_path(tmp_path: Path) -> None: 1abcdefghij

40 target = tmp_path / "config.txt" 1abcdefghij

41 target.write_text("hello\n", encoding="utf-8") 1abcdefghij

42 app = typer.Typer() 1abcdefghij

43 seen: list[Path] = [] 1abcdefghij

44 

45 @app.command() 1abcdefghij

46 def main(config: Path = typer.Option(..., exists=True)): 1abcdefghij

47 seen.append(config) 1abcdefghij

48 

49 result = runner.invoke(app, ["--config", str(target)]) 1abcdefghij

50 assert result.exit_code == 0 1abcdefghij

51 assert seen == [target] 1abcdefghij

52 

53 

54def test_coercion_tuple_files(tmp_path: Path) -> None: 1abcdefghij

55 first = tmp_path / "first.txt" 1abcdefghij

56 second = tmp_path / "second.txt" 1abcdefghij

57 first.write_text("first-content\n", encoding="utf-8") 1abcdefghij

58 second.write_text("second-content\n", encoding="utf-8") 1abcdefghij

59 app = typer.Typer() 1abcdefghij

60 seen: list[str] = [] 1abcdefghij

61 

62 @app.command() 1abcdefghij

63 def main(files: tuple[typer.FileText, typer.FileText]): 1abcdefghij

64 seen.append(files[0].read()) 1abcdefghij

65 seen.append(files[1].read()) 1abcdefghij

66 

67 result = runner.invoke(app, [str(first), str(second)]) 1abcdefghij

68 assert result.exit_code == 0, result.output 1abcdefghij

69 assert seen == ["first-content\n", "second-content\n"] 1abcdefghij

70 

71 

72def test_coercion_tuple_file_modes(tmp_path: Path) -> None: 1abcdefghij

73 """Ensure that each file gets the correct mode (edge case for bwd-compat)""" 

74 read_file = tmp_path / "read.txt" 1abcdefghij

75 write_file = tmp_path / "write.bin" 1abcdefghij

76 read_file.write_text("hello\n", encoding="utf-8") 1abcdefghij

77 app = typer.Typer() 1abcdefghij

78 seen: dict[str, object] = {} 1abcdefghij

79 

80 @app.command() 1abcdefghij

81 def main(files: tuple[typer.FileText, typer.FileBinaryWrite]): 1abcdefghij

82 seen["text"] = files[0].read() 1abcdefghij

83 files[1].write(b"world") 1abcdefghij

84 files[1].close() 1abcdefghij

85 

86 result = runner.invoke(app, [str(read_file), str(write_file)]) 1abcdefghij

87 assert result.exit_code == 0, result.output 1abcdefghij

88 assert seen["text"] == "hello\n" 1abcdefghij

89 assert write_file.read_bytes() == b"world" 1abcdefghij

90 

91 

92def test_coercion_tuple_file_and_int(tmp_path: Path) -> None: 1abcdefghij

93 """Ensure that each tuple element is parsed correctly (edge case for bwd-compat)""" 

94 some_file = tmp_path / "f.txt" 1abcdefghij

95 some_file.write_text("content\n", encoding="utf-8") 1abcdefghij

96 app = typer.Typer() 1abcdefghij

97 seen: dict[str, object] = {} 1abcdefghij

98 

99 @app.command() 1abcdefghij

100 def main(files: tuple[int, typer.FileText]): 1abcdefghij

101 seen["count"] = files[0] 1abcdefghij

102 seen["text"] = files[1].read() 1abcdefghij

103 

104 result = runner.invoke(app, ["42", str(some_file)]) 1abcdefghij

105 assert result.exit_code == 0, result.output 1abcdefghij

106 assert seen["count"] == 42 1abcdefghij

107 assert seen["text"] == "content\n" 1abcdefghij

108 

109 result = runner.invoke(app, ["nope", str(some_file)]) 1abcdefghij

110 assert result.exit_code == 2 1abcdefghij

111 assert "Input should be a valid integer" in result.output 1abcdefghij

112 

113 

114def test_list_rejects_none() -> None: 1abcdefghij

115 app = typer.Typer() 1abcdefghij

116 

117 @app.command() 1abcdefghij

118 def main(items: list[int] = typer.Option([1, None])): 1abcdefghij

119 pass # pragma: no cover 

120 

121 result = runner.invoke(app) 1abcdefghij

122 assert "Invalid value for '--items'" in result.stderr 1abcdefghij

123 assert "Input should be a valid integer" in result.stderr 1abcdefghij

124 assert result.exit_code == 2 1abcdefghij

125 

126 

127def test_tuple_rejects_none() -> None: 1abcdefghij

128 app = typer.Typer() 1abcdefghij

129 

130 @app.command() 1abcdefghij

131 def main(pair: tuple[int, str] = (1, None)): 1abcdefghij

132 pass # pragma: no cover 

133 

134 help_result = runner.invoke(app, ["--help"]) 1abcdefghij

135 assert help_result.exit_code == 0 1abcdefghij

136 assert "[default: 1, None]" in help_result.output 1abcdefghij

137 

138 result = runner.invoke(app) 1abcdefghij

139 assert "Invalid value for '--pair'" in result.stderr 1abcdefghij

140 assert "None is not a valid string" in result.stderr 1abcdefghij

141 assert result.exit_code == 2 1abcdefghij

142 

143 

144def test_passthrough_runtime_param_default() -> None: 1abcdefghij

145 class Widget: 1abcdefghij

146 def __init__(self, value: int) -> None: 1abcdefghij

147 self.value = value 1abcdefghij

148 

149 app = typer.Typer() 1abcdefghij

150 seen: dict[str, Widget] = {} 1abcdefghij

151 

152 @app.command() 1abcdefghij

153 def main(val=Widget(42)): 1abcdefghij

154 seen["val"] = val 1abcdefghij

155 

156 param = next(p for p in typer.main.get_command(app).params if p.name == "val") 1abcdefghij

157 assert isinstance(param, _TyperParameter) 1abcdefghij

158 assert param.get_runtime_param() is not None 1abcdefghij

159 assert param.get_runtime_param().annotation is Widget 1abcdefghij

160 

161 result = runner.invoke(app) 1abcdefghij

162 assert result.exit_code == 0 1abcdefghij

163 assert isinstance(seen["val"], Widget) 1abcdefghij

164 assert seen["val"].value == 42 1abcdefghij

165 

166 result = runner.invoke(app, ["--val", "666"]) 1abcdefghij

167 assert result.exit_code == 2 1abcdefghij

168 # This doesn't work because there's no parser 

169 assert "is not a valid Widget" in result.output 1abcdefghij

170 

171 

172def test_widget_parsed_from_cli_with_parser() -> None: 1abcdefghij

173 class Widget: 1abcdefghij

174 def __init__(self, value: int) -> None: 1abcdefghij

175 self.value = value 1abcdefghij

176 

177 def parse_widget(value: str) -> Widget: 1abcdefghij

178 return Widget(int(value)) 1abcdefghij

179 

180 app = typer.Typer() 1abcdefghij

181 seen: dict[str, Widget] = {} 1abcdefghij

182 

183 @app.command() 1abcdefghij

184 def main(val: Widget = typer.Option("42", parser=parse_widget)): 1abcdefghij

185 seen["val"] = val 1abcdefghij

186 

187 param = next(p for p in typer.main.get_command(app).params if p.name == "val") 1abcdefghij

188 assert isinstance(param, _TyperParameter) 1abcdefghij

189 assert param.get_runtime_param() is not None 1abcdefghij

190 assert param.get_runtime_param().annotation is Widget 1abcdefghij

191 

192 result = runner.invoke(app) 1abcdefghij

193 assert result.exit_code == 0 1abcdefghij

194 assert isinstance(seen["val"], Widget) 1abcdefghij

195 assert seen["val"].value == 42 1abcdefghij

196 

197 result = runner.invoke(app, ["--val", "666"]) 1abcdefghij

198 assert result.exit_code == 0 1abcdefghij

199 assert isinstance(seen["val"], Widget) 1abcdefghij

200 assert seen["val"].value == 666 1abcdefghij

201 

202 

203def test_plugin_when_previously_unset( 1abcdefghij

204 monkeypatch: pytest.MonkeyPatch, 

205) -> None: 

206 from typer._adapters import disabled_pydantic_plugins 1abcdefghij

207 

208 monkeypatch.delenv("PYDANTIC_DISABLE_PLUGINS", raising=False) 1abcdefghij

209 with disabled_pydantic_plugins(): 1abcdefghij

210 assert os.environ["PYDANTIC_DISABLE_PLUGINS"] == "1" 1abcdefghij

211 assert "PYDANTIC_DISABLE_PLUGINS" not in os.environ 1abcdefghij

212 

213 

214def test_plugin_when_previously_set( 1abcdefghij

215 monkeypatch: pytest.MonkeyPatch, 

216) -> None: 

217 from typer._adapters import disabled_pydantic_plugins 1abcdefghij

218 

219 monkeypatch.setenv("PYDANTIC_DISABLE_PLUGINS", "0") 1abcdefghij

220 with disabled_pydantic_plugins(): 1abcdefghij

221 assert os.environ["PYDANTIC_DISABLE_PLUGINS"] == "1" 1abcdefghij

222 assert os.environ["PYDANTIC_DISABLE_PLUGINS"] == "0" 1abcdefghij