Add some unit tests and integration tests for get_pager_file.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andreas Backx · committed by Kevin Deldycke · parent 7c99ebe · Browse files · 1 file·+160 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+160 added−0 removed
- tests:+160 added−0 removed
Provenance
- Commit
e94e8dc- Tree
0094aba- Author
Andreas Backx <andreas@backx.org>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
7c99ebe
1 file changed+160 added−0 removed
modified:tests/test_termui.py+160 added
1+import contextlib2+import io3 import platform4 import shlex5+import shutil6+import subprocess7 import tempfile8 import time9+from functools import partial10 from unittest.mock import patch11 12 import pytest13 14+import click15 import click._termui_impl16 from click._compat import WIN17 from click._termui_impl import Editor18 from click._utils import UNSET606 unmodified lines625 """626 assert shlex.split(pager_env) == expected_parts627 628 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")633+634+ @contextlib.contextmanager635+ def pager_contextmanager(color=None):636+ yield wrapped, "utf-8", color637+638+ monkeypatch.setattr(639+ click._termui_impl, "_pager_contextmanager", pager_contextmanager640+ )641+642+ with click.get_pager_file(color=True) as pager:643+ assert pager is wrapped644+ pager.write("hello")645+646+ assert buffer.getvalue() == b"hello"647+648+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+ """654+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.")725+@pytest.mark.parametrize(726+ ("text", "color", "expected"),727+ [728+ pytest.param("hello\n", False, "hello\n", id="plain text"),729+ pytest.param(730+ click.style("hello", fg="red") + "\n", False, "hello\n", id="strip ansi"731+ ),732+ pytest.param(733+ click.style("hello", fg="red") + "\n",734+ True,735+ click.style("hello", fg="red") + "\n",736+ id="preserve ansi",737+ ),738+ pytest.param("", False, "", id="empty string"),739+ ],740+)741+def test_get_pager_file_with_real_pager_data_cases(742+ monkeypatch, tmp_path, text, color, expected743+):744+ """Real pager output should match text and color expectations."""745+ output = _run_get_pager_file_with_real_pager(746+ monkeypatch, tmp_path, lambda pager: pager.write(text), color=color747+ )748+749+ assert output == expected750+751+752+def test_get_pager_file_flushes_stream_on_exception(monkeypatch):753+ """Exceptions should still flush the yielded stream in ``finally``."""754+755+ class FlushableTextStream:756+ encoding = "utf-8"757+758+ def __init__(self):759+ self.color = None760+ self.flush_calls = 0761+762+ def flush(self):763+ self.flush_calls += 1764+765+ stream = FlushableTextStream()766+767+ @contextlib.contextmanager768+ def pager_contextmanager(color=None):769+ yield stream, "utf-8", color770+771+ monkeypatch.setattr(772+ click._termui_impl, "_pager_contextmanager", pager_contextmanager773+ )774+775+ with pytest.raises(RuntimeError, match="boom"):776+ with click.get_pager_file() as pager:777+ assert pager is stream778+ raise RuntimeError("boom")779+780+ assert stream.flush_calls == 1781+782+783 def test_editor_unclosed_quote():784 """An unclosed quote in the editor command raises ValueError."""785 with pytest.raises(ValueError, match="No closing quotation"):786 Editor(editor='"unclosed').edit_files(["f.txt"])620 unmodified lines