Skip to content
Myr

test_echo_via_pager.py

This file

Path

tests/test_utils/test_echo_via_pager.py

259 lines · 8.6 KiB · Python

Last changed by

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

History of this file

Take it

1import os2import subprocess3import sys4from collections import namedtuple5from contextlib import nullcontext6from functools import partial7from unittest.mock import patch89import pytest1011import click12from click._compat import WIN1314EchoViaPagerTest = namedtuple(15    "EchoViaPagerTest",16    (17        "description",18        "test_input",19        "expected_pager",20        "expected_stdout",21        "expected_stderr",22        "expected_error",23    ),24)252627def _test_gen_func():28    yield "a"29    yield "b"30    yield "c"31    yield "abc"323334def _test_gen_func_fails():35    raise RuntimeError("This is a test.")36    yield  # unreachable, keeps this a generator function373839def _test_gen_func_yields_then_fails():40    yield "test"41    raise RuntimeError("This is a test.")424344def _test_gen_func_echo(file=None):45    yield "test"46    click.echo("hello", file=file)47    yield "test"484950def _test_simulate_keyboard_interrupt(file=None):51    yield "output_before_keyboard_interrupt"52    raise KeyboardInterrupt()535455@pytest.mark.skipif(WIN, reason="Different behavior on windows.")56@pytest.mark.parametrize(57    "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]58)59@pytest.mark.parametrize(60    "test",61    [62        # We need to pass a parameter function instead of a plain param63        # as pytest.mark.parametrize will reuse the parameters causing the64        # generators to be used up so they will not yield anymore65        EchoViaPagerTest(66            description="Plain string argument",67            test_input=lambda: "just text",68            expected_pager="just text\n",69            expected_stdout="",70            expected_stderr="",71            expected_error=None,72        ),73        EchoViaPagerTest(74            description="Iterable argument",75            test_input=lambda: ["itera", "ble"],76            expected_pager="iterable\n",77            expected_stdout="",78            expected_stderr="",79            expected_error=None,80        ),81        EchoViaPagerTest(82            description="Generator function argument",83            test_input=lambda: _test_gen_func,84            expected_pager="abcabc\n",85            expected_stdout="",86            expected_stderr="",87            expected_error=None,88        ),89        EchoViaPagerTest(90            description="String generator argument",91            test_input=lambda: _test_gen_func(),92            expected_pager="abcabc\n",93            expected_stdout="",94            expected_stderr="",95            expected_error=None,96        ),97        EchoViaPagerTest(98            description="Number generator expression argument",99            test_input=lambda: (c for c in range(6)),100            expected_pager="012345\n",101            expected_stdout="",102            expected_stderr="",103            expected_error=None,104        ),105        EchoViaPagerTest(106            description="Exception in generator function argument",107            test_input=lambda: _test_gen_func_fails,108            # Because generator throws early on, the pager did not have109            # a chance yet to write the file.110            expected_pager="",111            expected_stdout="",112            expected_stderr="",113            expected_error=RuntimeError,114        ),115        EchoViaPagerTest(116            description="Exception in generator argument",117            test_input=lambda: _test_gen_func_fails,118            # Because generator throws early on, the pager did not have a119            # chance yet to write the file.120            expected_pager="",121            expected_stdout="",122            expected_stderr="",123            expected_error=RuntimeError,124        ),125        EchoViaPagerTest(126            description="Keyboard interrupt should not terminate the pager",127            test_input=lambda: _test_simulate_keyboard_interrupt(),128            # Due to the keyboard interrupt during pager execution, click program129            # should abort, but the pager should stay open.130            # This allows users to cancel the program and search in the pager131            # output, before they decide to terminate the pager.132            expected_pager="output_before_keyboard_interrupt",133            expected_stdout="",134            expected_stderr="",135            expected_error=KeyboardInterrupt,136        ),137        EchoViaPagerTest(138            description="Writing to stdout during generator execution",139            test_input=lambda: _test_gen_func_echo(),140            expected_pager="testtest\n",141            expected_stdout="hello\n",142            expected_stderr="",143            expected_error=None,144        ),145        EchoViaPagerTest(146            description="Writing to stderr during generator execution",147            test_input=lambda: _test_gen_func_echo(file=sys.stderr),148            expected_pager="testtest\n",149            expected_stdout="",150            expected_stderr="hello\n",151            expected_error=None,152        ),153    ],154)155def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):156    monkeypatch.setitem(os.environ, "PAGER", pager_cmd)157    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)158159    test_input = test.test_input()160    expected_pager = test.expected_pager161    expected_stdout = test.expected_stdout162    expected_stderr = test.expected_stderr163    expected_error = test.expected_error164165    check_raise = pytest.raises(expected_error) if expected_error else nullcontext()166167    pager_out_tmp = tmp_path / "pager_out.txt"168    with pager_out_tmp.open("w") as f:169        force_subprocess_stdout = patch.object(170            subprocess,171            "Popen",172            partial(subprocess.Popen, stdout=f),173        )174        with force_subprocess_stdout:175            with check_raise:176                click.echo_via_pager(test_input)177178    out, err = capfd.readouterr()179180    pager = pager_out_tmp.read_text()181182    assert pager == expected_pager, (183        f"Unexpected pager output in test case '{test.description}'"184    )185    assert out == expected_stdout, (186        f"Unexpected stdout in test case '{test.description}'"187    )188    assert err == expected_stderr, (189        f"Unexpected stderr in test case '{test.description}'"190    )191192193@pytest.mark.skipif(WIN, reason="Different behavior on windows.")194def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):195    """A generator that yields then raises: click writes the partial output to196    the pager stream before propagating the exception.197198    The pager file content is intentionally NOT asserted: pipe-drain timing199    between click and the pager subprocess is outside click's control200    (#2899, #3470). Spying on ``_PagerWriter.write`` records what click sent201    to the pager, which is deterministic regardless of scheduling.202    """203    monkeypatch.setitem(os.environ, "PAGER", "cat")204    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)205206    writes: list[str] = []207    real_write = click._termui_impl._PagerWriter.write208209    def spy(self, text):210        writes.append(text)211        return real_write(self, text)212213    monkeypatch.setattr(click._termui_impl._PagerWriter, "write", spy)214215    pager_out_tmp = tmp_path / "pager_out.txt"216    with (217        pager_out_tmp.open("w") as f,218        patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),219        pytest.raises(RuntimeError, match="This is a test."),220    ):221        click.echo_via_pager(_test_gen_func_yields_then_fails())222223    assert "".join(writes) == "test", (224        f"click should have written the yielded chunk before exception, got {writes!r}"225    )226227228@pytest.mark.stress229@pytest.mark.skipif(WIN, reason="Different behavior on windows.")230@pytest.mark.parametrize("_", range(1000))231def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):232    """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.233234    Regression coverage for the cleanup path in ``_pipepager``'s exception235    handler (issue #2899, PR #3470). Each iteration spawns a real pager236    subprocess, raises before any data is written and check there is no leak.237    """238    monkeypatch.setitem(os.environ, "PAGER", "cat")239    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)240241    spawned: list[subprocess.Popen] = []242    real_popen = subprocess.Popen243244    def tracking_popen(*args, **kwargs):245        p = real_popen(*args, **kwargs)246        spawned.append(p)247        return p248249    pager_out_tmp = tmp_path / "pager_out.txt"250    with (251        pager_out_tmp.open("w") as f,252        patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),253        pytest.raises(RuntimeError),254    ):255        click.echo_via_pager(_test_gen_func_fails())256257    assert spawned, "pager subprocess was never started"258    for p in spawned:259        assert p.returncode is not None, "pager subprocess not reaped"