Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by GitHub · parent 948d7a7 · Browse files · 4 files·+126 added−70 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: Andreas Backx <andreas@backx.org>
Diff stats
4 files+126 added−70 removed
- tests:+12 added−21 removed
- other:+114 added−49 removed
Provenance
- Commit
0e0c003- Tree
2eb2f53- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
948d7a7
4 files changed+126 added−70 removed
modified:src/click/testing.py+110 added-49 removed
16 unmodified lines17 from . import utils18 from ._compat import _find_binary_reader19 20 if t.TYPE_CHECKING:21+ from _typeshed import ReadableBuffer22+23 from .core import Command24 25 26 class EchoingStdin:39 unmodified lines66 yield67 stream._paused = False68 69 70+class BytesIOCopy(io.BytesIO):71+ """Patch ``io.BytesIO`` to let the written stream be copied to another.72+73+ .. versionadded:: 8.274+ """75+76+ def __init__(self, copy_to: io.BytesIO) -> None:77+ super().__init__()78+ self.copy_to = copy_to79+80+ def flush(self) -> None:81+ super().flush()82+ self.copy_to.flush()83+84+ def write(self, b: ReadableBuffer) -> int:85+ self.copy_to.write(b)86+ return super().write(b)87+88+89+class StreamMixer:90+ """Mixes `<stdout>` and `<stderr>` streams.91+92+ The result is available in the ``output`` attribute.93+94+ .. versionadded:: 8.295+ """96+97+ def __init__(self) -> None:98+ self.output: io.BytesIO = io.BytesIO()99+ self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)100+ self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101+102+103 class _NamedTextIOWrapper(io.TextIOWrapper):104 def __init__(105 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any106 ) -> None:30 unmodified lines137 return io.BytesIO(input)138 139 140 class Result:106- """Holds the captured result of an invoked CLI script."""141+ """Holds the captured result of an invoked CLI script.142 143+ :param runner: The runner that created the result144+ :param stdout_bytes: The standard output as bytes.145+ :param stderr_bytes: The standard error as bytes.146+ :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the147+ user would see it in its terminal.148+ :param return_value: The value returned from the invoked command.149+ :param exit_code: The exit code as integer.150+ :param exception: The exception that happened if one did.151+ :param exc_info: Exception information (exception type, exception instance,152+ traceback type).153+154+ .. versionchanged:: 8.2155+ ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and156+ ``mix_stderr`` has been removed.157+158+ .. versionadded:: 8.0159+ Added ``return_value``.160+ """161+162 def __init__(163 self,164 runner: CliRunner,165 stdout_bytes: bytes,112- stderr_bytes: bytes | None,166+ stderr_bytes: bytes,167+ output_bytes: bytes,168 return_value: t.Any,169 exit_code: int,170 exception: BaseException | None,171 exc_info: tuple[type[BaseException], BaseException, TracebackType]172 | None = None,173 ):119- #: The runner that created the result174 self.runner = runner121- #: The standard output as bytes.175 self.stdout_bytes = stdout_bytes123- #: The standard error as bytes, or None if not available176 self.stderr_bytes = stderr_bytes125- #: The value returned from the invoked command.126- #:127- #: .. versionadded:: 8.0177+ self.output_bytes = output_bytes178 self.return_value = return_value129- #: The exit code as integer.179 self.exit_code = exit_code131- #: The exception that happened if one did.180 self.exception = exception133- #: The traceback181 self.exc_info = exc_info182 183 @property184 def output(self) -> str:138- """The (standard) output as unicode string."""139- return self.stdout185+ """The terminal output as unicode string, as the user would see it.186 187+ .. versionchanged:: 8.2188+ No longer a proxy for ``self.stdout``. Now has its own independent stream189+ that is mixing `<stdout>` and `<stderr>`, in the order they were written.190+ """191+ return self.output_bytes.decode(self.runner.charset, "replace").replace(192+ "\r\n", "\n"193+ )194+195 @property196 def stdout(self) -> str:197 """The standard output as unicode string."""198 return self.stdout_bytes.decode(self.runner.charset, "replace").replace(1 unmodified line200 )201 202 @property203 def stderr(self) -> str:150- """The standard error as unicode string."""151- if self.stderr_bytes is None:152- raise ValueError("stderr not separately captured")204+ """The standard error as unicode string.205+206+ .. versionchanged:: 8.2207+ No longer raise an exception, always returns the `<stderr>` string.208+ """209 return self.stderr_bytes.decode(self.runner.charset, "replace").replace(210 "\r\n", "\n"211 )212 9 unmodified lines222 global interpreter state.223 224 :param charset: the character set for the input and output data.225 :param env: a dictionary with environment variables for overriding.170- :param echo_stdin: if this is set to `True`, then reading from stdin writes171- to stdout. This is useful for showing examples in226+ :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes227+ to `<stdout>`. This is useful for showing examples in228 some circumstances. Note that regular prompts229 will automatically echo the input.174- :param mix_stderr: if this is set to `False`, then stdout and stderr are175- preserved as independent streams. This is useful for176- Unix-philosophy apps that have predictable stdout and177- noisy stderr, such that each may be measured178- independently230+231+ .. versionchanged:: 8.2232+ ``mix_stderr`` parameter has been removed.233 """234 235 def __init__(236 self,237 charset: str = "utf-8",238 env: cabc.Mapping[str, str | None] | None = None,239 echo_stdin: bool = False,186- mix_stderr: bool = True,240 ) -> None:241 self.charset = charset242 self.env: cabc.Mapping[str, str | None] = env or {}243 self.echo_stdin = echo_stdin191- self.mix_stderr = mix_stderr244 245 def get_default_prog_name(self, cli: Command) -> str:246 """Given a command object it will return the default program name247 for it. The default is the `name` attribute or ``"root"`` if not15 unmodified lines263 self,264 input: str | bytes | t.IO[t.Any] | None = None,265 env: cabc.Mapping[str, str | None] | None = None,266 color: bool = False,215- ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO | None]]:267+ ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:268 """A context manager that sets up the isolation for invoking of a217- command line tool. This sets up stdin with the given input data269+ command line tool. This sets up `<stdin>` with the given input data270 and `os.environ` with the overrides from the given dictionary.271 This also rebinds some internals in Click to be mocked (like the272 prompt functionality).273 274 This is automatically done in the :meth:`invoke` method.275 224- :param input: the input stream to put into sys.stdin.276+ :param input: the input stream to put into `sys.stdin`.277 :param env: the environment overrides as dictionary.278 :param color: whether the output should contain color codes. The279 application can still override this explicitly.280 281+ .. versionadded:: 8.2282+ An additional output stream is returned, which is a mix of283+ `<stdout>` and `<stderr>` streams.284+285+ .. versionchanged:: 8.2286+ Always returns the `<stderr>` stream.287+288 .. versionchanged:: 8.0230- ``stderr`` is opened with ``errors="backslashreplace"``289+ `<stderr>` is opened with ``errors="backslashreplace"``290 instead of the default ``"strict"``.291 292 .. versionchanged:: 4.0293 Added the ``color`` parameter.8 unmodified lines302 formatting.FORCED_WIDTH = 80303 304 env = self.make_env(env)305 247- bytes_output = io.BytesIO()306+ stream_mixer = StreamMixer()307 308 if self.echo_stdin:309 bytes_input = echo_input = t.cast(251- t.BinaryIO, EchoingStdin(bytes_input, bytes_output)310+ t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)311 )312 313 sys.stdin = text_input = _NamedTextIOWrapper(314 bytes_input, encoding=self.charset, name="<stdin>", mode="r"4 unmodified lines319 # large chunk which is echoed early.320 text_input._CHUNK_SIZE = 1 # type: ignore321 322 sys.stdout = _NamedTextIOWrapper(264- bytes_output, encoding=self.charset, name="<stdout>", mode="w"323+ stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"324 )325 267- bytes_error = None268- if self.mix_stderr:269- sys.stderr = sys.stdout270- else:271- bytes_error = io.BytesIO()272- sys.stderr = _NamedTextIOWrapper(273- bytes_error,274- encoding=self.charset,275- name="<stderr>",276- mode="w",277- errors="backslashreplace",278- )326+ sys.stderr = _NamedTextIOWrapper(327+ stream_mixer.stderr,328+ encoding=self.charset,329+ name="<stderr>",330+ mode="w",331+ errors="backslashreplace",332+ )333 334 @_pause_echo(echo_input) # type: ignore335 def visible_input(prompt: str | None = None) -> str:336 sys.stdout.write(prompt or "")47 unmodified lines384 except Exception:385 pass386 else:387 os.environ[key] = value334- yield (bytes_output, bytes_error)388+ yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)389 finally:390 for key, value in old_env.items():391 if value is None:392 try:40 unmodified lines433 :param extra: the keyword arguments to pass to :meth:`main`.434 :param color: whether the output should contain color codes. The435 application can still override this explicitly.436 437+ .. versionadded:: 8.2438+ The result object has the ``output_bytes`` attribute with439+ the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would440+ see it in its terminal.441+442+ .. versionchanged:: 8.2443+ The result object always returns the ``stderr_bytes`` stream.444+445 .. versionchanged:: 8.0446 The result object has the ``return_value`` attribute with447 the value returned from the invoked command.448 48 unmodified lines497 exc_info = sys.exc_info()498 finally:499 sys.stdout.flush()500 stdout = outstreams[0].getvalue()439- if self.mix_stderr:440- stderr = None441- else:442- stderr = outstreams[1].getvalue() # type: ignore501+ stderr = outstreams[1].getvalue()502+ output = outstreams[2].getvalue()503 504 return Result(505 runner=self,506 stdout_bytes=stdout,507 stderr_bytes=stderr,508+ output_bytes=output,509 return_value=return_value,510 exit_code=exit_code,511 exception=exception,512 exc_info=exc_info, # type: ignore32 unmodified linesmodified:tests/test_termui.py+1 added-1 removed
244 unmodified lines245 @pytest.mark.parametrize(246 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]247 )248 def test_secho_non_text(runner, value, expect):249- with runner.isolation() as (out, _):249+ with runner.isolation() as (out, _, _):250 click.secho(value, nl=False, color=True, bg="magenta")251 result = out.getvalue()252 assert result == expect253 208 unmodified linesmodified:tests/test_testing.py+11 added-20 removed
299 unmodified lines300 301 def test_stderr():302 @click.command()303 def cli_stderr():304- click.echo("stdout")305- click.echo("stderr", err=True)304+ click.echo("1 - stdout")305+ click.echo("2 - stderr", err=True)306+ click.echo("3 - stdout")307+ click.echo("4 - stderr", err=True)308 307- runner = CliRunner(mix_stderr=False)308-309- result = runner.invoke(cli_stderr)310-311- assert result.output == "stdout\n"312- assert result.stdout == "stdout\n"313- assert result.stderr == "stderr\n"314-315- runner_mix = CliRunner(mix_stderr=True)309+ runner_mix = CliRunner()310 result_mix = runner_mix.invoke(cli_stderr)311 318- assert result_mix.output == "stdout\nstderr\n"319- assert result_mix.stdout == "stdout\nstderr\n"312+ assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"313+ assert result_mix.stdout == "1 - stdout\n3 - stdout\n"314+ assert result_mix.stderr == "2 - stderr\n4 - stderr\n"315 321- with pytest.raises(ValueError):322- assert result_mix.stderr # noqa B018323-316 @click.command()317 def cli_empty_stderr():318 click.echo("stdout")319 328- runner = CliRunner(mix_stderr=False)329-320+ runner = CliRunner()321 result = runner.invoke(cli_empty_stderr)322 323 assert result.output == "stdout\n"324 assert result.stdout == "stdout\n"75 unmodified lines400 def test_isolation_stderr_errors():401 """Writing to stderr should escape invalid characters instead of402 raising a UnicodeEncodeError.403 """413- runner = CliRunner(mix_stderr=False)404+ runner = CliRunner()405 415- with runner.isolation() as (_, err):406+ with runner.isolation() as (_, err, _):407 click.echo("\udce2", err=True, nl=False)408 409 assert err.getvalue() == b"\\udce2"modified:CHANGES.rst+4 added
37 unmodified lines38 ``False``. :pr:`2509`39 - Add ``get_help_extra`` method on ``Option`` to fetch the generated extra40 items used in ``get_help_record`` to render help text. :issue:`2516`41 :pr:`2517`42+- Keep stdout and stderr streams independent in ``CliRunner``. Always43+ collect stderr output and never raise an exception. Add a new44+ output` stream to simulate what the user sees in its terminal. Removes45+ the ``mix_stderr`` parameter in ``CliRunner``. :issue:`2522` :pr:`2523`46 47 48 Version 8.1.849 -------------1116 unmodified lines