Expose original file descriptor in `CliRunner`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix #2865
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 878de46 · Browse files · 4 files·+137 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+137 added−6 removed
- tests:+26 added−0 removed
- other:+111 added−6 removed
Provenance
- Commit
8762c77- Tree
bda38d8- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
878de46
4 files changed+137 added−6 removed
modified:docs/testing.md+48 added
194 unmodified lines195 196 Prompts will be emulated so they write the input data to197 the output stream as well. If hidden input is expected then this198 does not happen.199+200+## File Descriptors and Low-Level I/O201+202+{class}`CliRunner` captures output by replacing203+`sys.stdout` and `sys.stderr` with in-memory204+{class}`~io.BytesIO`-backed wrappers. This is205+Python-level redirection: calls to {func}`~click.echo`,206+{func}`print`, or `sys.stdout.write()` are captured, but207+the wrappers have no OS-level file descriptor.208+209+Code that calls `fileno()` on `sys.stdout` or210+`sys.stderr`, like {mod}`faulthandler`,211+{mod}`subprocess`, or C extensions, would normally crash212+with {exc}`io.UnsupportedOperation` inside213+{class}`CliRunner`.214+215+To avoid this, {class}`CliRunner` preserves the original216+stream's file descriptor and exposes it via `fileno()` on217+the replacement wrapper.218+219+This means:220+- **Python-level writes** (`print()`, `click.echo()`,221+ ...) are captured as usual.222+- **fd-level writes** (C code writing directly to the223+ file descriptor) go to the original terminal and are224+ **not** captured.225+226+This is the same trade-off that227+[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228+makes with its two capture modes:229+230+- `capsys`, which captures Python-level output, where231+ `fileno()` raises `UnsupportedOperation` and fd-level232+ writes are not captured.233+- `capfd`, which captures fd-level output via234+ `os.dup2()`, where `fileno()` works and fd-level235+ writes *are* captured.236+237+Rather than implementing a full `capfd`-style mechanism,238+{class}`CliRunner` takes the simpler path: expose the239+original `fd` so that standard library helpers keep240+working, while accepting that their output is not241+captured.242+243+```{versionchanged} 8.3.3244+`fileno()` on the redirected streams now returns the245+original stream's file descriptor instead of raising.246+```modified:src/click/testing.py+59 added-6 removed
99 unmodified lines100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101 102 103 class _NamedTextIOWrapper(io.TextIOWrapper):104+ """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``105+ that does not close its underlying buffer.106+107+ 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.112+113+ .. versionchanged:: 8.3.3114+ Added ``original_fd`` parameter and :meth:`fileno` override.115+ """116+117 def __init__(105- self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any118+ self,119+ buffer: t.BinaryIO,120+ name: str,121+ mode: str,122+ *,123+ original_fd: int = -1,124+ **kwargs: t.Any,125 ) -> None:126 super().__init__(buffer, **kwargs)127 self._name = name128 self._mode = mode129+ self._original_fd = original_fd130 131 def close(self) -> None:112- """113- The buffer this object contains belongs to some other object, so114- prevent the default __del__ implementation from closing that buffer.132+ """The buffer this object contains belongs to some other object,133+ so prevent the default ``__del__`` implementation from closing134+ that buffer.135 136 .. versionadded:: 8.3.2137 """118- ...138 139+ def fileno(self) -> int:140+ """Return the file descriptor of the original stream, if one was141+ provided at construction time.142+143+ 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.147+148+ .. versionadded:: 8.3.3149+ """150+ if self._original_fd >= 0:151+ return self._original_fd152+ return super().fileno()153+154 @property155 def name(self) -> str:156 return self._name157 196 unmodified lines354 env = self.make_env(env)355 356 stream_mixer = StreamMixer()357 358+ # 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 -1368+369+ old_stdout_fd = _safe_fileno(old_stdout)370+ old_stderr_fd = _safe_fileno(old_stderr)371+372 if self.echo_stdin:373 bytes_input = echo_input = t.cast(374 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)375 )7 unmodified lines383 # large chunk which is echoed early.384 text_input._CHUNK_SIZE = 1 # type: ignore385 386 sys.stdout = _NamedTextIOWrapper(339- stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"387+ stream_mixer.stdout,388+ encoding=self.charset,389+ name="<stdout>",390+ mode="w",391+ original_fd=old_stdout_fd,392 )393 394 sys.stderr = _NamedTextIOWrapper(395 stream_mixer.stderr,396 encoding=self.charset,397 name="<stderr>",398 mode="w",399 errors="backslashreplace",400+ original_fd=old_stderr_fd,401 )402 403 @_pause_echo(echo_input) # type: ignore404 def visible_input(prompt: str | None = None) -> str:268 unmodified linesmodified:tests/test_testing.py+26 added
1+import faulthandler2 import os3 import pdb4 import sys5 from io import BytesIO513 unmodified lines519 runner = CliRunner()520 runner.invoke(cli)521 522 assert pdb.Pdb.__init__ is original523+524+525+def test_faulthandler_enable(runner):526+ """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527+ ``io.UnsupportedOperation: fileno``.528+529+ ``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.532+533+ Reproduce:https://github.com/pallets/click/issues/2865534+ """535+536+ @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.")544+545+ result = runner.invoke(cli, ["--flag", True])546+ assert result.exit_code == 0, result.output547+ assert "Finished executing main function." in result.outputmodified:CHANGES.rst+4 added
19 unmodified lines20 - Add optional randomized parallel test execution using ``pytest-randomly`` and21 ``pytest-xdist`` to detect test pollution and race conditions. :pr:`3151`22 - Add contributor documentation for running stress tests, randomized23 parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`24+- ``CliRunner``'s redirected streams now expose the original file descriptor25+ via ``fileno()``, so that ``faulthandler``, ``subprocess``, and other26+ C-level consumers no longer crash with ``io.UnsupportedOperation``.27+ :issue:`2865`28 29 Version 8.3.230 -------------31 1323 unmodified lines