Skip to content
Myr

`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

3 files+253 added−13 removed

modified:src/click/_termui_impl.py+24 added-12 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:
378 unmodified lines
430@contextlib.contextmanager431def 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()452453
456 unmodified lines
modified:tests/test_termui.py+228 added
1import contextlib2import io3import platform4import shlex5import shutil6import sys7import tempfile8import time9from unittest.mock import patch1011import pytest1213import click14import click._termui_impl15from click._compat import WIN16from click._termui_impl import Editor17from click._utils import UNSET
606 unmodified lines
624 """625 assert shlex.split(pager_env) == expected_parts626627628def _get_real_pager_command() -> str:629 """Return a real pager binary path used to exercise the pipe pager branch.630631 ..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_path638639640def _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 )646647 with click.get_pager_file(color=color) as pager:648 writer(pager)649650 # The real pager writes to the process stdout; stderr should stay quiet.651 out, err = capfd.readouterr()652 assert err == ""653 return out654655656def _write_pager_from_multiple_sites(pager):657 pager.write("prefix\n")658 click.echo("middle", file=pager)659 pager.write("suffix\n")660661662@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)693def 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 )700701 assert output == expected702703704@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)715def 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 )721722 click.echo_via_pager(click.style("hello", fg="red"), color=color)723724 out, err = capfd.readouterr()725 assert err == ""726 assert out == expected727728729def 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"732733 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)739740 with pager_out.open("w", encoding="utf-8") as text_stream:741 monkeypatch.setattr(742 click._termui_impl, "_default_text_stdout", lambda: text_stream743 )744745 with click.get_pager_file() as pager:746 pager.write("hello\n")747748 assert pager_out.read_text(encoding="utf-8") == "hello\n"749750751def 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"754755 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)759760 with pager_out.open("w", encoding="utf-8") as text_stream:761 monkeypatch.setattr(762 click._termui_impl, "_default_text_stdout", lambda: text_stream763 )764765 with click.get_pager_file() as pager:766 pager.write("hello\n")767768 assert pager_out.read_text(encoding="utf-8") == "hello\n"769770771@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)778def 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"783784 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 )791792 with click.get_pager_file(color=color) as pager:793 pager.write(click.style("hello", fg="red") + "\n")794795 assert pager_out.read_text(encoding="utf-8") == expected796797798def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):799 """The no-stdout fallback should keep a text-only stream and set ``.color``."""800801 created = []802803 def make_stringio():804 stream = io.StringIO()805 created.append(stream)806 return stream807808 monkeypatch.setattr(sys, "stdout", None)809 monkeypatch.setattr(click._termui_impl, "StringIO", make_stringio)810 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)811812 styled_text = click.style("hello", fg="red")813814 with click.get_pager_file(color=False) as pager:815 assert pager is created[0]816 pager.write(styled_text)817818 assert created[0].getvalue() == styled_text819820821def test_get_pager_file_flushes_stream_on_exception(monkeypatch):822 """Exceptions should still flush the yielded stream in ``finally``."""823824 class FlushableTextStream(io.StringIO):825 def __init__(self):826 super().__init__()827 self.color = None828 self.flush_calls = 0829830 def flush(self):831 self.flush_calls += 1832833 stream = FlushableTextStream()834835 @contextlib.contextmanager836 def pager_contextmanager(color=None):837 yield stream, "utf-8", color838839 monkeypatch.setattr(840 click._termui_impl, "_pager_contextmanager", pager_contextmanager841 )842843 with pytest.raises(RuntimeError, match="boom"):844 with click.get_pager_file() as pager:845 assert pager is stream846 raise RuntimeError("boom")847848 assert stream.flush_calls == 1849850851def 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 lines
modified:CHANGES.rst+1 added-1 removed
53 unmodified lines
54 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` with
1400 unmodified lines