Coverage for tests / test_termui.py: 100%

296 statements  

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

1""" 

2Tests for the termui, echo, and CliRunner isolation functionality. 

3Created after vendoring Click to ensure test coverage is back up to 100%. 

4""" 

5 

6import io 1abcdhijefg

7import os 1abcdhijefg

8from contextlib import contextmanager 1abcdhijefg

9from typing import Literal 1abcdhijefg

10 

11import pytest 1abcdhijefg

12import typer 1abcdhijefg

13from typer._click import _termui_impl, termui 1abcdhijefg

14from typer.testing import CliRunner 1abcdhijefg

15 

16from tests.utils import needs_windows, skip_if_windows 1abcdhijefg

17 

18 

19def test_raw_terminal(monkeypatch): 1abcdhijefg

20 runner = CliRunner() 1abcdhijefg

21 app = typer.Typer() 1abcdhijefg

22 state = {"entered": 0, "exited": 0} 1abcdhijefg

23 

24 @contextmanager 1abcdhijefg

25 def fake_raw_terminal(): 1abcdhijefg

26 state["entered"] += 1 1abcdhijefg

27 try: 1abcdhijefg

28 yield 42 1abcdhijefg

29 finally: 

30 state["exited"] += 1 1abcdhijefg

31 

32 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw_terminal) 1abcdhijefg

33 

34 @app.command() 1abcdhijefg

35 def main(): 1abcdhijefg

36 with termui.raw_terminal() as fd: 1abcdhijefg

37 typer.echo(f"fd={fd}") 1abcdhijefg

38 

39 result = runner.invoke(app, []) 1abcdhijefg

40 assert result.exit_code == 0, result.output 1abcdhijefg

41 assert "fd=42" in result.stdout 1abcdhijefg

42 assert state["entered"] == 1 1abcdhijefg

43 assert state["exited"] == 1 1abcdhijefg

44 

45 

46def test_getchar(monkeypatch): 1abcdhijefg

47 # Cached path: call the existing _getchar directly. 

48 cached_state = {"echo": None} 1abcdhijefg

49 

50 def cached_getchar(echo: bool) -> str: 1abcdhijefg

51 cached_state["echo"] = echo 1abcdhijefg

52 return "x" 1abcdhijefg

53 

54 monkeypatch.setattr(termui, "_getchar", cached_getchar) 1abcdhijefg

55 assert termui.getchar(echo=True) == "x" 1abcdhijefg

56 assert cached_state["echo"] is True 1abcdhijefg

57 

58 # Lazy-load path: _getchar is None, so import/cache _termui_impl.getchar. 

59 lazy_state = {"calls": 0} 1abcdhijefg

60 

61 def lazy_getchar(echo: bool) -> str: 1abcdhijefg

62 lazy_state["calls"] += 1 1abcdhijefg

63 return "y" if not echo else "z" 1abcdhijefg

64 

65 monkeypatch.setattr(termui, "_getchar", None) 1abcdhijefg

66 monkeypatch.setattr(_termui_impl, "getchar", lazy_getchar) 1abcdhijefg

67 

68 assert termui.getchar(echo=False) == "y" 1abcdhijefg

69 assert termui._getchar is lazy_getchar 1abcdhijefg

70 assert termui.getchar(echo=True) == "z" 1abcdhijefg

71 assert lazy_state["calls"] == 2 1abcdhijefg

72 

73 

74def test_clirunner_getchar(monkeypatch) -> None: 1abcdhijefg

75 runner = CliRunner() 1abcdhijefg

76 app = typer.Typer() 1abcdhijefg

77 

78 @app.command() 1abcdhijefg

79 def main() -> None: 1abcdhijefg

80 first = termui.getchar(echo=False) 1abcdhijefg

81 second = termui.getchar(echo=True) 1abcdhijefg

82 typer.echo(f"\nfirst={first};second={second}") 1abcdhijefg

83 

84 monkeypatch.setattr(termui, "_getchar", None) 1abcdhijefg

85 result = runner.invoke(app, [], input="ab") 1abcdhijefg

86 assert result.exit_code == 0, result.output 1abcdhijefg

87 assert result.stdout.splitlines() == ["b", "first=a;second=b"] 1abcdhijefg

88 

89 

90def test_clirunner_env_none(monkeypatch) -> None: 1abcdhijefg

91 runner = CliRunner() 1abcdhijefg

92 app = typer.Typer() 1abcdhijefg

93 env_key = "TYPER_TEST_ENV_REMOVE" 1abcdhijefg

94 monkeypatch.setenv(env_key, "present") 1abcdhijefg

95 

96 @app.command() 1abcdhijefg

97 def main() -> None: 1abcdhijefg

98 typer.echo(f"inside={os.environ.get(env_key)}") 1abcdhijefg

99 

100 result = runner.invoke(app, [], env={env_key: None}) 1abcdhijefg

101 assert result.exit_code == 0, result.output 1abcdhijefg

102 assert "inside=None" in result.stdout 1abcdhijefg

103 assert os.environ.get(env_key) == "present" 1abcdhijefg

104 

105 

106@pytest.mark.parametrize( 1abcdhijefg

107 ("exit_value", "expected_exit_code", "expected_stdout"), 

108 [ 

109 (None, 0, ""), 

110 ("bad-exit", 1, "bad-exit\n"), 

111 ], 

112) 

113def test_clirunner_invoke_system_exit_branches( 1abcdhijefg

114 exit_value: object, 

115 expected_exit_code: int, 

116 expected_stdout: str, 

117) -> None: 

118 runner = CliRunner() 1abcdhijefg

119 app = typer.Typer() 1abcdhijefg

120 

121 @app.command() 1abcdhijefg

122 def main() -> None: 1abcdhijefg

123 raise SystemExit(exit_value) 1abcdhijefg

124 

125 result = runner.invoke(app, []) 1abcdhijefg

126 assert result.exit_code == expected_exit_code 1abcdhijefg

127 assert result.stdout == expected_stdout 1abcdhijefg

128 if expected_exit_code: 1abcdhijefg

129 assert isinstance(result.exception, SystemExit) 1abcdhijefg

130 else: 

131 assert result.exception is None 1abcdhijefg

132 

133 

134@needs_windows 1abcdhijefg

135def test_termui_impl_windows_raw_terminal(): 1abcdhijefg

136 with _termui_impl.raw_terminal() as fd: 1hij

137 assert fd == -1 1hij

138 with termui.raw_terminal() as fd: 1hij

139 assert fd == -1 1hij

140 

141 

142@needs_windows 1abcdhijefg

143def test_termui_impl_windows_getchar(monkeypatch): 1abcdhijefg

144 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "a") 1hij

145 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: "b") 1hij

146 assert _termui_impl.getchar(echo=False) == "a" 1hij

147 assert _termui_impl.getchar(echo=True) == "b" 1hij

148 

149 seq_null = iter(["\x00", "K"]) 1hij

150 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_null)) 1hij

151 assert _termui_impl.getchar(echo=False) == "\x00K" 1hij

152 

153 seq_e0 = iter(["\xe0", "H"]) 1hij

154 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_e0)) 1hij

155 assert _termui_impl.getchar(echo=False) == "\xe0H" 1hij

156 

157 seq_echo = iter(["\x00", "M"]) 1hij

158 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_echo)) 1hij

159 assert _termui_impl.getchar(echo=True) == "\x00M" 1hij

160 

161 seq_e0_echo = iter(["\xe0", "Z"]) 1hij

162 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_e0_echo)) 1hij

163 assert _termui_impl.getchar(echo=True) == "\xe0Z" 1hij

164 

165 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x03") 1hij

166 with pytest.raises(KeyboardInterrupt): 1hij

167 _termui_impl.getchar(echo=False) 1hij

168 

169 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x1a") 1hij

170 with pytest.raises(EOFError): 1hij

171 _termui_impl.getchar(echo=False) 1hij

172 

173 

174@skip_if_windows 1abcdhijefg

175@pytest.mark.parametrize("use_stdin_tty", [True, False]) 1abcdhijefg

176def test_termui_impl_posix_raw_terminal(monkeypatch, use_stdin_tty: bool): 1abcdhijefg

177 state: dict[str, object] = {} 1abcdefg

178 flushed: list[None] = [] 1abcdefg

179 fake_tty = None 1abcdefg

180 

181 if use_stdin_tty: 1abcdefg

182 expected_fd = 14 1abcdefg

183 old_termios = "old_settings" 1abcdefg

184 monkeypatch.setattr( 1abcdefg

185 _termui_impl, "isatty", lambda s: s is _termui_impl.sys.stdin 

186 ) 

187 monkeypatch.setattr(_termui_impl.sys.stdin, "fileno", lambda: expected_fd) 1abcdefg

188 else: 

189 expected_fd = 27 1abcdefg

190 old_termios = "old" 1abcdefg

191 monkeypatch.setattr( 1abcdefg

192 _termui_impl, 

193 "isatty", 

194 lambda s: s is not _termui_impl.sys.stdin, 

195 ) 

196 

197 class FakeTTY: 1abcdefg

198 def __init__(self) -> None: 1abcdefg

199 self.closed = False 1abcdefg

200 

201 def fileno(self) -> int: 1abcdefg

202 return expected_fd 1abcdefg

203 

204 def close(self) -> None: 1abcdefg

205 self.closed = True 1abcdefg

206 

207 fake_tty = FakeTTY() 1abcdefg

208 real_open = open 1abcdefg

209 

210 def fake_open(path, *args, **kwargs): 1abcdefg

211 if path == "/dev/tty": 1abcdefg

212 return fake_tty 1abcdefg

213 return real_open(path, *args, **kwargs) # pragma: no cover 

214 

215 monkeypatch.setattr("builtins.open", fake_open) 1abcdefg

216 

217 def tcgetattr(fd: int) -> str: 1abcdefg

218 state["tcgetattr_fd"] = fd 1abcdefg

219 return old_termios 1abcdefg

220 

221 def setraw(fd: int) -> None: 1abcdefg

222 state["setraw_fd"] = fd 1abcdefg

223 

224 def tcsetattr(fd: int, when: int, old: str) -> None: 1abcdefg

225 state["tcsetattr"] = (fd, when, old) 1abcdefg

226 

227 monkeypatch.setattr(_termui_impl.termios, "tcgetattr", tcgetattr) 1abcdefg

228 monkeypatch.setattr(_termui_impl.tty, "setraw", setraw) 1abcdefg

229 monkeypatch.setattr(_termui_impl.termios, "tcsetattr", tcsetattr) 1abcdefg

230 monkeypatch.setattr( 1abcdefg

231 _termui_impl.sys.stdout, "flush", lambda *a, **k: flushed.append(None) 

232 ) 

233 

234 with _termui_impl.raw_terminal() as fd: 1abcdefg

235 assert fd == expected_fd 1abcdefg

236 

237 assert state["tcgetattr_fd"] == expected_fd 1abcdefg

238 assert state["setraw_fd"] == expected_fd 1abcdefg

239 assert state["tcsetattr"] == ( 1abcdefg

240 expected_fd, 

241 _termui_impl.termios.TCSADRAIN, 

242 old_termios, 

243 ) 

244 assert flushed == [None] 1abcdefg

245 if fake_tty is not None: 1abcdefg

246 assert fake_tty.closed is True 1abcdefg

247 

248 

249@skip_if_windows 1abcdhijefg

250def test_termui_impl_posix_getchar(monkeypatch): 1abcdhijefg

251 @contextmanager 1abcdefg

252 def fake_raw(): 1abcdefg

253 yield 7 1abcdefg

254 

255 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw) 1abcdefg

256 monkeypatch.setattr(_termui_impl.os, "read", lambda fd, n: b"q") 1abcdefg

257 monkeypatch.setattr(_termui_impl, "get_best_encoding", lambda stdin: "utf-8") 1abcdefg

258 monkeypatch.setattr(_termui_impl, "isatty", lambda f: f is _termui_impl.sys.stdout) 1abcdefg

259 written: list[str] = [] 1abcdefg

260 monkeypatch.setattr(_termui_impl.sys.stdout, "write", lambda s: written.append(s)) 1abcdefg

261 

262 assert _termui_impl.getchar(echo=True) == "q" 1abcdefg

263 assert written == ["q"] 1abcdefg

264 

265 

266@skip_if_windows 1abcdhijefg

267def test_termui_impl_posix_getchar_eof(monkeypatch): 1abcdhijefg

268 @contextmanager 1abcdefg

269 def fake_raw(): 1abcdefg

270 yield 5 1abcdefg

271 

272 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw) 1abcdefg

273 monkeypatch.setattr(_termui_impl.os, "read", lambda fd, n: b"\x04") 1abcdefg

274 monkeypatch.setattr(_termui_impl, "get_best_encoding", lambda stdin: "utf-8") 1abcdefg

275 monkeypatch.setattr(_termui_impl, "isatty", lambda f: False) 1abcdefg

276 

277 with pytest.raises(EOFError): 1abcdefg

278 _termui_impl.getchar(echo=False) 1abcdefg

279 

280 

281def test_prompt(): 1abcdhijefg

282 runner = CliRunner() 1abcdhijefg

283 app = typer.Typer() 1abcdhijefg

284 fake_file = io.StringIO("data") 1abcdhijefg

285 fake_file.name = "demo.txt" 1abcdhijefg

286 

287 @app.command() 1abcdhijefg

288 def main( 1abcdhijefg

289 accept: bool = typer.Option(True, prompt=True), 

290 name: str = typer.Option(..., prompt=True), 

291 flavor: Literal["a", "b"] = typer.Option(..., prompt=True), 

292 city: str = typer.Option("London", prompt=True), 

293 config: str = typer.Option(fake_file, prompt=True), 

294 password: str = typer.Option( 

295 ..., 

296 prompt=True, 

297 hide_input=True, 

298 confirmation_prompt=True, 

299 ), 

300 ): 

301 typer.echo( 1abcdhijefg

302 f"accept={accept};name={name};flavor={flavor};city={city};config={config};pass_len={len(password)}" 

303 ) 

304 

305 result = runner.invoke(app, [], input="\nAda\na\n\ncustom.ini\nsecret\nsecret\n") 1abcdhijefg

306 assert result.exit_code == 0, result.output 1abcdhijefg

307 assert ( 1abcdhijefg

308 "accept=True;name=Ada;flavor=a;city=London;config=custom.ini;pass_len=6" 

309 in result.stdout 

310 ) 

311 assert "(a, b): " in result.stdout 1abcdhijefg

312 assert "[demo.txt]: " in result.stdout 1abcdhijefg

313 

314 

315def test_standalone_prompt(monkeypatch: pytest.MonkeyPatch) -> None: 1abcdhijefg

316 monkeypatch.setattr(termui, "visible_prompt_func", lambda prompt: "a") 1abcdhijefg

317 assert typer.prompt("flavor", type=Literal["a", "b"]) == "a" 1abcdhijefg

318 

319 

320def test_standalone_prompt_invalid( 1abcdhijefg

321 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] 

322) -> None: 

323 answers = iter(["nope", "a"]) 1abcdhijefg

324 monkeypatch.setattr(termui, "visible_prompt_func", lambda prompt: next(answers)) 1abcdhijefg

325 

326 assert typer.prompt("flavor", type=Literal["a", "b"]) == "a" 1abcdhijefg

327 assert "is not one of" in capsys.readouterr().out 1abcdhijefg

328 

329 

330def test_standalone_prompt_passthrough_default( 1abcdhijefg

331 monkeypatch: pytest.MonkeyPatch, 

332) -> None: 

333 class Widget: 1abcdhijefg

334 def __init__(self, value: int = 0) -> None: 1abcdhijefg

335 self.value = value 1abcdhijefg

336 

337 default = Widget(42) 1abcdhijefg

338 monkeypatch.setattr(termui, "visible_prompt_func", lambda prompt: "") 1abcdhijefg

339 assert typer.prompt("widget", type=Widget, default=default) is default 1abcdhijefg

340 

341 

342def test_standalone_prompt_passthrough_invalid( 1abcdhijefg

343 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] 

344) -> None: 

345 class Widget: 1abcdhijefg

346 def __init__(self, value: int = 0) -> None: 1abcdhijefg

347 self.value = value 1abcdhijefg

348 

349 default = Widget(42) 1abcdhijefg

350 answers = iter(["nope", ""]) 1abcdhijefg

351 monkeypatch.setattr(termui, "visible_prompt_func", lambda prompt: next(answers)) 1abcdhijefg

352 

353 assert typer.prompt("widget", type=Widget, default=default) is default 1abcdhijefg

354 assert "is not a valid Widget" in capsys.readouterr().out 1abcdhijefg

355 

356 

357def test_hidden_prompt_func(monkeypatch): 1abcdhijefg

358 monkeypatch.setattr("getpass.getpass", lambda prompt: "secret") 1abcdhijefg

359 assert termui.hidden_prompt_func("Password: ") == "secret" 1abcdhijefg

360 

361 

362def test_echo_stdout_missing(monkeypatch: pytest.MonkeyPatch) -> None: 1abcdhijefg

363 monkeypatch.setattr("sys.stdout", None) 1abcdhijefg

364 typer.echo("ignored") 1abcdhijefg

365 

366 

367def test_echo_stringifies() -> None: 1abcdhijefg

368 stream = io.StringIO() 1abcdhijefg

369 typer.echo(123, file=stream, nl=False) 1abcdhijefg

370 assert stream.getvalue() == "123" 1abcdhijefg

371 

372 

373def test_echo_bytes() -> None: 1abcdhijefg

374 buffer = io.BytesIO() 1abcdhijefg

375 stream = io.TextIOWrapper(buffer, encoding="utf-8") 1abcdhijefg

376 typer.echo(b"abc", file=stream, nl=True) 1abcdhijefg

377 assert buffer.getvalue() == b"abc\n" 1abcdhijefg

378 

379 

380def test_echo_empty_output() -> None: 1abcdhijefg

381 class FlushTrackingTextStream(io.StringIO): 1abcdhijefg

382 def __init__(self) -> None: 1abcdhijefg

383 super().__init__() 1abcdhijefg

384 self.flush_count = 0 1abcdhijefg

385 

386 def flush(self) -> None: 1abcdhijefg

387 self.flush_count += 1 1abcdhijefg

388 super().flush() 1abcdhijefg

389 

390 def write(self, s: str) -> int: 1abcdhijefg

391 raise AssertionError("Empty output") # pragma: no cover 

392 

393 stream = FlushTrackingTextStream() 1abcdhijefg

394 typer.echo("", file=stream, nl=False) 1abcdhijefg

395 assert stream.flush_count == 1 1abcdhijefg

396 

397 

398@needs_windows 1abcdhijefg

399def test_echo_windows_color_none( 1abcdhijefg

400 monkeypatch: pytest.MonkeyPatch, 

401) -> None: 

402 class TtyStream(io.StringIO): 1hij

403 def isatty(self) -> bool: 1hij

404 return True 1hij

405 

406 stream = TtyStream() 1hij

407 monkeypatch.setattr("typer._click.utils.auto_wrap_for_ansi", None) 1hij

408 typer.echo("\x1b[31mred\x1b[0m", file=stream, nl=False, color=None) 1hij

409 assert stream.getvalue() == "red" 1hij

410 

411 

412@pytest.mark.parametrize( 1abcdhijefg

413 ("flag", "true_code", "false_code"), 

414 [ 

415 ("bold", "\x1b[1m", "\x1b[22m"), 

416 ("dim", "\x1b[2m", "\x1b[22m"), 

417 ("underline", "\x1b[4m", "\x1b[24m"), 

418 ("overline", "\x1b[53m", "\x1b[55m"), 

419 ("italic", "\x1b[3m", "\x1b[23m"), 

420 ("blink", "\x1b[5m", "\x1b[25m"), 

421 ("reverse", "\x1b[7m", "\x1b[27m"), 

422 ("strikethrough", "\x1b[9m", "\x1b[29m"), 

423 ], 

424) 

425def test_style(flag, true_code, false_code): 1abcdhijefg

426 runner = CliRunner() 1abcdhijefg

427 app = typer.Typer() 1abcdhijefg

428 

429 @app.command() 1abcdhijefg

430 def main(): 1abcdhijefg

431 # testing an int and a str on purpose 

432 typer.echo("TRUE=" + typer.style("42", **{flag: True}), color=True) 1abcdhijefg

433 typer.echo("FALSE=" + typer.style(666, **{flag: False}), color=True) 1abcdhijefg

434 

435 result = runner.invoke(app, []) 1abcdhijefg

436 assert result.exit_code == 0, result.output 1abcdhijefg

437 lines = [line for line in result.stdout.splitlines() if line] 1abcdhijefg

438 true_line = next(line for line in lines if line.startswith("TRUE=")) 1abcdhijefg

439 false_line = next(line for line in lines if line.startswith("FALSE=")) 1abcdhijefg

440 assert "42" in true_line 1abcdhijefg

441 assert "666" in false_line 1abcdhijefg

442 

443 assert true_code in true_line 1abcdhijefg

444 assert true_code not in false_line 1abcdhijefg

445 assert false_code in false_line 1abcdhijefg

446 assert false_code not in true_line 1abcdhijefg

447 

448 

449def test_style_color(): 1abcdhijefg

450 fg_int = typer.style("x", fg=123) 1abcdhijefg

451 assert "\x1b[38;5;123m" in fg_int 1abcdhijefg

452 

453 bg_list = typer.style("x", bg=[1, 2, 3]) 1abcdhijefg

454 assert "\x1b[48;2;1;2;3m" in bg_list 1abcdhijefg

455 

456 with pytest.raises(TypeError, match="Unknown color"): 1abcdhijefg

457 typer.style("x", fg="not-a-color") 1abcdhijefg

458 

459 with pytest.raises(TypeError, match="Unknown color"): 1abcdhijefg

460 typer.style("x", bg="not-a-color") 1abcdhijefg

461 

462 

463def test_termui_launch(monkeypatch): 1abcdhijefg

464 captured = {} 1abcdhijefg

465 

466 def fake_open_url(url, wait=False, locate=False): 1abcdhijefg

467 captured["url"] = url 1abcdhijefg

468 captured["wait"] = wait 1abcdhijefg

469 captured["locate"] = locate 1abcdhijefg

470 return 7 1abcdhijefg

471 

472 monkeypatch.setattr(_termui_impl, "open_url", fake_open_url) 1abcdhijefg

473 rv = termui.launch("https://example.com", wait=True, locate=True) 1abcdhijefg

474 assert rv == 7 1abcdhijefg

475 assert captured == { 1abcdhijefg

476 "url": "https://example.com", 

477 "wait": True, 

478 "locate": True, 

479 }