Skip to content
Myr

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

1 file+160 added−0 removed

modified:tests/test_termui.py+160 added
1import contextlib2import io3import platform4import shlex5import shutil6import subprocess7import tempfile8import time9from functools import partial10from unittest.mock import patch1112import pytest1314import click15import click._termui_impl16from click._compat import WIN17from click._termui_impl import Editor18from click._utils import UNSET
606 unmodified lines
625 """626 assert shlex.split(pager_env) == expected_parts627628629def 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")633634 @contextlib.contextmanager635 def pager_contextmanager(color=None):636 yield wrapped, "utf-8", color637638 monkeypatch.setattr(639 click._termui_impl, "_pager_contextmanager", pager_contextmanager640 )641642 with click.get_pager_file(color=True) as pager:643 assert pager is wrapped644 pager.write("hello")645646 assert buffer.getvalue() == b"hello"647648649def 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 """654655 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.")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)741def 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 )748749 assert output == expected750751752def test_get_pager_file_flushes_stream_on_exception(monkeypatch):753 """Exceptions should still flush the yielded stream in ``finally``."""754755 class FlushableTextStream:756 encoding = "utf-8"757758 def __init__(self):759 self.color = None760 self.flush_calls = 0761762 def flush(self):763 self.flush_calls += 1764765 stream = FlushableTextStream()766767 @contextlib.contextmanager768 def pager_contextmanager(color=None):769 yield stream, "utf-8", color770771 monkeypatch.setattr(772 click._termui_impl, "_pager_contextmanager", pager_contextmanager773 )774775 with pytest.raises(RuntimeError, match="boom"):776 with click.get_pager_file() as pager:777 assert pager is stream778 raise RuntimeError("boom")779780 assert stream.flush_calls == 1781782783def 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