Skip to content
Myr

Expose original file descriptor in `CliRunner` (#3244)

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

authored by Rowlando13 · committed by GitHub · parents 32010b9, 8762c77 · 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

4 files+137 added−6 removed

modified:docs/testing.md+48 added
194 unmodified lines
195196Prompts will be emulated so they write the input data to197the output stream as well. If hidden input is expected then this198does not happen.199200## File Descriptors and Low-Level I/O201202{class}`CliRunner` captures output by replacing203`sys.stdout` and `sys.stderr` with in-memory204{class}`~io.BytesIO`-backed wrappers. This is205Python-level redirection: calls to {func}`~click.echo`,206{func}`print`, or `sys.stdout.write()` are captured, but207the wrappers have no OS-level file descriptor.208209Code that calls `fileno()` on `sys.stdout` or210`sys.stderr`, like {mod}`faulthandler`,211{mod}`subprocess`, or C extensions, would normally crash212with {exc}`io.UnsupportedOperation` inside213{class}`CliRunner`.214215To avoid this, {class}`CliRunner` preserves the original216stream's file descriptor and exposes it via `fileno()` on217the replacement wrapper.218219This 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.225226This is the same trade-off that227[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228makes with its two capture modes:229230- `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.236237Rather than implementing a full `capfd`-style mechanism,238{class}`CliRunner` takes the simpler path: expose the239original `fd` so that standard library helpers keep240working, while accepting that their output is not241captured.242243```{versionchanged} 8.3.3244`fileno()` on the redirected streams now returns the245original stream's file descriptor instead of raising.246```
modified:src/click/testing.py+59 added-6 removed
99 unmodified lines
100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101102103class _NamedTextIOWrapper(io.TextIOWrapper):104 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``105 that does not close its underlying buffer.106107 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.115 """116117 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_fd130131 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.135136 .. versionadded:: 8.3.2137 """118 ...138139 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.3149 """150 if self._original_fd >= 0:151 return self._original_fd152 return super().fileno()153154 @property155 def name(self) -> str:156 return self._name157
196 unmodified lines
354 env = self.make_env(env)355356 stream_mixer = StreamMixer()357358 # 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)371372 if self.echo_stdin:373 bytes_input = echo_input = t.cast(374 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)375 )
7 unmodified lines
383 # large chunk which is echoed early.384 text_input._CHUNK_SIZE = 1 # type: ignore385386 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 )393394 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 )402403 @_pause_echo(echo_input) # type: ignore404 def visible_input(prompt: str | None = None) -> str:
268 unmodified lines
modified:tests/test_testing.py+26 added
1import faulthandler2import os3import pdb4import sys5from io import BytesIO
513 unmodified lines
519 runner = CliRunner()520 runner.invoke(cli)521522 assert pdb.Pdb.__init__ is original523524525def test_faulthandler_enable(runner):526 """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527 ``io.UnsupportedOperation: fileno``.528529 ``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.532533 Reproduce:https://github.com/pallets/click/issues/2865534 """535536 @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.")544545 result = runner.invoke(cli, ["--flag", True])546 assert result.exit_code == 0, result.output547 assert "Finished executing main function." in result.output
modified:CHANGES.rst+4 added
19 unmodified lines
20- 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`2829Version 8.3.230-------------31
1323 unmodified lines