Skip to content
Myr

Add `capture` parameter to `CliRunner` and revert default-mode `fileno` exposure

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

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 0039359 · Browse files · 4 files+383 added−90 removed
This commit

State

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

Trailers

  • Closes: #3384
  • Refs: #3244

Diff stats

4 files+383 added−90 removed

  • tests:+218 added−16 removed
  • other:+165 added−74 removed

4 files+383 added−90 removed

modified:docs/testing.md+50 added-38 removed
202 unmodified lines
203Prompts will be emulated so they write the input data to204the output stream as well. If hidden input is expected then this205does not happen.206207## File Descriptors and Low-Level I/O207## Capture modes208209{class}`CliRunner` captures output by replacing210`sys.stdout` and `sys.stderr` with in-memory211{class}`~io.BytesIO`-backed wrappers. This is212Python-level redirection: calls to {func}`~click.echo`,213{func}`print`, or `sys.stdout.write()` are captured, but214the wrappers have no OS-level file descriptor.209{class}`CliRunner` captures output by replacing `sys.stdout` and `sys.stderr`210with in-memory wrappers. The `capture` parameter controls which strategy is211used.212216Code that calls `fileno()` on `sys.stdout` or217`sys.stderr`, like {mod}`faulthandler`,218{mod}`subprocess`, or C extensions, would normally crash219with {exc}`io.UnsupportedOperation` inside220{class}`CliRunner`.213### `capture="sys"` (default)214222To avoid this, {class}`CliRunner` preserves the original223stream's file descriptor and exposes it via `fileno()` on224the replacement wrapper.215Captures Python-level writes (`print()`, `click.echo()`, `sys.stdout.write()`).216It is fast and sufficient for most Click applications.217226This means:227- **Python-level writes** (`print()`, `click.echo()`,228 ...) are captured as usual.229- **fd-level writes** (C code writing directly to the230 file descriptor) go to the original terminal and are231 **not** captured.218Code that holds a reference to the original `sys.stdout` (like a library that219does `from sys import stdout` at import time) bypasses the capture and its220output is lost.221233This is the same trade-off that234[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)235makes with its two capture modes:222In this mode `sys.stdout.fileno()` and `sys.stderr.fileno()` raise223{exc}`io.UnsupportedOperation`, matching the pre-`8.3.3` behavior. C-level224consumers ({mod}`faulthandler`, {mod}`subprocess`, C extensions) that expect a225real file descriptor must opt into the `capture="fd"` mode.226237- `capsys`, which captures Python-level output, where238 `fileno()` raises `UnsupportedOperation` and fd-level239 writes are not captured.240- `capfd`, which captures fd-level output via241 `os.dup2()`, where `fileno()` works and fd-level242 writes *are* captured.227### `capture="fd"`228244Rather than implementing a full `capfd`-style mechanism,245{class}`CliRunner` takes the simpler path: expose the246original `fd` so that standard library helpers keep247working, while accepting that their output is not248captured.229Redirects OS file descriptors `1` and `2` to a temporary file via230{func}`os.dup2`, inspired by [Pytest's231`capfd`](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html).232This catches output that bypasses `sys.stdout`, including:233250```{versionchanged} 8.3.3251`fileno()` on the redirected streams now returns the252original stream's file descriptor instead of raising.234- Stale references to the original `sys.stdout` and `sys.stderr`.235- Logging frameworks that cache the original stream (like `structlog` or the236 stdlib's `logging` module).237- C extensions and subprocesses that write directly to `fd 1` or `fd 2`.238239```python240from click.testing import CliRunner241from myapp import cli242243244def test_captures_everything():245 runner = CliRunner(capture="fd")246 result = runner.invoke(cli)247 # result.stdout contains both Python-level and fd-level output248 assert "expected output" in result.stdout249```250251In this mode `sys.stdout.fileno()` returns the saved (pre-redirection) `fd`, so252{mod}`faulthandler` and similar consumers keep working. Writes to `fd 1` and253`fd 2` land in the capture tmpfile, so `os.dup2()` calls inside the CLI no254longer leak into the host runner's stdout.255256```{note}257`capture="fd"` is not available on Windows.258```259260```{versionchanged} 8.4.0261Added the `capture` parameter. The default `sys` mode no longer exposes the262original `fd` through `fileno()`, reverting the change introduced in `8.3.3`263that broke Pytest's `fd`-level capture teardown. Use `capture="fd"` to restore264that behavior with proper isolation.265```
modified:src/click/testing.py+103 added-36 removed
20 unmodified lines
21 from _typeshed import ReadableBuffer2223 from .core import Command2425CaptureMode = t.Literal["sys", "fd"]262728class EchoingStdin:29 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:30 self._input = input31 self._output = output
36 unmodified lines
68 yield69 stream._paused = False707172class _FDCapture:73 """Redirect a file descriptor to a temporary file for capture.7475 Saves the current target of *targetfd* via :func:`os.dup`, then76 redirects it to a temporary file via :func:`os.dup2`. On77 :meth:`stop`, restores the original ``fd`` and returns the captured78 bytes. Inspired by Pytest's ``FDCapture``.7980 .. versionadded:: 8.4.081 """8283 def __init__(self, targetfd: int) -> None:84 self._targetfd = targetfd85 self.saved_fd: int = -186 self._tmpfile: t.BinaryIO | None = None8788 def start(self) -> None:89 self.saved_fd = os.dup(self._targetfd)90 self._tmpfile = tempfile.TemporaryFile(buffering=0)91 os.dup2(self._tmpfile.fileno(), self._targetfd)9293 def stop(self) -> bytes:94 assert self._tmpfile is not None, "_FDCapture.start() was not called"95 os.dup2(self.saved_fd, self._targetfd)96 os.close(self.saved_fd)97 self.saved_fd = -198 self._tmpfile.seek(0)99 data = self._tmpfile.read()100 self._tmpfile.close()101 self._tmpfile = None102 return data103104105class BytesIOCopy(io.BytesIO):106 """Patch ``io.BytesIO`` to let the written stream be copied to another.107108 .. versionadded:: 8.2
29 unmodified lines
138class _NamedTextIOWrapper(io.TextIOWrapper):139 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``140 that does not close its underlying buffer.141107 An optional ``original_fd`` preserves the file descriptor of the108 stream being replaced, so that C-level consumers that call109 :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.110 Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`111 for details.112113 .. versionchanged:: 8.3.3114 Added ``original_fd`` parameter and :meth:`fileno` override.142 When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to143 point at the saved (pre-redirection) ``fd``, so C-level consumers that call144 :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In145 the default ``sys`` mode ``_original_fd`` stays at ``-1`` and146 :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the147 pre-``8.3.3`` behavior.148 """149150 def __init__(151 self,152 buffer: t.BinaryIO,153 name: str,154 mode: str,122 *,123 original_fd: int = -1,155 **kwargs: t.Any,156 ) -> None:157 super().__init__(buffer, **kwargs)158 self._name = name159 self._mode = mode129 self._original_fd = original_fd160 self._original_fd: int = -1161162 def close(self) -> None:163 """The buffer this object contains belongs to some other object,164 so prevent the default ``__del__`` implementation from closing
2 unmodified lines
167 .. versionadded:: 8.3.2168 """169170 def fileno(self) -> int:140 """Return the file descriptor of the original stream, if one was141 provided at construction time.142143 This allows C-level consumers (``faulthandler``, ``subprocess``,144 signal handlers, ...) to obtain a valid fd without crashing, even145 though the Python-level writes are redirected to an in-memory146 buffer.147148 .. versionadded:: 8.3.3171 """Return the file descriptor of the saved original stream when172 ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to173 :class:`~io.TextIOWrapper`, which raises174 :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer.175 """176 if self._original_fd >= 0:177 return self._original_fd178 return super().fileno()
118 unmodified lines
297 some circumstances. Note that regular prompts298 will automatically echo the input.299 :param catch_exceptions: Whether to catch any exceptions other than300 ``SystemExit`` when running :meth:`~CliRunner.invoke`.301 :param capture: Selects the output capture strategy. ``sys`` (default)302 captures Python-level writes only and leaves303 :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so304 user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot305 clobber the host runner's stdout. ``fd`` redirects file descriptors306 ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching307 output from stale stream references, C extensions, and subprocesses.308 ``fd`` is not supported on Windows.309310 .. versionchanged:: 8.4.0311 Added the ``capture`` parameter. The default ``sys`` mode no longer312 exposes the original fd through :meth:`fileno`, reverting the change313 introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture314 teardown. Use ``capture="fd"`` to restore that behavior with proper315 isolation. :issue:`3384`316317 .. versionchanged:: 8.2318 Added the ``catch_exceptions`` parameter.319320 .. versionchanged:: 8.2
5 unmodified lines
326 charset: str = "utf-8",327 env: cabc.Mapping[str, str | None] | None = None,328 echo_stdin: bool = False,329 catch_exceptions: bool = True,330 capture: CaptureMode = "sys",331 ) -> None:332 if capture not in {"sys", "fd"}:333 raise ValueError(334 f"capture={capture!r} is not valid. Choose from 'sys' or 'fd'."335 )336 if capture == "fd" and sys.platform == "win32":337 raise ValueError(338 f"capture={capture!r} is not supported on Windows. Use 'sys'."339 )340 self.charset = charset341 self.env: cabc.Mapping[str, str | None] = env or {}342 self.echo_stdin = echo_stdin343 self.catch_exceptions = catch_exceptions344 self.capture: CaptureMode = capture345346 def get_default_prog_name(self, cli: Command) -> str:347 """Given a command object it will return the default program name348 for it. The default is the `name` attribute or ``"root"`` if not
56 unmodified lines
405 env = self.make_env(env)406407 stream_mixer = StreamMixer()408358 # Preserve the original file descriptors so that C-level359 # consumers (faulthandler, subprocess, etc.) can still obtain a360 # valid fd from the redirected streams. The original streams361 # may themselves lack a fileno() (e.g. when CliRunner is used362 # inside pytest's capsys), so we fall back to -1.363 def _safe_fileno(stream: t.IO[t.Any]) -> int:364 try:365 return stream.fileno()366 except (AttributeError, io.UnsupportedOperation):367 return -1368369 old_stdout_fd = _safe_fileno(old_stdout)370 old_stderr_fd = _safe_fileno(old_stderr)371409 if self.echo_stdin:410 bytes_input = echo_input = t.cast(411 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)412 )
11 unmodified lines
424 stream_mixer.stdout,425 encoding=self.charset,426 name="<stdout>",427 mode="w",391 original_fd=old_stdout_fd,428 )429430 sys.stderr = _NamedTextIOWrapper(431 stream_mixer.stderr,432 encoding=self.charset,433 name="<stderr>",434 mode="w",435 errors="backslashreplace",400 original_fd=old_stderr_fd,436 )437438 @_pause_echo(echo_input) # type: ignore439 def visible_input(prompt: str | None = None) -> str:
173 unmodified lines
613 exc_info = None614 if catch_exceptions is None:615 catch_exceptions = self.catch_exceptions616617 # Set up fd capture before isolation replaces sys.stdout and sys.stderr.618 cap_out: _FDCapture | None = None619 cap_err: _FDCapture | None = None620621 if self.capture == "fd":622 cap_out = _FDCapture(1)623 cap_err = _FDCapture(2)624 try:625 cap_out.start()626 cap_err.start()627 except OSError:628 cap_out = cap_err = None629630 with self.isolation(input=input, env=env, color=color) as outstreams:631 # Point the captured streams' fileno() at the saved (original)632 # fd so that C-level consumers like faulthandler keep working633 # while fd 1/2 are redirected to the capture tmpfile.634 if cap_out is not None and cap_err is not None:635 sys.stdout._original_fd = cap_out.saved_fd # type: ignore[union-attr]636 sys.stderr._original_fd = cap_err.saved_fd # type: ignore[union-attr]637638 return_value = None639 exception: BaseException | None = None640 exit_code = 0641
32 unmodified lines
674 exc_info = sys.exc_info()675 finally:676 sys.stdout.flush()677 sys.stderr.flush()678679 # Stop fd capture and merge the captured bytes into680 # the stdout/stderr BytesIO streams. BytesIOCopy mirrors681 # those writes into outstreams[2] automatically.682 if cap_out is not None and cap_err is not None:683 fd_out = cap_out.stop()684 fd_err = cap_err.stop()685 if fd_out:686 outstreams[0].write(fd_out)687 if fd_err:688 outstreams[1].write(fd_err)689690 stdout = outstreams[0].getvalue()691 stderr = outstreams[1].getvalue()692 output = outstreams[2].getvalue()693
43 unmodified lines
modified:tests/test_testing.py+218 added-16 removed
1import faulthandler2import io3import os4import pdb5import sys6from io import BytesIO
515 unmodified lines
522523 assert pdb.Pdb.__init__ is original524525525def test_faulthandler_enable(runner):526 """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527 ``io.UnsupportedOperation: fileno``.526needs_fd_capture = pytest.mark.skipif(527 sys.platform == "win32",528 reason="fd capture not supported on Windows",529)530529 ``faulthandler.enable()`` needs a real OS file descriptor to register530 its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531 ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.531533 Reproduce:https://github.com/pallets/click/issues/2865532def test_capture_invalid_mode():533 """Invalid capture mode raises ValueError."""534 with pytest.raises(ValueError, match="capture"):535 CliRunner(capture="invalid") # type: ignore[arg-type]536537538@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")539def test_capture_fd_windows_error():540 """fd capture raises ValueError on Windows."""541 with pytest.raises(ValueError, match="not supported on Windows"):542 CliRunner(capture="fd")543544545@needs_fd_capture546def test_capture_fd_os_write():547 """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""548549 @click.command()550 def cli():551 click.echo("python stdout")552 os.write(1, b"fd stdout\n")553 os.write(2, b"fd stderr\n")554555 runner = CliRunner(capture="fd")556 result = runner.invoke(cli)557 assert "python stdout" in result.stdout558 assert "fd stdout" in result.stdout559 assert "fd stderr" in result.stderr560561562@needs_fd_capture563def test_capture_fd_stale_reference():564 """capture='fd' captures writes from stale stdout references (issue #2874).565566 Simulates ``from sys import stdout`` at import time, which grabs567 the real stdout connected to fd 1. The stale object's underlying568 FileIO uses fd 1, so redirecting fd 1 captures its writes.569 """570 # open(1, ..., closefd=False) creates a writer whose underlying571 # FileIO uses fd 1 directly. This mirrors the real scenario:572 # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->573 # FileIO(fd=1).574 stale_stdout = open(1, "w", closefd=False) # noqa: SIM115575576 @click.command()537 @click.option("--flag", type=bool, default=True)538 def cli(flag):539 click.echo("Executing main function...")540 if flag:541 click.echo("Registering faulthandler")542 faulthandler.enable()543 click.echo("Finished executing main function.")577 def cli():578 stale_stdout.write("stale write\n")579 stale_stdout.flush()580 click.echo("normal write")581582 runner = CliRunner(capture="fd")545 result = runner.invoke(cli, ["--flag", True])583 result = runner.invoke(cli)584 assert "normal write" in result.stdout585 assert "stale write" in result.stdout586587588@needs_fd_capture589def test_capture_fd_logging_handler(tmp_path):590 """capture='fd' captures logging output from a handler holding a stale591 stderr reference (issue #2827).592593 stdlib logging.StreamHandler grabs sys.stderr at configuration time.594 Under normal CliRunner (sys-level capture), the handler still writes595 to the original stream object and output is lost. fd-level capture596 redirects the underlying file descriptor, so the writes are captured.597 """598 import logging599600 # Create a writer backed by the real fd 2, simulating a handler601 # configured at import time before pytest or CliRunner replaced602 # sys.stderr. open(2, closefd=False) mirrors the real scenario:603 # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->604 # FileIO(fd=2).605 stale_stderr = open(2, "w", closefd=False) # noqa: SIM115606 handler = logging.StreamHandler(stale_stderr)607 handler.setFormatter(logging.Formatter("%(message)s"))608609 logger = logging.getLogger(f"click_test_{tmp_path.name}")610 logger.addHandler(handler)611 logger.setLevel(logging.INFO)612 logger.propagate = False613614 @click.command()615 def cli():616 logger.info("log from stale handler")617 click.echo("normal echo")618619 # sys-level capture misses the log line (it bypasses sys.stderr).620 runner_sys = CliRunner(capture="sys")621 result_sys = runner_sys.invoke(cli)622 assert "normal echo" in result_sys.output623 assert "log from stale handler" not in result_sys.output624625 # fd-level capture catches it by redirecting fd 2.626 runner_fd = CliRunner(capture="fd")627 result_fd = runner_fd.invoke(cli)628 assert "normal echo" in result_fd.output629 assert "log from stale handler" in result_fd.output630631 logger.removeHandler(handler)632633634@needs_fd_capture635def test_capture_fd_faulthandler():636 """faulthandler.enable() works with capture='fd' (issue #2865)."""637638 @click.command()639 def cli():640 faulthandler.enable()641 click.echo("after faulthandler")642643 runner = CliRunner(capture="fd")644 result = runner.invoke(cli)645 assert result.exit_code == 0646 assert "after faulthandler" in result.output647648649def test_capture_sys_fileno_raises():650 """capture='sys' leaves fileno() raising UnsupportedOperation, so user651 code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host652 runner's stdout (issue #3384).653 """654655 @click.command()656 def cli():657 with pytest.raises(io.UnsupportedOperation):658 sys.stdout.fileno()659 with pytest.raises(io.UnsupportedOperation):660 sys.stderr.fileno()661 click.echo("ok")662663 runner = CliRunner(capture="sys")664 result = runner.invoke(cli)665 assert result.exit_code == 0, result.output547 assert "Finished executing main function." in result.output666 assert "ok" in result.stdout667668669@needs_fd_capture670def test_capture_fd_stderr_separation():671 """capture='fd' properly separates fd-level stdout and stderr."""672673 @click.command()674 def cli():675 click.echo("py-out")676 click.echo("py-err", err=True)677 os.write(1, b"fd-out\n")678 os.write(2, b"fd-err\n")679680 runner = CliRunner(capture="fd")681 result = runner.invoke(cli)682 assert "py-out" in result.stdout683 assert "fd-out" in result.stdout684 assert "py-err" in result.stderr685 assert "fd-err" in result.stderr686 # Mixed output has all of them687 assert "py-out" in result.output688 assert "py-err" in result.output689 assert "fd-out" in result.output690 assert "fd-err" in result.output691692693@needs_fd_capture694def test_capture_fd_nesting():695 """Nested CliRunner.invoke() with fd capture works correctly."""696697 @click.command("inner")698 def inner_cli():699 click.echo("inner")700701 @click.command("outer")702 def outer_cli():703 click.echo("outer")704 os.write(1, b"outer fd\n")705 inner_runner = CliRunner(capture="fd")706 inner_result = inner_runner.invoke(inner_cli)707 click.echo(f"inner captured: {inner_result.stdout.strip()}")708709 runner = CliRunner(capture="fd")710 result = runner.invoke(outer_cli)711 assert "outer" in result.stdout712 assert "outer fd" in result.stdout713 assert "inner captured: inner" in result.stdout714715716@needs_fd_capture717@pytest.mark.parametrize("runner_capture", ["sys", "fd"])718@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])719def test_capture_pytest_matrix(720 request: pytest.FixtureRequest,721 runner_capture: str,722 pytest_fixture: str,723) -> None:724 """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""725 pytest_cap = request.getfixturevalue(pytest_fixture)726727 @click.command()728 def cli() -> None:729 click.echo("inside-stdout")730 click.echo("inside-stderr", err=True)731732 runner = CliRunner(capture=runner_capture)733 result = runner.invoke(cli)734735 # CliRunner sees Click's output.736 assert result.exit_code == 0737 assert "inside-stdout" in result.stdout738 assert "inside-stderr" in result.stderr739740 # Pytest capture machinery is still working after invoke().741 print("post-invoke-stdout")742 print("post-invoke-stderr", file=sys.stderr)743 captured = pytest_cap.readouterr()744 assert "post-invoke-stdout" in captured.out745 assert "post-invoke-stderr" in captured.err746747 # Click output is not leaking into Pytest.748 assert "inside-stdout" not in captured.out749 assert "inside-stderr" not in captured.err
modified:CHANGES.rst+12 added
55 unmodified lines
56- Show custom error messages from types when :func:`prompt` with57 ``hide_input=True`` fails validation, instead of always showing a58 generic message. Built-in type messages mask the input value.59 :issue:`2809` :pr:`3256`60- Add ``capture`` parameter to :class:`CliRunner` with two modes: ``sys``61 (default) and ``fd``. ``fd`` redirects file descriptors ``1`` and ``2``62 via :func:`os.dup2` so output that bypasses ``sys.stdout`` (stale stream63 references, C extensions, subprocesses, ``faulthandler``) is captured64 with proper isolation. :issue:`854` :issue:`2412` :issue:`2468`65 :issue:`2497` :issue:`2761` :issue:`2827` :issue:`2865`66- Revert the ``8.3.3`` change that exposed the original file descriptor67 via ``fileno()`` on the redirected ``CliRunner`` streams in the default68 capture mode. ``os.dup2(w, sys.stdout.fileno())`` calls inside a CLI no69 longer mutate the host runner's stdout, which broke Pytest's ``fd``-level70 capture teardown. C-level consumers that need a real ``fd`` should use71 ``capture="fd"``. :issue:`3384` :pr:`3391`7273Version 8.3.374-------------75
1364 unmodified lines