Skip to content
Myr

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

2 files+117 added−112 removed

modified:src/click/_termui_impl.py+23 added-11 removed
30 unmodified lines
31from .utils import echo3233V = t.TypeVar("V")343536class _BufferedTextPagerStream(t.Protocol):37 buffer: t.BinaryIO383940def _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 None464748if os.name == "nt":49 BEFORE_BAR = "\r"50 AFTER_BAR = "\n"51else:
383 unmodified lines
435 :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()452453
456 unmodified lines
modified:tests/test_termui.py+94 added-101 removed
1 unmodified line
2import io3import platform4import shlex5import shutil6import subprocess6import sys7import tempfile8import time9from functools import partial9from unittest.mock import patch1011import pytest12
611 unmodified lines
624 """625 assert shlex.split(pager_env) == expected_parts626627629def 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")628def _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_path634634 @contextlib.contextmanager635 def pager_contextmanager(color=None):636 yield wrapped, "utf-8", color635636def _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 )642642 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)645646 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 out650651649def 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 """652def _write_pager_from_multiple_sites(pager):653 pager.write("prefix\n")654 click.echo("middle", file=pager)655 pager.write("suffix\n")656655 class TextStreamWithoutBuffer:656 encoding = "utf-8"657658 def __init__(self):659 self.value = ""660 self.color = None661662 def write(self, text):663 self.value += text664 return len(text)665666 def flush(self):667 pass668669 stream = TextStreamWithoutBuffer()670 styled_text = click.style("hello", fg="red")671672 @contextlib.contextmanager673 def pager_contextmanager(color=None):674 yield stream, "utf-8", color675676 monkeypatch.setattr(677 click._termui_impl, "_pager_contextmanager", pager_contextmanager678 )679680 with click.get_pager_file(color=False) as pager:681 assert pager is stream682 assert pager.color is False683 pager.write(styled_text)684685 assert stream.value == styled_text686687688def _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"691692 pager_out = tmp_path / "pager_out.txt"693694 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)695 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", pager_path)696697 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)706707 return pager_out.read_text()708709710@pytest.mark.skipif(WIN, reason="Exercises the pipe pager path.")711def test_get_pager_file_supports_multiple_write_sites(monkeypatch, tmp_path):712 """Different helpers can write to the same pager stream."""713714 def writer(pager):715 pager.write("prefix\n")716 click.echo("middle", file=pager)717 pager.write("suffix\n")718719 output = _run_get_pager_file_with_real_pager(monkeypatch, tmp_path, writer)720721 assert output == "prefix\nmiddle\nsuffix\n"722723724@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)741def test_get_pager_file_with_real_pager_data_cases(742 monkeypatch, tmp_path, text, color, expected685def 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 )692693 assert output == expected694695696@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)703def 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"708709 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 )716717 with click.get_pager_file(color=color) as pager:718 pager.write(click.style("hello", fg="red") + "\n")719720 assert pager_out.read_text(encoding="utf-8") == expected721722723def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):724 """The no-stdout fallback should keep a text-only stream and set ``.color``."""725726 created = []727728 def make_stringio():729 stream = io.StringIO()730 created.append(stream)731 return stream732733 monkeypatch.setattr(sys, "stdout", None)734 monkeypatch.setattr(click._termui_impl, "StringIO", make_stringio)735 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)736737 styled_text = click.style("hello", fg="red")738739 with click.get_pager_file(color=False) as pager:740 assert pager is created[0]741 pager.write(styled_text)742743 assert created[0].getvalue() == styled_text744745746def test_get_pager_file_flushes_stream_on_exception(monkeypatch):747 """Exceptions should still flush the yielded stream in ``finally``."""748755 class FlushableTextStream:756 encoding = "utf-8"757749 class FlushableTextStream(io.StringIO):750 def __init__(self):751 super().__init__()752 self.color = None753 self.flush_calls = 0754755 def flush(self):
644 unmodified lines