`click.get_pager_file`: add tests (#1572 followup) (#3405)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 7c99ebe, b761eda · Browse files · 3 files·+253 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+253 added−13 removed
- tests:+228 added−0 removed
- other:+25 added−13 removed
Provenance
- Commit
63274a7- Tree
f24fd2a- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
7c99ebe- Parent 2
b761eda
3 files changed+253 added−13 removed
modified:src/click/_termui_impl.py+24 added-12 removed
30 unmodified lines31 from .utils import echo32 33 V = t.TypeVar("V")34 35+36+class _BufferedTextPagerStream(t.Protocol):37+ buffer: t.BinaryIO38+39+40+def _has_binary_buffer(41+ stream: t.BinaryIO | t.TextIO,42+) -> t.TypeGuard[_BufferedTextPagerStream]:43+ # TextIO is wider than TextIOWrapper; text-only streams such as StringIO44+ # are valid TextIO values but do not expose a binary buffer to wrap.45+ return getattr(stream, "buffer", None) is not None46+47+48 if os.name == "nt":49 BEFORE_BAR = "\r"50 AFTER_BAR = "\n"51 else:378 unmodified lines430 @contextlib.contextmanager431 def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:432 """Context manager.433 Yields a writable file-like object which can be used as an output pager.421- .. versionadded:: 8.2434+ .. versionadded:: 8.4435 :param color: controls if the pager supports ANSI colors or not. The436 default is autodetection.437 """438 with _pager_contextmanager(color=color) as (stream, encoding, color):426- if not isinstance(stream, MaybeStripAnsi):427- if hasattr(stream, "buffer"):428- # Real TextIO with buffer - unwrap and wrap in MaybeStripAnsi429- stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)430- elif not getattr(stream, "encoding", None):431- # BinaryIO - wrap directly in MaybeStripAnsi432- stream = MaybeStripAnsi(stream, color=color, encoding=encoding)433- else:434- # StringIO - add .color attribute only, no ANSI stripping435- stream.color = color # type: ignore[attr-defined]439+ # Split streams by capabilities rather than the abstract TextIO /440+ # BinaryIO annotations: buffered text streams can be unwrapped to bytes,441+ # while text-only streams are yielded as-is.442+ if _has_binary_buffer(stream):443+ # Text stream backed by a binary buffer.444+ stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)445+ elif isinstance(stream, t.BinaryIO):446+ # Binary stream447+ stream = MaybeStripAnsi(stream, color=color, encoding=encoding)448 try:437- yield t.cast(t.TextIO, stream)449+ yield stream450 finally:451 stream.flush()452 453 456 unmodified linesmodified:tests/test_termui.py+228 added
1+import contextlib2+import io3 import platform4 import shlex5+import shutil6+import sys7 import tempfile8 import time9 from unittest.mock import patch10 11 import pytest12 13+import click14 import click._termui_impl15 from click._compat import WIN16 from click._termui_impl import Editor17 from click._utils import UNSET606 unmodified lines624 """625 assert shlex.split(pager_env) == expected_parts626 627 628+def _get_real_pager_command() -> str:629+ """Return a real pager binary path used to exercise the pipe pager branch.630+631+ ..warning::632+ Unix-only for now: ``more.com`` on Windows is interactive and goes633+ through ``_tempfilepager`` rather than ``_pipepager``.634+ """635+ pager_path = shutil.which("cat")636+ assert pager_path is not None, "cat not available"637+ return pager_path638+639+640+def _run_get_pager_file_with_real_pager(monkeypatch, capfd, writer, color=False):641+ """Run through the pipe pager backend selected by ``PAGER``."""642+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)643+ monkeypatch.setitem(644+ click._termui_impl.os.environ, "PAGER", _get_real_pager_command()645+ )646+647+ with click.get_pager_file(color=color) as pager:648+ writer(pager)649+650+ # The real pager writes to the process stdout; stderr should stay quiet.651+ out, err = capfd.readouterr()652+ assert err == ""653+ return out654+655+656+def _write_pager_from_multiple_sites(pager):657+ pager.write("prefix\n")658+ click.echo("middle", file=pager)659+ pager.write("suffix\n")660+661+662+@pytest.mark.skipif(663+ WIN,664+ reason="Exercises the pipe pager path; Windows uses _tempfilepager.",665+)666+@pytest.mark.parametrize(667+ ("writer", "color", "expected"),668+ [669+ pytest.param(670+ _write_pager_from_multiple_sites,671+ False,672+ "prefix\nmiddle\nsuffix\n",673+ id="multiple write sites",674+ ),675+ pytest.param(676+ lambda pager: pager.write("hello\n"), False, "hello\n", id="plain text"677+ ),678+ pytest.param(679+ lambda pager: pager.write(click.style("hello", fg="red") + "\n"),680+ False,681+ "hello\n",682+ id="strip ansi",683+ ),684+ pytest.param(685+ lambda pager: pager.write(click.style("hello", fg="red") + "\n"),686+ True,687+ click.style("hello", fg="red") + "\n",688+ id="preserve ansi",689+ ),690+ pytest.param(lambda pager: pager.write(""), False, "", id="empty string"),691+ ],692+)693+def test_get_pager_file_with_real_pager_binary_stream(694+ monkeypatch, capfd, writer, color, expected695+):696+ """A real pager should exercise the BinaryIO branch."""697+ output = _run_get_pager_file_with_real_pager(698+ monkeypatch, capfd, writer, color=color699+ )700+701+ assert output == expected702+703+704+@pytest.mark.skipif(705+ WIN,706+ reason="Exercises the pipe pager path; Windows uses _tempfilepager.",707+)708+@pytest.mark.parametrize(709+ ("color", "expected"),710+ [711+ pytest.param(False, "hello\n", id="strip ansi"),712+ pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),713+ ],714+)715+def test_echo_via_pager_real_pager_handles_ansi(monkeypatch, capfd, color, expected):716+ """``echo_via_pager`` should honor ``color`` like ``get_pager_file``."""717+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)718+ monkeypatch.setitem(719+ click._termui_impl.os.environ, "PAGER", _get_real_pager_command()720+ )721+722+ click.echo_via_pager(click.style("hello", fg="red"), color=color)723+724+ out, err = capfd.readouterr()725+ assert err == ""726+ assert out == expected727+728+729+def test_get_pager_file_pager_missing_binary_falls_back(monkeypatch, tmp_path):730+ """``PAGER`` pointing to a nonexistent binary falls back to the text stdout."""731+ pager_out = tmp_path / "pager_out.txt"732+733+ monkeypatch.setitem(734+ click._termui_impl.os.environ,735+ "PAGER",736+ "click-tests-nonexistent-pager-9b3f2",737+ )738+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)739+740+ with pager_out.open("w", encoding="utf-8") as text_stream:741+ monkeypatch.setattr(742+ click._termui_impl, "_default_text_stdout", lambda: text_stream743+ )744+745+ with click.get_pager_file() as pager:746+ pager.write("hello\n")747+748+ assert pager_out.read_text(encoding="utf-8") == "hello\n"749+750+751+def test_get_pager_file_pager_unset_falls_back_when_no_default(monkeypatch, tmp_path):752+ """``PAGER`` unset still works when the platform default isn't installed."""753+ pager_out = tmp_path / "pager_out.txt"754+755+ monkeypatch.delitem(click._termui_impl.os.environ, "PAGER", raising=False)756+ monkeypatch.delitem(click._termui_impl.os.environ, "TERM", raising=False)757+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)758+ monkeypatch.setattr(shutil, "which", lambda _name: None)759+760+ with pager_out.open("w", encoding="utf-8") as text_stream:761+ monkeypatch.setattr(762+ click._termui_impl, "_default_text_stdout", lambda: text_stream763+ )764+765+ with click.get_pager_file() as pager:766+ pager.write("hello\n")767+768+ assert pager_out.read_text(encoding="utf-8") == "hello\n"769+770+771+@pytest.mark.parametrize(772+ ("color", "expected"),773+ [774+ pytest.param(False, "hello\n", id="strip ansi"),775+ pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),776+ ],777+)778+def test_get_pager_file_nullpager_wraps_textio_stream(779+ monkeypatch, tmp_path, color, expected780+):781+ """When paging falls back to a real TextIO stream, ``.buffer`` is wrapped."""782+ pager_out = tmp_path / "pager_out.txt"783+784+ with pager_out.open("w", encoding="utf-8") as text_stream:785+ monkeypatch.setattr(786+ click._termui_impl, "_default_text_stdout", lambda: text_stream787+ )788+ monkeypatch.setattr(789+ click._termui_impl, "isatty", lambda stream: stream is not sys.stdin790+ )791+792+ with click.get_pager_file(color=color) as pager:793+ pager.write(click.style("hello", fg="red") + "\n")794+795+ assert pager_out.read_text(encoding="utf-8") == expected796+797+798+def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):799+ """The no-stdout fallback should keep a text-only stream and set ``.color``."""800+801+ created = []802+803+ def make_stringio():804+ stream = io.StringIO()805+ created.append(stream)806+ return stream807+808+ monkeypatch.setattr(sys, "stdout", None)809+ monkeypatch.setattr(click._termui_impl, "StringIO", make_stringio)810+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)811+812+ styled_text = click.style("hello", fg="red")813+814+ with click.get_pager_file(color=False) as pager:815+ assert pager is created[0]816+ pager.write(styled_text)817+818+ assert created[0].getvalue() == styled_text819+820+821+def test_get_pager_file_flushes_stream_on_exception(monkeypatch):822+ """Exceptions should still flush the yielded stream in ``finally``."""823+824+ class FlushableTextStream(io.StringIO):825+ def __init__(self):826+ super().__init__()827+ self.color = None828+ self.flush_calls = 0829+830+ def flush(self):831+ self.flush_calls += 1832+833+ stream = FlushableTextStream()834+835+ @contextlib.contextmanager836+ def pager_contextmanager(color=None):837+ yield stream, "utf-8", color838+839+ monkeypatch.setattr(840+ click._termui_impl, "_pager_contextmanager", pager_contextmanager841+ )842+843+ with pytest.raises(RuntimeError, match="boom"):844+ with click.get_pager_file() as pager:845+ assert pager is stream846+ raise RuntimeError("boom")847+848+ assert stream.flush_calls == 1849+850+851 def test_editor_unclosed_quote():852 """An unclosed quote in the editor command raises ValueError."""853 with pytest.raises(ValueError, match="No closing quotation"):854 Editor(editor='"unclosed').edit_files(["f.txt"])620 unmodified linesmodified:CHANGES.rst+1 added-1 removed
53 unmodified lines54 commands. :issue:`3107` :pr:`3228`55 - Use :class:`ValueError` message when conversion in :class:`FuncParamType` would56 fail. :issue:`3105` :pr:`3211`57 - Add ``click.get_pager_file`` for file-like access to an output58- pager. :pr:`1572`58+ pager. :pr:`1572` :pr:`3405`59 - :class:`~click.formatting.TextWrapper` and60 :func:`~click.formatting.wrap_text` now measure line width in visible61 characters, ignoring ANSI escape sequences. :pr:`3420`62 - Show custom error messages from types when :func:`prompt` with1400 unmodified lines