Fix pager test race by raising before yield
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 1050d95 · 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.
Trailers
- Refs: #3470 #2899
Diff stats
4 files+78 added−9 removed
- tests:+77 added−6 removed
- other:+1 added−3 removed
Provenance
- Commit
7eb57cf- Tree
40db80a- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
1050d95
4 files changed+78 added−9 removed
modified:src/click/_compat.py-1 removed
10 unmodified lines11 from weakref import WeakKeyDictionary12 13 CYGWIN = sys.platform.startswith("cygwin")14 WIN = sys.platform.startswith("win")15-MAC = sys.platform == "darwin"15 auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None16 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")17 18 608 unmodified linesmodified:tests/test_stream_lifecycle.py+3 added-1 removed
482 unmodified lines483 # ---------------------------------------------------------------------------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 # ---------------------------------------------------------------------------491 492 493 @pytest.mark.stress47 unmodified linesmodified:tests/test_utils.py+74 added-5 removed
14 unmodified lines15 import pytest16 17 import click._termui_impl18 import click.utils19-from click._compat import MAC19 from click._compat import WIN20 from click._utils import UNSET21 22 261 unmodified lines284 yield "abc"285 286 287 def _test_gen_func_fails():288+ raise RuntimeError("This is a test.")289+ yield # unreachable, keeps this a generator function290+291+292+def _test_gen_func_yields_then_fails():293 yield "test"294 raise RuntimeError("This is a test.")295 296 21 unmodified lines318 )319 320 321 @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 lines455 f"Unexpected stderr in test case '{test.description}'"456 )457 458 459+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460+def 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.463+464+ 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)471+472+ writes: list[str] = []473+ real_write = click._termui_impl.MaybeStripAnsi.write474+475+ def spy(self, text):476+ writes.append(text)477+ return real_write(self, text)478+479+ monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480+481+ 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())488+489+ assert "".join(writes) == "test", (490+ f"click should have written the yielded chunk before exception, got {writes!r}"491+ )492+493+494+@pytest.mark.stress495+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496+@pytest.mark.parametrize("_", range(1000))497+def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498+ """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499+500+ 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)506+507+ spawned: list[subprocess.Popen] = []508+ real_popen = subprocess.Popen509+510+ def tracking_popen(*args, **kwargs):511+ p = real_popen(*args, **kwargs)512+ spawned.append(p)513+ return p514+515+ 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())522+523+ assert spawned, "pager subprocess was never started"524+ for p in spawned:525+ assert p.returncode is not None, "pager subprocess not reaped"526+527+528 def test_echo_color_flag(monkeypatch, capfd):529 isatty = True530 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531 330 unmodified linesmodified:pyproject.toml+1 added-2 removed
183 unmodified lines184 {replace = "posargs", default = [], extend = true},185 ]]186 187 [tool.tox.env.stress]188-description = "stress tests for stream lifecycle race conditions"188+description = "high-iteration stress tests for race conditions"189 commands = [[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 ]]195 196 [tool.tox.env.style]44 unmodified lines