Skip to content
Myr

♻️ Unify the testing functionality (#1792)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sofie Van Landeghem · committed by GitHub · parent eef433f · Browse files · 4 files+328 added−415 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>

Diff stats

4 files+328 added−415 removed

  • tests:+1 added−33 removed
  • other:+327 added−382 removed

4 files+328 added−415 removed

modified:tests/test_termui.py-21 removed
102 unmodified lines
103 assert os.environ.get(env_key) == "present"104105106@pytest.mark.parametrize(107 ("runner_exc", "invoke_exc"),108 [109 (False, None),110 (True, False),111 ],112)113def test_clirunner_invoke_catch_exceptions(114 runner_exc: bool, invoke_exc: bool | None115) -> None:116 runner = CliRunner(catch_exceptions=runner_exc)117 app = typer.Typer()118119 @app.command()120 def main() -> None:121 raise RuntimeError("boom")122123 with pytest.raises(RuntimeError, match="boom"):124 runner.invoke(app, [], catch_exceptions=invoke_exc)125126127@pytest.mark.parametrize(107 ("exit_value", "expected_exit_code", "expected_stdout"),108 [109 (None, 0, ""),110 ("bad-exit", 1, "bad-exit\n"),
327 unmodified lines
modified:tests/test_types_file.py+1 added-12 removed
1import subprocess2import sys3from io import BytesIO, StringIO, TextIOWrapper3from io import BytesIO, StringIO4from pathlib import Path56import pytest7import typer8from typer._click._compat import get_best_encoding, should_strip_ansi9from typer._click.testing import make_input_stream9from typer._click.utils import PacifyFlushWrapper10from typer.testing import CliRunner1112from tests.utils import needs_linux, needs_windows
109 unmodified lines
122 assert "1 line written" in result.output123 assert stream.getvalue() == "This is a single line\n"124125127def test_input_stream() -> None:128 binary_stream = BytesIO(b"hello")129 converted = make_input_stream(binary_stream, charset="utf-8")130 assert converted is binary_stream131132 text_stream = TextIOWrapper(BytesIO(b"hello"), encoding="utf-8")133 converted = make_input_stream(text_stream, charset="utf-8")134 assert converted is text_stream.buffer135136126def test_binary_dash() -> None:127 result = runner.invoke(app, ["write-binary", "--file-out=-"])128 assert result.exit_code == 0129 assert result.stdout_bytes == b"binary-written\n"
255 unmodified lines
deleted:typer/_click/testing.py-366 removed
1import contextlib2import io3import os4import shlex5import sys6from collections.abc import Iterator, Mapping, Sequence7from types import TracebackType8from typing import IO, TYPE_CHECKING, Any, BinaryIO, cast910from . import _compat, formatting, termui, utils11from ._compat import _find_binary_reader12from .core import Command1314if TYPE_CHECKING:15 from _typeshed import ReadableBuffer161718class BytesIOCopy(io.BytesIO):19 """Patch ``io.BytesIO`` to let the written stream be copied to another."""2021 def __init__(self, copy_to: io.BytesIO) -> None:22 super().__init__()23 self.copy_to = copy_to2425 def flush(self) -> None:26 super().flush()27 self.copy_to.flush()2829 def write(self, b: "ReadableBuffer") -> int:30 self.copy_to.write(b)31 return super().write(b)323334class StreamMixer:35 """Mixes `<stdout>` and `<stderr>` streams.3637 The result is available in the ``output`` attribute.38 """3940 def __init__(self) -> None:41 self.output: io.BytesIO = io.BytesIO()42 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)43 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)4445 def __del__(self) -> None:46 """47 Guarantee that embedded file-like objects are closed in a48 predictable order, protecting against races between49 self.output being closed and other streams being flushed on close50 """51 self.stderr.close()52 self.stdout.close()53 self.output.close()545556class _NamedTextIOWrapper(io.TextIOWrapper):57 def __init__(self, buffer: BinaryIO, name: str, mode: str, **kwargs: Any) -> None:58 super().__init__(buffer, **kwargs)59 self._name = name60 self._mode = mode6162 @property63 def name(self) -> str:64 return self._name # pragma: no cover6566 @property67 def mode(self) -> str:68 return self._mode # pragma: no cover697071def make_input_stream(input: str | bytes | IO[Any] | None, charset: str) -> BinaryIO:72 # Is already an input stream.73 if hasattr(input, "read"):74 rv = _find_binary_reader(cast("IO[Any]", input))7576 if rv is not None:77 return rv7879 raise TypeError(80 "Could not find binary reader for input stream."81 ) # pragma: no cover8283 if input is None:84 input = b""85 elif isinstance(input, str):86 input = input.encode(charset)8788 return io.BytesIO(input)899091class Result:92 """Holds the captured result of an invoked CLI script."""9394 def __init__(95 self,96 runner: "CliRunner",97 stdout_bytes: bytes,98 stderr_bytes: bytes,99 output_bytes: bytes,100 return_value: Any,101 exit_code: int,102 exception: BaseException | None,103 exc_info: tuple[type[BaseException], BaseException, TracebackType]104 | None = None,105 ):106 self.runner = runner107 self.stdout_bytes = stdout_bytes108 self.stderr_bytes = stderr_bytes109 self.output_bytes = output_bytes110 self.return_value = return_value111 self.exit_code = exit_code112 self.exception = exception113 self.exc_info = exc_info114115 @property116 def output(self) -> str:117 """The terminal output as unicode string, as the user would see it."""118 return self.output_bytes.decode(self.runner.charset, "replace").replace(119 "\r\n", "\n"120 )121122 @property123 def stdout(self) -> str:124 """The standard output as unicode string."""125 return self.stdout_bytes.decode(self.runner.charset, "replace").replace(126 "\r\n", "\n"127 )128129 @property130 def stderr(self) -> str:131 """The standard error as unicode string."""132 return self.stderr_bytes.decode(self.runner.charset, "replace").replace(133 "\r\n", "\n"134 )135136 def __repr__(self) -> str:137 exc_str = repr(self.exception) if self.exception else "okay"138 return f"<{type(self).__name__} {exc_str}>"139140141class CliRunner:142 """The CLI runner provides functionality to invoke a Click command line143 script for unittesting purposes in a isolated environment. This only144 works in single-threaded systems without any concurrency as it changes the145 global interpreter state.146 """147148 def __init__(149 self,150 charset: str = "utf-8",151 env: Mapping[str, str | None] | None = None,152 catch_exceptions: bool = True,153 ) -> None:154 self.charset = charset155 self.env: Mapping[str, str | None] = env or {}156 self.catch_exceptions = catch_exceptions157158 def get_default_prog_name(self, cli: Command) -> str:159 """Given a command object it will return the default program name160 for it. The default is the `name` attribute or ``"root"`` if not161 set.162 """163 return cli.name or "root"164165 def make_env(166 self, overrides: Mapping[str, str | None] | None = None167 ) -> Mapping[str, str | None]:168 """Returns the environment overrides for invoking a script."""169 rv = dict(self.env)170 if overrides:171 rv.update(overrides)172 return rv173174 @contextlib.contextmanager175 def isolation(176 self,177 input: str | bytes | IO[Any] | None = None,178 env: Mapping[str, str | None] | None = None,179 color: bool = False,180 ) -> Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:181 """A context manager that sets up the isolation for invoking of a182 command line tool. This sets up `<stdin>` with the given input data183 and `os.environ` with the overrides from the given dictionary.184 This also rebinds some internals in Click to be mocked (like the185 prompt functionality).186 """187 bytes_input = make_input_stream(input, self.charset)188189 old_stdin = sys.stdin190 old_stdout = sys.stdout191 old_stderr = sys.stderr192 old_forced_width = formatting.FORCED_WIDTH193 formatting.FORCED_WIDTH = 80194195 env = self.make_env(env)196197 stream_mixer = StreamMixer()198199 sys.stdin = text_input = _NamedTextIOWrapper(200 bytes_input, encoding=self.charset, name="<stdin>", mode="r"201 )202203 sys.stdout = _NamedTextIOWrapper(204 stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"205 )206207 sys.stderr = _NamedTextIOWrapper(208 stream_mixer.stderr,209 encoding=self.charset,210 name="<stderr>",211 mode="w",212 errors="backslashreplace",213 )214215 def visible_input(prompt: str | None = None) -> str:216 sys.stdout.write(prompt or "")217 try:218 val = next(text_input).rstrip("\r\n")219 except StopIteration as e: # pragma: no cover220 raise EOFError() from e221 sys.stdout.write(f"{val}\n")222 sys.stdout.flush()223 return val224225 def hidden_input(prompt: str | None = None) -> str:226 sys.stdout.write(f"{prompt or ''}\n")227 sys.stdout.flush()228 try:229 return next(text_input).rstrip("\r\n")230 except StopIteration as e: # pragma: no cover231 raise EOFError() from e232233 def _getchar(echo: bool) -> str:234 char = sys.stdin.read(1)235236 if echo:237 sys.stdout.write(char)238239 sys.stdout.flush()240 return char241242 default_color = color243244 def should_strip_ansi(245 stream: IO[Any] | None = None, color: bool | None = None246 ) -> bool:247 if color is None:248 return not default_color249 return not color250251 old_visible_prompt_func = termui.visible_prompt_func252 old_hidden_prompt_func = termui.hidden_prompt_func253 old__getchar_func = termui._getchar254 old_should_strip_ansi = utils.should_strip_ansi # type: ignore[attr-defined]255 old__compat_should_strip_ansi = _compat.should_strip_ansi256 termui.visible_prompt_func = visible_input257 termui.hidden_prompt_func = hidden_input # ty: ignore[invalid-assignment]258 termui._getchar = _getchar259 utils.should_strip_ansi = should_strip_ansi # type: ignore260 _compat.should_strip_ansi = should_strip_ansi # ty: ignore[invalid-assignment]261262 old_env = {}263 try:264 for key, value in env.items():265 old_env[key] = os.environ.get(key)266 if value is None:267 try:268 del os.environ[key]269 except Exception: # pragma: no cover270 pass271 else:272 os.environ[key] = value273 yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)274 finally:275 for key, value in old_env.items():276 if value is None:277 try:278 del os.environ[key]279 except Exception: # pragma: no cover280 pass281 else:282 os.environ[key] = value283 sys.stdout = old_stdout284 sys.stderr = old_stderr285 sys.stdin = old_stdin286 termui.visible_prompt_func = old_visible_prompt_func287 termui.hidden_prompt_func = old_hidden_prompt_func288 termui._getchar = old__getchar_func289 utils.should_strip_ansi = old_should_strip_ansi # type: ignore[attr-defined]290 _compat.should_strip_ansi = old__compat_should_strip_ansi291 formatting.FORCED_WIDTH = old_forced_width292293 def invoke(294 self,295 cli: Command,296 args: str | Sequence[str] | None = None,297 input: str | bytes | IO[Any] | None = None,298 env: Mapping[str, str | None] | None = None,299 catch_exceptions: bool | None = None,300 color: bool = False,301 **extra: Any,302 ) -> Result:303 """Invokes a command in an isolated environment. The arguments are304 forwarded directly to the command line script, the `extra` keyword305 arguments are passed to the `Command.main` function of306 the command.307 """308 exc_info = None309 if catch_exceptions is None:310 catch_exceptions = self.catch_exceptions311312 with self.isolation(input=input, env=env, color=color) as outstreams:313 return_value = None314 exception: BaseException | None = None315 exit_code = 0316317 if isinstance(args, str):318 args = shlex.split(args)319320 try:321 prog_name = extra.pop("prog_name")322 except KeyError:323 prog_name = self.get_default_prog_name(cli)324325 try:326 return_value = cli.main(args=args or (), prog_name=prog_name, **extra)327 except SystemExit as e:328 exc_info = sys.exc_info()329 e_code = cast("int | Any | None", e.code)330331 if e_code is None:332 e_code = 0333334 if e_code != 0:335 exception = e336337 if not isinstance(e_code, int):338 sys.stdout.write(str(e_code))339 sys.stdout.write("\n")340 e_code = 1341342 exit_code = e_code343344 except Exception as e:345 if not catch_exceptions:346 raise347 exception = e348 exit_code = 1349 exc_info = sys.exc_info()350 finally:351 sys.stdout.flush()352 sys.stderr.flush()353 stdout = outstreams[0].getvalue()354 stderr = outstreams[1].getvalue()355 output = outstreams[2].getvalue()356357 return Result(358 runner=self,359 stdout_bytes=stdout,360 stderr_bytes=stderr,361 output_bytes=output,362 return_value=return_value,363 exit_code=exit_code,364 exception=exception,365 exc_info=exc_info, # type: ignore366 )
modified:typer/testing.py+327 added-16 removed
1import contextlib2import io3import os4import shlex5import sys1from collections.abc import Mapping, Sequence2from typing import IO, Any6from collections.abc import Iterator, Mapping, Sequence7from types import TracebackType8from typing import IO, TYPE_CHECKING, Any, BinaryIO, cast910from typer.main import Typer11from typer.main import get_command as _get_command127from ._click.testing import CliRunner as ClickCliRunner # noqa8from ._click.testing import Result13from . import _click14from ._click import _compat, formatting, termui, utils1516if TYPE_CHECKING:17 from _typeshed import ReadableBuffer1811class CliRunner(ClickCliRunner):12 def invoke( # type: ignore1920def make_input_stream(input: str | bytes | None, charset: str) -> BinaryIO:21 if input is None:22 input = b""23 elif isinstance(input, str):24 input = input.encode(charset)2526 return io.BytesIO(input)272829class BytesIOCopy(io.BytesIO):30 """Patch ``io.BytesIO`` to let the written stream be copied to another."""3132 def __init__(self, copy_to: io.BytesIO) -> None:33 super().__init__()34 self.copy_to = copy_to3536 def flush(self) -> None:37 super().flush()38 self.copy_to.flush()3940 def write(self, b: "ReadableBuffer") -> int:41 self.copy_to.write(b)42 return super().write(b)434445class StreamMixer:46 """Mixes `<stdout>` and `<stderr>` streams.4748 The result is available in the ``output`` attribute.49 """5051 def __init__(self) -> None:52 self.output: io.BytesIO = io.BytesIO()53 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)54 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)5556 def __del__(self) -> None:57 """Guarantee that file-like objects are closed in a predictable order"""58 self.stderr.close()59 self.stdout.close()60 self.output.close()616263class _NamedTextIOWrapper(io.TextIOWrapper):64 def __init__(self, buffer: BinaryIO, name: str, mode: str, **kwargs: Any) -> None:65 super().__init__(buffer, **kwargs)66 self._name = name67 self._mode = mode6869 @property70 def name(self) -> str:71 return self._name # pragma: no cover7273 @property74 def mode(self) -> str:75 return self._mode # pragma: no cover767778class Result:79 """Holds the captured result of an invoked CLI script."""8081 def __init__(82 self,83 runner: "CliRunner",84 stdout_bytes: bytes,85 stderr_bytes: bytes,86 output_bytes: bytes,87 return_value: Any,88 exit_code: int,89 exception: BaseException | None,90 exc_info: tuple[type[BaseException], BaseException, TracebackType]91 | None = None,92 ):93 self.runner = runner94 self.stdout_bytes = stdout_bytes95 self.stderr_bytes = stderr_bytes96 self.output_bytes = output_bytes97 self.return_value = return_value98 self.exit_code = exit_code99 self.exception = exception100 self.exc_info = exc_info101102 @property103 def output(self) -> str:104 """The terminal output as unicode string, as the user would see it."""105 return self.output_bytes.decode(self.runner.charset, "replace").replace(106 "\r\n", "\n"107 )108109 @property110 def stdout(self) -> str:111 """The standard output as unicode string."""112 return self.stdout_bytes.decode(self.runner.charset, "replace").replace(113 "\r\n", "\n"114 )115116 @property117 def stderr(self) -> str:118 """The standard error as unicode string."""119 return self.stderr_bytes.decode(self.runner.charset, "replace").replace(120 "\r\n", "\n"121 )122123 def __repr__(self) -> str:124 exc_str = repr(self.exception) if self.exception else "okay"125 return f"<{type(self).__name__} {exc_str}>"126127128class CliRunner:129 """The CLI runner provides functionality to invoke a command line130 script for unittesting purposes in an isolated environment. This only131 works in single-threaded systems without any concurrency as it changes the132 global interpreter state. Based on functionality from Click.133 """134135 def __init__(136 self,137 charset: str = "utf-8",138 env: Mapping[str, str | None] | None = None,139 ) -> None:140 self.charset = charset141 self.env: Mapping[str, str | None] = env or {}142143 def get_default_prog_name(self, cli: _click.Command) -> str:144 """Return the default program name for a command.145 The default is the `name` attribute or ``"root"`` if not set.146 """147 return cli.name or "root"148149 def make_env(150 self, overrides: Mapping[str, str | None] | None = None151 ) -> Mapping[str, str | None]:152 """Returns the environment overrides for invoking a script."""153 rv = dict(self.env)154 if overrides:155 rv.update(overrides)156 return rv157158 @contextlib.contextmanager159 def isolation(160 self,161 input: str | bytes | None = None,162 env: Mapping[str, str | None] | None = None,163 color: bool = False,164 ) -> Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:165 """A context manager that sets up the isolation for invoking of a166 command line tool. This sets up `<stdin>` with the given input data167 and `os.environ` with the overrides from the given dictionary.168 """169 bytes_input = make_input_stream(input, self.charset)170171 old_stdin = sys.stdin172 old_stdout = sys.stdout173 old_stderr = sys.stderr174 old_forced_width = formatting.FORCED_WIDTH175 formatting.FORCED_WIDTH = 80176177 env = self.make_env(env)178179 stream_mixer = StreamMixer()180181 sys.stdin = text_input = _NamedTextIOWrapper(182 bytes_input, encoding=self.charset, name="<stdin>", mode="r"183 )184185 sys.stdout = _NamedTextIOWrapper(186 stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"187 )188189 sys.stderr = _NamedTextIOWrapper(190 stream_mixer.stderr,191 encoding=self.charset,192 name="<stderr>",193 mode="w",194 errors="backslashreplace",195 )196197 def visible_input(prompt: str | None = None) -> str:198 sys.stdout.write(prompt or "")199 try:200 val = next(text_input).rstrip("\r\n")201 except StopIteration as e: # pragma: no cover202 raise EOFError() from e203 sys.stdout.write(f"{val}\n")204 sys.stdout.flush()205 return val206207 def hidden_input(prompt: str | None = None) -> str:208 sys.stdout.write(f"{prompt or ''}\n")209 sys.stdout.flush()210 try:211 return next(text_input).rstrip("\r\n")212 except StopIteration as e: # pragma: no cover213 raise EOFError() from e214215 def _getchar(echo: bool) -> str:216 char = sys.stdin.read(1)217218 if echo:219 sys.stdout.write(char)220221 sys.stdout.flush()222 return char223224 default_color = color225226 def should_strip_ansi(227 stream: IO[Any] | None = None, color: bool | None = None228 ) -> bool:229 if color is None:230 return not default_color231 return not color232233 old_visible_prompt_func = termui.visible_prompt_func234 old_hidden_prompt_func = termui.hidden_prompt_func235 old__getchar_func = termui._getchar236 old_should_strip_ansi = utils.should_strip_ansi # type: ignore[attr-defined]237 old__compat_should_strip_ansi = _compat.should_strip_ansi238 termui.visible_prompt_func = visible_input239 termui.hidden_prompt_func = hidden_input # ty: ignore[invalid-assignment]240 termui._getchar = _getchar241 utils.should_strip_ansi = should_strip_ansi # type: ignore242 _compat.should_strip_ansi = should_strip_ansi # ty: ignore[invalid-assignment]243244 old_env = {}245 try:246 for key, value in env.items():247 old_env[key] = os.environ.get(key)248 if value is None:249 try:250 del os.environ[key]251 except Exception: # pragma: no cover252 pass253 else:254 os.environ[key] = value255 yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)256 finally:257 for key, value in old_env.items():258 if value is None:259 try:260 del os.environ[key]261 except Exception: # pragma: no cover262 pass263 else:264 os.environ[key] = value265 sys.stdout = old_stdout266 sys.stderr = old_stderr267 sys.stdin = old_stdin268 termui.visible_prompt_func = old_visible_prompt_func269 termui.hidden_prompt_func = old_hidden_prompt_func270 termui._getchar = old__getchar_func271 utils.should_strip_ansi = old_should_strip_ansi # type: ignore[attr-defined]272 _compat.should_strip_ansi = old__compat_should_strip_ansi273 formatting.FORCED_WIDTH = old_forced_width274275 def invoke(276 self,277 app: Typer,278 args: str | Sequence[str] | None = None,16 input: bytes | str | IO[Any] | None = None,279 input: bytes | str | None = None,280 env: Mapping[str, str | None] | None = None,281 catch_exceptions: bool = True,282 color: bool = False,283 **extra: Any,284 ) -> Result:22 use_cli = _get_command(app)23 return super().invoke(24 use_cli,25 args=args,26 input=input,27 env=env,28 catch_exceptions=catch_exceptions,29 color=color,30 **extra,285 cli = _get_command(app)286 exc_info = None287288 with self.isolation(input=input, env=env, color=color) as outstreams:289 return_value = None290 exception: BaseException | None = None291 exit_code = 0292293 if isinstance(args, str):294 args = shlex.split(args)295296 try:297 prog_name = extra.pop("prog_name")298 except KeyError:299 prog_name = self.get_default_prog_name(cli)300301 try:302 return_value = cli.main(args=args or (), prog_name=prog_name, **extra)303 except SystemExit as e:304 exc_info = sys.exc_info()305 e_code = cast("int | Any | None", e.code)306307 if e_code is None:308 e_code = 0309310 if e_code != 0:311 exception = e312313 if not isinstance(e_code, int):314 sys.stdout.write(str(e_code))315 sys.stdout.write("\n")316 e_code = 1317318 exit_code = e_code319320 except Exception as e:321 if not catch_exceptions:322 raise323 exception = e324 exit_code = 1325 exc_info = sys.exc_info()326 finally:327 sys.stdout.flush()328 sys.stderr.flush()329 stdout = outstreams[0].getvalue()330 stderr = outstreams[1].getvalue()331 output = outstreams[2].getvalue()332333 return Result(334 runner=self,335 stdout_bytes=stdout,336 stderr_bytes=stderr,337 output_bytes=output,338 return_value=return_value,339 exit_code=exit_code,340 exception=exception,341 exc_info=exc_info, # type: ignore342 )