Skip to content
Myr

Fix pager test flackiness and add stress tests for `echo_via_pager` (#3499)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 567d7e9, 7eb57cf · Browse files · 4 files+78 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+78 added−9 removed

  • tests:+77 added−6 removed
  • other:+1 added−3 removed

4 files+78 added−9 removed

modified:src/click/_compat.py-1 removed
10 unmodified lines
11from weakref import WeakKeyDictionary1213CYGWIN = sys.platform.startswith("cygwin")14WIN = sys.platform.startswith("win")15MAC = sys.platform == "darwin"15auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None16_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")1718
608 unmodified lines
modified:tests/test_stream_lifecycle.py+3 added-1 removed
482 unmodified lines
483# ---------------------------------------------------------------------------484# Category 6: Stress tests - high-iteration reproducers for race conditions485#486# These are marked with ``pytest.mark.stress`` so they can be included or487# excluded independently. The CI workflow runs them in a separate job.487# excluded independently. The ``tox -e stress`` env collects every488# ``pytest.mark.stress`` test across the suite (not just this file), so489# stress regressions for other components live alongside their unit tests.490# ---------------------------------------------------------------------------491492493@pytest.mark.stress
47 unmodified lines
modified:tests/test_utils.py+74 added-5 removed
14 unmodified lines
15import pytest1617import click._termui_impl18import click.utils19from click._compat import MAC19from click._compat import WIN20from click._utils import UNSET2122
261 unmodified lines
284 yield "abc"285286287def _test_gen_func_fails():288 raise RuntimeError("This is a test.")289 yield # unreachable, keeps this a generator function290291292def _test_gen_func_yields_then_fails():293 yield "test"294 raise RuntimeError("This is a test.")295296
21 unmodified lines
318)319320321@pytest.mark.skipif(WIN, reason="Different behavior on windows.")318@pytest.mark.skipif(319 MAC and sys.version_info >= (3, 13) and not sys._is_gil_enabled(),320 reason="Generator exception tests are flaky in Python 3.14t on macOS.",321)322@pytest.mark.parametrize(323 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]324)325@pytest.mark.parametrize(
129 unmodified lines
455 f"Unexpected stderr in test case '{test.description}'"456 )457458459@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):461 """A generator that yields then raises: click writes the partial output to462 the pager stream before propagating the exception.463464 The pager file content is intentionally NOT asserted: pipe-drain timing465 between click and the pager subprocess is outside click's control466 (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent467 to the pager, which is deterministic regardless of scheduling.468 """469 monkeypatch.setitem(os.environ, "PAGER", "cat")470 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)471472 writes: list[str] = []473 real_write = click._termui_impl.MaybeStripAnsi.write474475 def spy(self, text):476 writes.append(text)477 return real_write(self, text)478479 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480481 pager_out_tmp = tmp_path / "pager_out.txt"482 with (483 pager_out_tmp.open("w") as f,484 patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),485 pytest.raises(RuntimeError, match="This is a test."),486 ):487 click.echo_via_pager(_test_gen_func_yields_then_fails())488489 assert "".join(writes) == "test", (490 f"click should have written the yielded chunk before exception, got {writes!r}"491 )492493494@pytest.mark.stress495@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496@pytest.mark.parametrize("_", range(1000))497def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498 """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499500 Regression coverage for the cleanup path in ``_pipepager``'s exception501 handler (issue #2899, PR #3470). Each iteration spawns a real pager502 subprocess, raises before any data is written and check there is no leak.503 """504 monkeypatch.setitem(os.environ, "PAGER", "cat")505 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)506507 spawned: list[subprocess.Popen] = []508 real_popen = subprocess.Popen509510 def tracking_popen(*args, **kwargs):511 p = real_popen(*args, **kwargs)512 spawned.append(p)513 return p514515 pager_out_tmp = tmp_path / "pager_out.txt"516 with (517 pager_out_tmp.open("w") as f,518 patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),519 pytest.raises(RuntimeError),520 ):521 click.echo_via_pager(_test_gen_func_fails())522523 assert spawned, "pager subprocess was never started"524 for p in spawned:525 assert p.returncode is not None, "pager subprocess not reaped"526527528def test_echo_color_flag(monkeypatch, capfd):529 isatty = True530 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531
330 unmodified lines
modified:pyproject.toml+1 added-2 removed
183 unmodified lines
184 {replace = "posargs", default = [], extend = true},185]]186187[tool.tox.env.stress]188description = "stress tests for stream lifecycle race conditions"188description = "high-iteration stress tests for race conditions"189commands = [[190 "pytest", "-v", "--tb=short", "-x", "-m", "stress",191 "--basetemp={env_tmp_dir}",192 "--override-ini=addopts=",193 "tests/test_stream_lifecycle.py",193 {replace = "posargs", default = [], extend = true},194]]195196[tool.tox.env.style]
44 unmodified lines