test_termui.py
This file
Path
tests/test_termui.py
437 lines · 13.0 KiB · Python
Last changed by
♻️ Unify the testing functionality (#1792)Sofie Van Landeghembefore adoption2ce37a7
History of this fileTake it
1"""2Tests for the termui, echo, and CliRunner isolation functionality.3Created after vendoring Click to ensure test coverage is back up to 100%.4"""56import io7import os8from contextlib import contextmanager9from typing import Literal1011import pytest12import typer13from typer._click import _termui_impl, termui14from typer.testing import CliRunner1516from tests.utils import needs_windows, skip_if_windows171819def test_raw_terminal(monkeypatch):20 runner = CliRunner()21 app = typer.Typer()22 state = {"entered": 0, "exited": 0}2324 @contextmanager25 def fake_raw_terminal():26 state["entered"] += 127 try:28 yield 4229 finally:30 state["exited"] += 13132 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw_terminal)3334 @app.command()35 def main():36 with termui.raw_terminal() as fd:37 typer.echo(f"fd={fd}")3839 result = runner.invoke(app, [])40 assert result.exit_code == 0, result.output41 assert "fd=42" in result.stdout42 assert state["entered"] == 143 assert state["exited"] == 1444546def test_getchar(monkeypatch):47 # Cached path: call the existing _getchar directly.48 cached_state = {"echo": None}4950 def cached_getchar(echo: bool) -> str:51 cached_state["echo"] = echo52 return "x"5354 monkeypatch.setattr(termui, "_getchar", cached_getchar)55 assert termui.getchar(echo=True) == "x"56 assert cached_state["echo"] is True5758 # Lazy-load path: _getchar is None, so import/cache _termui_impl.getchar.59 lazy_state = {"calls": 0}6061 def lazy_getchar(echo: bool) -> str:62 lazy_state["calls"] += 163 return "y" if not echo else "z"6465 monkeypatch.setattr(termui, "_getchar", None)66 monkeypatch.setattr(_termui_impl, "getchar", lazy_getchar)6768 assert termui.getchar(echo=False) == "y"69 assert termui._getchar is lazy_getchar70 assert termui.getchar(echo=True) == "z"71 assert lazy_state["calls"] == 2727374def test_clirunner_getchar(monkeypatch) -> None:75 runner = CliRunner()76 app = typer.Typer()7778 @app.command()79 def main() -> None:80 first = termui.getchar(echo=False)81 second = termui.getchar(echo=True)82 typer.echo(f"\nfirst={first};second={second}")8384 monkeypatch.setattr(termui, "_getchar", None)85 result = runner.invoke(app, [], input="ab")86 assert result.exit_code == 0, result.output87 assert result.stdout.splitlines() == ["b", "first=a;second=b"]888990def test_clirunner_env_none(monkeypatch) -> None:91 runner = CliRunner()92 app = typer.Typer()93 env_key = "TYPER_TEST_ENV_REMOVE"94 monkeypatch.setenv(env_key, "present")9596 @app.command()97 def main() -> None:98 typer.echo(f"inside={os.environ.get(env_key)}")99100 result = runner.invoke(app, [], env={env_key: None})101 assert result.exit_code == 0, result.output102 assert "inside=None" in result.stdout103 assert os.environ.get(env_key) == "present"104105106@pytest.mark.parametrize(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(114 exit_value: object,115 expected_exit_code: int,116 expected_stdout: str,117) -> None:118 runner = CliRunner()119 app = typer.Typer()120121 @app.command()122 def main() -> None:123 raise SystemExit(exit_value)124125 result = runner.invoke(app, [])126 assert result.exit_code == expected_exit_code127 assert result.stdout == expected_stdout128 if expected_exit_code:129 assert isinstance(result.exception, SystemExit)130 else:131 assert result.exception is None132133134@needs_windows135def test_termui_impl_windows_raw_terminal():136 with _termui_impl.raw_terminal() as fd:137 assert fd == -1138 with termui.raw_terminal() as fd:139 assert fd == -1140141142@needs_windows143def test_termui_impl_windows_getchar(monkeypatch):144 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "a")145 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: "b")146 assert _termui_impl.getchar(echo=False) == "a"147 assert _termui_impl.getchar(echo=True) == "b"148149 seq_null = iter(["\x00", "K"])150 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_null))151 assert _termui_impl.getchar(echo=False) == "\x00K"152153 seq_e0 = iter(["\xe0", "H"])154 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_e0))155 assert _termui_impl.getchar(echo=False) == "\xe0H"156157 seq_echo = iter(["\x00", "M"])158 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_echo))159 assert _termui_impl.getchar(echo=True) == "\x00M"160161 seq_e0_echo = iter(["\xe0", "Z"])162 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_e0_echo))163 assert _termui_impl.getchar(echo=True) == "\xe0Z"164165 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x03")166 with pytest.raises(KeyboardInterrupt):167 _termui_impl.getchar(echo=False)168169 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x1a")170 with pytest.raises(EOFError):171 _termui_impl.getchar(echo=False)172173174@skip_if_windows175@pytest.mark.parametrize("use_stdin_tty", [True, False])176def test_termui_impl_posix_raw_terminal(monkeypatch, use_stdin_tty: bool):177 state: dict[str, object] = {}178 flushed: list[None] = []179 fake_tty = None180181 if use_stdin_tty:182 expected_fd = 14183 old_termios = "old_settings"184 monkeypatch.setattr(185 _termui_impl, "isatty", lambda s: s is _termui_impl.sys.stdin186 )187 monkeypatch.setattr(_termui_impl.sys.stdin, "fileno", lambda: expected_fd)188 else:189 expected_fd = 27190 old_termios = "old"191 monkeypatch.setattr(192 _termui_impl,193 "isatty",194 lambda s: s is not _termui_impl.sys.stdin,195 )196197 class FakeTTY:198 def __init__(self) -> None:199 self.closed = False200201 def fileno(self) -> int:202 return expected_fd203204 def close(self) -> None:205 self.closed = True206207 fake_tty = FakeTTY()208 real_open = open209210 def fake_open(path, *args, **kwargs):211 if path == "/dev/tty":212 return fake_tty213 return real_open(path, *args, **kwargs) # pragma: no cover214215 monkeypatch.setattr("builtins.open", fake_open)216217 def tcgetattr(fd: int) -> str:218 state["tcgetattr_fd"] = fd219 return old_termios220221 def setraw(fd: int) -> None:222 state["setraw_fd"] = fd223224 def tcsetattr(fd: int, when: int, old: str) -> None:225 state["tcsetattr"] = (fd, when, old)226227 monkeypatch.setattr(_termui_impl.termios, "tcgetattr", tcgetattr)228 monkeypatch.setattr(_termui_impl.tty, "setraw", setraw)229 monkeypatch.setattr(_termui_impl.termios, "tcsetattr", tcsetattr)230 monkeypatch.setattr(231 _termui_impl.sys.stdout, "flush", lambda *a, **k: flushed.append(None)232 )233234 with _termui_impl.raw_terminal() as fd:235 assert fd == expected_fd236237 assert state["tcgetattr_fd"] == expected_fd238 assert state["setraw_fd"] == expected_fd239 assert state["tcsetattr"] == (240 expected_fd,241 _termui_impl.termios.TCSADRAIN,242 old_termios,243 )244 assert flushed == [None]245 if fake_tty is not None:246 assert fake_tty.closed is True247248249@skip_if_windows250def test_termui_impl_posix_getchar(monkeypatch):251 @contextmanager252 def fake_raw():253 yield 7254255 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw)256 monkeypatch.setattr(_termui_impl.os, "read", lambda fd, n: b"q")257 monkeypatch.setattr(_termui_impl, "get_best_encoding", lambda stdin: "utf-8")258 monkeypatch.setattr(_termui_impl, "isatty", lambda f: f is _termui_impl.sys.stdout)259 written: list[str] = []260 monkeypatch.setattr(_termui_impl.sys.stdout, "write", lambda s: written.append(s))261262 assert _termui_impl.getchar(echo=True) == "q"263 assert written == ["q"]264265266@skip_if_windows267def test_termui_impl_posix_getchar_eof(monkeypatch):268 @contextmanager269 def fake_raw():270 yield 5271272 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw)273 monkeypatch.setattr(_termui_impl.os, "read", lambda fd, n: b"\x04")274 monkeypatch.setattr(_termui_impl, "get_best_encoding", lambda stdin: "utf-8")275 monkeypatch.setattr(_termui_impl, "isatty", lambda f: False)276277 with pytest.raises(EOFError):278 _termui_impl.getchar(echo=False)279280281def test_prompt():282 runner = CliRunner()283 app = typer.Typer()284 fake_file = io.StringIO("data")285 fake_file.name = "demo.txt"286287 @app.command()288 def main(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(302 f"accept={accept};name={name};flavor={flavor};city={city};config={config};pass_len={len(password)}"303 )304305 result = runner.invoke(app, [], input="\nAda\na\n\ncustom.ini\nsecret\nsecret\n")306 assert result.exit_code == 0, result.output307 assert (308 "accept=True;name=Ada;flavor=a;city=London;config=custom.ini;pass_len=6"309 in result.stdout310 )311 assert "(a, b): " in result.stdout312 assert "[demo.txt]: " in result.stdout313314315def test_hidden_prompt_func(monkeypatch):316 monkeypatch.setattr("getpass.getpass", lambda prompt: "secret")317 assert termui.hidden_prompt_func("Password: ") == "secret"318319320def test_echo_stdout_missing(monkeypatch: pytest.MonkeyPatch) -> None:321 monkeypatch.setattr("sys.stdout", None)322 typer.echo("ignored")323324325def test_echo_stringifies() -> None:326 stream = io.StringIO()327 typer.echo(123, file=stream, nl=False)328 assert stream.getvalue() == "123"329330331def test_echo_bytes() -> None:332 buffer = io.BytesIO()333 stream = io.TextIOWrapper(buffer, encoding="utf-8")334 typer.echo(b"abc", file=stream, nl=True)335 assert buffer.getvalue() == b"abc\n"336337338def test_echo_empty_output() -> None:339 class FlushTrackingTextStream(io.StringIO):340 def __init__(self) -> None:341 super().__init__()342 self.flush_count = 0343344 def flush(self) -> None:345 self.flush_count += 1346 super().flush()347348 def write(self, s: str) -> int:349 raise AssertionError("Empty output") # pragma: no cover350351 stream = FlushTrackingTextStream()352 typer.echo("", file=stream, nl=False)353 assert stream.flush_count == 1354355356@needs_windows357def test_echo_windows_color_none(358 monkeypatch: pytest.MonkeyPatch,359) -> None:360 class TtyStream(io.StringIO):361 def isatty(self) -> bool:362 return True363364 stream = TtyStream()365 monkeypatch.setattr("typer._click.utils.auto_wrap_for_ansi", None)366 typer.echo("\x1b[31mred\x1b[0m", file=stream, nl=False, color=None)367 assert stream.getvalue() == "red"368369370@pytest.mark.parametrize(371 ("flag", "true_code", "false_code"),372 [373 ("bold", "\x1b[1m", "\x1b[22m"),374 ("dim", "\x1b[2m", "\x1b[22m"),375 ("underline", "\x1b[4m", "\x1b[24m"),376 ("overline", "\x1b[53m", "\x1b[55m"),377 ("italic", "\x1b[3m", "\x1b[23m"),378 ("blink", "\x1b[5m", "\x1b[25m"),379 ("reverse", "\x1b[7m", "\x1b[27m"),380 ("strikethrough", "\x1b[9m", "\x1b[29m"),381 ],382)383def test_style(flag, true_code, false_code):384 runner = CliRunner()385 app = typer.Typer()386387 @app.command()388 def main():389 # testing an int and a str on purpose390 typer.echo("TRUE=" + typer.style("42", **{flag: True}), color=True)391 typer.echo("FALSE=" + typer.style(666, **{flag: False}), color=True)392393 result = runner.invoke(app, [])394 assert result.exit_code == 0, result.output395 lines = [line for line in result.stdout.splitlines() if line]396 true_line = next(line for line in lines if line.startswith("TRUE="))397 false_line = next(line for line in lines if line.startswith("FALSE="))398 assert "42" in true_line399 assert "666" in false_line400401 assert true_code in true_line402 assert true_code not in false_line403 assert false_code in false_line404 assert false_code not in true_line405406407def test_style_color():408 fg_int = typer.style("x", fg=123)409 assert "\x1b[38;5;123m" in fg_int410411 bg_list = typer.style("x", bg=[1, 2, 3])412 assert "\x1b[48;2;1;2;3m" in bg_list413414 with pytest.raises(TypeError, match="Unknown color"):415 typer.style("x", fg="not-a-color")416417 with pytest.raises(TypeError, match="Unknown color"):418 typer.style("x", bg="not-a-color")419420421def test_termui_launch(monkeypatch):422 captured = {}423424 def fake_open_url(url, wait=False, locate=False):425 captured["url"] = url426 captured["wait"] = wait427 captured["locate"] = locate428 return 7429430 monkeypatch.setattr(_termui_impl, "open_url", fake_open_url)431 rv = termui.launch("https://example.com", wait=True, locate=True)432 assert rv == 7433 assert captured == {434 "url": "https://example.com",435 "wait": True,436 "locate": True,437 }