Redesigned tests and get_pager_file branching to be more clear and not set color
Before adoption: this commit came in with the history the project adopted, so no landing records it.
unknowingly.
authored by Andreas Backx · committed by Kevin Deldycke · parent e94e8dc · Browse files · 2 files·+117 added−112 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+117 added−112 removed
- tests:+94 added−101 removed
- other:+23 added−11 removed
Provenance
- Commit
1aa2d53- Tree
6a4be46- Author
Andreas Backx <andreas@backx.org>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
e94e8dc
2 files changed+117 added−112 removed
modified:src/click/_termui_impl.py+23 added-11 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:383 unmodified lines435 :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+94 added-101 removed
1 unmodified line2 import io3 import platform4 import shlex5 import shutil6-import subprocess6+import sys7 import tempfile8 import time9-from functools import partial9 from unittest.mock import patch10 11 import pytest12 611 unmodified lines624 """625 assert shlex.split(pager_env) == expected_parts626 627 629-def test_get_pager_file_reuses_existing_maybe_strip_ansi(monkeypatch):630- """An already-wrapped pager stream should be yielded unchanged."""631- buffer = io.BytesIO()632- wrapped = click._termui_impl.MaybeStripAnsi(buffer, color=True, encoding="utf-8")628+def _get_real_pager_command() -> str:629+ """Return a platform pager used to exercise the BinaryIO pager branch."""630+ pager_name = "more" if WIN else "cat"631+ pager_path = shutil.which(pager_name)632+ assert pager_path is not None, f"{pager_name} not available"633+ return pager_path634 634- @contextlib.contextmanager635- def pager_contextmanager(color=None):636- yield wrapped, "utf-8", color635 636+def _run_get_pager_file_with_real_pager(monkeypatch, capfd, writer, color=False):637+ """Run through the platform pager backend selected by ``PAGER``."""638+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)638- monkeypatch.setattr(639- click._termui_impl, "_pager_contextmanager", pager_contextmanager639+ monkeypatch.setitem(640+ click._termui_impl.os.environ, "PAGER", _get_real_pager_command()641 )642 642- with click.get_pager_file(color=True) as pager:643- assert pager is wrapped644- pager.write("hello")643+ with click.get_pager_file(color=color) as pager:644+ writer(pager)645 646- assert buffer.getvalue() == b"hello"646+ # The real pager writes to the process stdout; stderr should stay quiet.647+ out, err = capfd.readouterr()648+ assert err == ""649+ return out650 651 649-def test_get_pager_file_keeps_text_stream_without_buffer(monkeypatch):650- """651- A text stream with no ``.buffer`` should not be re-wrapped and have652- its color field set.653- """652+def _write_pager_from_multiple_sites(pager):653+ pager.write("prefix\n")654+ click.echo("middle", file=pager)655+ pager.write("suffix\n")656 655- class TextStreamWithoutBuffer:656- encoding = "utf-8"657 658- def __init__(self):659- self.value = ""660- self.color = None661-662- def write(self, text):663- self.value += text664- return len(text)665-666- def flush(self):667- pass668-669- stream = TextStreamWithoutBuffer()670- styled_text = click.style("hello", fg="red")671-672- @contextlib.contextmanager673- def pager_contextmanager(color=None):674- yield stream, "utf-8", color675-676- monkeypatch.setattr(677- click._termui_impl, "_pager_contextmanager", pager_contextmanager678- )679-680- with click.get_pager_file(color=False) as pager:681- assert pager is stream682- assert pager.color is False683- pager.write(styled_text)684-685- assert stream.value == styled_text686-687-688-def _run_get_pager_file_with_real_pager(monkeypatch, tmp_path, writer, color=False):689- pager_path = shutil.which("cat")690- assert pager_path is not None, "cat not available"691-692- pager_out = tmp_path / "pager_out.txt"693-694- monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)695- monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", pager_path)696-697- with pager_out.open("w") as f:698- force_subprocess_stdout = patch.object(699- subprocess,700- "Popen",701- partial(subprocess.Popen, stdout=f),702- )703- with force_subprocess_stdout:704- with click.get_pager_file(color=color) as pager:705- writer(pager)706-707- return pager_out.read_text()708-709-710-@pytest.mark.skipif(WIN, reason="Exercises the pipe pager path.")711-def test_get_pager_file_supports_multiple_write_sites(monkeypatch, tmp_path):712- """Different helpers can write to the same pager stream."""713-714- def writer(pager):715- pager.write("prefix\n")716- click.echo("middle", file=pager)717- pager.write("suffix\n")718-719- output = _run_get_pager_file_with_real_pager(monkeypatch, tmp_path, writer)720-721- assert output == "prefix\nmiddle\nsuffix\n"722-723-724-@pytest.mark.skipif(WIN, reason="Exercises the pipe pager path.")658 @pytest.mark.parametrize(726- ("text", "color", "expected"),659+ ("writer", "color", "expected"),660 [728- pytest.param("hello\n", False, "hello\n", id="plain text"),661 pytest.param(730- click.style("hello", fg="red") + "\n", False, "hello\n", id="strip ansi"662+ _write_pager_from_multiple_sites,663+ False,664+ "prefix\nmiddle\nsuffix\n",665+ id="multiple write sites",666 ),667 pytest.param(733- click.style("hello", fg="red") + "\n",668+ lambda pager: pager.write("hello\n"), False, "hello\n", id="plain text"669+ ),670+ pytest.param(671+ lambda pager: pager.write(click.style("hello", fg="red") + "\n"),672+ False,673+ "hello\n",674+ id="strip ansi",675+ ),676+ pytest.param(677+ lambda pager: pager.write(click.style("hello", fg="red") + "\n"),678 True,679 click.style("hello", fg="red") + "\n",680 id="preserve ansi",681 ),738- pytest.param("", False, "", id="empty string"),682+ pytest.param(lambda pager: pager.write(""), False, "", id="empty string"),683 ],684 )741-def test_get_pager_file_with_real_pager_data_cases(742- monkeypatch, tmp_path, text, color, expected685+def test_get_pager_file_with_real_pager_binary_stream(686+ monkeypatch, capfd, writer, color, expected687 ):744- """Real pager output should match text and color expectations."""688+ """A real pager should exercise the BinaryIO branch on Unix and Windows."""689 output = _run_get_pager_file_with_real_pager(746- monkeypatch, tmp_path, lambda pager: pager.write(text), color=color690+ monkeypatch, capfd, writer, color=color691 )692 693 assert output == expected694 695 696+@pytest.mark.parametrize(697+ ("color", "expected"),698+ [699+ pytest.param(False, "hello\n", id="strip ansi"),700+ pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),701+ ],702+)703+def test_get_pager_file_nullpager_wraps_textio_stream(704+ monkeypatch, tmp_path, color, expected705+):706+ """When paging falls back to a real TextIO stream, ``.buffer`` is wrapped."""707+ pager_out = tmp_path / "pager_out.txt"708+709+ with pager_out.open("w", encoding="utf-8") as text_stream:710+ monkeypatch.setattr(711+ click._termui_impl, "_default_text_stdout", lambda: text_stream712+ )713+ monkeypatch.setattr(714+ click._termui_impl, "isatty", lambda stream: stream is not sys.stdin715+ )716+717+ with click.get_pager_file(color=color) as pager:718+ pager.write(click.style("hello", fg="red") + "\n")719+720+ assert pager_out.read_text(encoding="utf-8") == expected721+722+723+def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):724+ """The no-stdout fallback should keep a text-only stream and set ``.color``."""725+726+ created = []727+728+ def make_stringio():729+ stream = io.StringIO()730+ created.append(stream)731+ return stream732+733+ monkeypatch.setattr(sys, "stdout", None)734+ monkeypatch.setattr(click._termui_impl, "StringIO", make_stringio)735+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)736+737+ styled_text = click.style("hello", fg="red")738+739+ with click.get_pager_file(color=False) as pager:740+ assert pager is created[0]741+ pager.write(styled_text)742+743+ assert created[0].getvalue() == styled_text744+745+746 def test_get_pager_file_flushes_stream_on_exception(monkeypatch):747 """Exceptions should still flush the yielded stream in ``finally``."""748 755- class FlushableTextStream:756- encoding = "utf-8"757-749+ class FlushableTextStream(io.StringIO):750 def __init__(self):751+ super().__init__()752 self.color = None753 self.flush_calls = 0754 755 def flush(self):644 unmodified lines