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

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

8 

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

17 

18from .utils import requires_completion_permission 1abcdefghij

19 

20runner = CliRunner() 1abcdefghij

21 

22 

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

27 

28 

29def test_defaults_from_info(): 1abcdefghij

30 # Mainly for coverage/completeness 

31 value = solve_typer_info_defaults(TyperInfo()) 1abcdefghij

32 assert value 1abcdefghij

33 

34 

35@requires_completion_permission 1abcdefghij

36def test_install_invalid_shell(): 1abcdefghij

37 app = typer.Typer() 1abcdefghij

38 

39 @app.command() 1abcdefghij

40 def main(): 1abcdefghij

41 print("Hello World") 1abcdefghij

42 

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

50 

51 

52def test_callback_too_many_parameters(): 1abcdefghij

53 app = typer.Typer() 1abcdefghij

54 

55 def name_callback(ctx, param, val1, val2): 1abcdefghij

56 pass # pragma: no cover 

57 

58 @app.command() 1abcdefghij

59 def main(name: str = typer.Option(..., callback=name_callback)): 1abcdefghij

60 pass # pragma: no cover 

61 

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 ) 

67 

68 

69def test_callback_2_untyped_parameters(): 1abcdefghij

70 app = typer.Typer() 1abcdefghij

71 

72 def name_callback(ctx, value): 1abcdefghij

73 print(f"info name is: {ctx.info_name}") 1abcdefghij

74 print(f"value is: {value}") 1abcdefghij

75 

76 @app.command() 1abcdefghij

77 def main(name: str = typer.Option(..., callback=name_callback)): 1abcdefghij

78 print("Hello World") 1abcdefghij

79 

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

83 

84 

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

96 

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

100 

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 

104 

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

109 

110 

111def test_bad_parameter_main() -> None: 1abcdefghij

112 app = typer.Typer() 1abcdefghij

113 

114 @app.command() 1abcdefghij

115 def main() -> None: 1abcdefghij

116 raise typer.BadParameter("custom validation failed") 1abcdefghij

117 

118 result = runner.invoke(app, []) 1abcdefghij

119 assert result.exit_code == 2 1abcdefghij

120 assert "Invalid value: custom validation failed" in result.stderr 1abcdefghij

121 

122 

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

135 

136 @app.command() 1abcdefghij

137 def main() -> None: 1abcdefghij

138 raise typer._click.exceptions.MissingParameter(**kw) 1abcdefghij

139 

140 result = runner.invoke(app, []) 1abcdefghij

141 assert result.exit_code == 2 1abcdefghij

142 assert msg in result.stderr 1abcdefghij

143 

144 

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 ) 

150 

151 app = typer.Typer(rich_markup_mode=None) 1abcdefghij

152 

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 

161 

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

171 

172 

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

176 

177 app = typer.Typer() 1abcdefghij

178 

179 @app.command() 1abcdefghij

180 def main(mode: str = typer.Option(..., "--mode", callback=my_cb)) -> None: 1abcdefghij

181 typer.echo(mode) # pragma: no cover 

182 

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

186 

187 

188def test_click_exception_show_default_file() -> None: 1abcdefghij

189 app = typer.Typer(rich_markup_mode=None) 1abcdefghij

190 

191 @app.command() 1abcdefghij

192 def main() -> None: 1abcdefghij

193 raise typer._click.ClickException("custom click failure") 1abcdefghij

194 

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

199 

200 

201def test_no_args_is_help_show() -> None: 1abcdefghij

202 app = typer.Typer(rich_markup_mode=None) 1abcdefghij

203 

204 @app.callback(invoke_without_command=True, no_args_is_help=True) 1abcdefghij

205 def main() -> None: 1abcdefghij

206 return None # pragma: no cover 

207 

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

212 

213 

214def test_callback_3_untyped_parameters(): 1abcdefghij

215 app = typer.Typer() 1abcdefghij

216 

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

221 

222 @app.command() 1abcdefghij

223 def main(name: str = typer.Option(..., callback=name_callback)): 1abcdefghij

224 print("Hello World") 1abcdefghij

225 

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

230 

231 

232def test_callback_4_list_none(): 1abcdefghij

233 app = typer.Typer() 1abcdefghij

234 

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

239 

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

248 

249 result = runner.invoke(app, ["--name", "Sideshow", "--name", "Bob"]) 1abcdefghij

250 assert "Hello SIDESHOW, BOB" in result.stdout 1abcdefghij

251 

252 result = runner.invoke(app, []) 1abcdefghij

253 assert "Hello World" in result.stdout 1abcdefghij

254 

255 

256def test_multiple_bool_flags() -> None: 1abcdefghij

257 app = typer.Typer() 1abcdefghij

258 

259 @app.command() 1abcdefghij

260 def main(choices: list[bool] = typer.Option([], "--accept/--reject")) -> None: 1abcdefghij

261 print(choices) 1abcdefghij

262 

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

266 

267 

268def test_empty_list_default_generator(): 1abcdefghij

269 def empty_list() -> list[str]: 1abcdefghij

270 return [] 1abcdefghij

271 

272 app = typer.Typer() 1abcdefghij

273 

274 @app.command() 1abcdefghij

275 def main( 1abcdefghij

276 names: Annotated[list[str], typer.Option(default_factory=empty_list)], 

277 ): 

278 print(names) 1abcdefghij

279 

280 result = runner.invoke(app) 1abcdefghij

281 assert "[]" in result.output 1abcdefghij

282 

283 

284def test_option_envvar(): 1abcdefghij

285 app = typer.Typer() 1abcdefghij

286 

287 @app.command() 1abcdefghij

288 def main(user: Annotated[str, typer.Option(envvar="ME")]): 1abcdefghij

289 print(f"Hello {user}") 1abcdefghij

290 

291 result = runner.invoke(app, env={"ME": "rick"}) 1abcdefghij

292 assert result.exit_code == 0 1abcdefghij

293 assert "Hello rick" in result.output 1abcdefghij

294 

295 

296def test_option_envvar_list(): 1abcdefghij

297 app = typer.Typer() 1abcdefghij

298 

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

303 

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

308 

309 

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

316 

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

320 

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

324 

325 

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

332 

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

336 

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

340 

341 

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

350 

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

358 

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

362 

363 

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

381 

382 

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

400 

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

407 

408 

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

426 

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

433 

434 

435def test_autocompletion_too_many_parameters(): 1abcdefghij

436 app = typer.Typer() 1abcdefghij

437 

438 def name_callback(ctx, args, incomplete, val2): 1abcdefghij

439 pass # pragma: no cover 

440 

441 @app.command() 1abcdefghij

442 def main(name: str = typer.Option(..., autocompletion=name_callback)): 1abcdefghij

443 pass # pragma: no cover 

444 

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

448 

449 

450def test_forward_references(): 1abcdefghij

451 app = typer.Typer() 1abcdefghij

452 

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

460 

461 result = runner.invoke(app, ["Hello", "2", "invalid"]) 1abcdefghij

462 

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 ) 

470 

471 

472def test_context_settings_inheritance_single_command(): 1abcdefghij

473 app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}) 1abcdefghij

474 

475 @app.command() 1abcdefghij

476 def main(name: str): 1abcdefghij

477 pass # pragma: no cover 

478 

479 result = runner.invoke(app, ["main", "-h"]) 1abcdefghij

480 assert "Show this message and exit." in result.stdout 1abcdefghij

481 

482 

483def test_options_metadata_typer_default(): 1abcdefghij

484 app = typer.Typer(options_metavar="[options]") 1abcdefghij

485 

486 @app.command() 1abcdefghij

487 def c1(): 1abcdefghij

488 pass # pragma: no cover 

489 

490 @app.command(options_metavar="[OPTS]") 1abcdefghij

491 def c2(): 1abcdefghij

492 pass # pragma: no cover 

493 

494 result = runner.invoke(app, ["c1", "--help"]) 1abcdefghij

495 assert "Usage: root c1 [options]" in result.stdout 1abcdefghij

496 

497 result = runner.invoke(app, ["c2", "--help"]) 1abcdefghij

498 assert "Usage: root c2 [OPTS]" in result.stdout 1abcdefghij