`NamedTextIOWrapper`: stop closing buffer (#3139)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents b6afbf0, 777a89e · Browse files · 5 files·+587 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+587 added−12 removed
- tests:+538 added−0 removed
- other:+49 added−12 removed
Provenance
- Commit
ae46cfd- Tree
8780a65- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
b6afbf0- Parent 2
777a89e
5 files changed+587 added−12 removed
modified:.github/workflows/tests.yaml+19 added
30 unmodified lines31323334353637383940414243444546474849505152535455565713 unmodified lines30 unmodified lines - uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0 with: python-version: ${{ matrix.python }} - run: uv run --locked tox run -e ${{ matrix.tox || format('py{0}', matrix.python) }} stress: name: stress (${{ matrix.name || matrix.python }}) runs-on: ${{ matrix.os || 'ubuntu-latest' }} strategy: fail-fast: false matrix: include: - {python: '3.14'} - {name: free-threaded, python: '3.14t', tox: stress-py3.14t} steps: - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 - uses: astral-sh/setup-uv@5a7eac68fb9809dea845d802897dc5c723910fa3 # v7.1.3 with: enable-cache: true prune-cache: false - uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0 with: python-version: ${{ matrix.python }} - run: uv run --locked tox run -e ${{ matrix.tox || format('stress-py{0}', matrix.python) }} typing: runs-on: ubuntu-latest steps: - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.113 unmodified linesmodified:src/click/testing.py+9 added-12 removed
96 unmodified lines97 self.output: io.BytesIO = io.BytesIO()98 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)99 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)100 101- def __del__(self) -> None:102- """103- Guarantee that embedded file-like objects are closed in a104- predictable order, protecting against races between105- self.output being closed and other streams being flushed on close101 107- .. versionadded:: 8.2.2108- """109- self.stderr.close()110- self.stdout.close()111- self.output.close()112-113-102 class _NamedTextIOWrapper(io.TextIOWrapper):103 def __init__(104 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any105 ) -> None:106 super().__init__(buffer, **kwargs)107 self._name = name108 self._mode = mode109 110+ def close(self) -> None:111+ """112+ The buffer this object contains belongs to some other object, so113+ prevent the default __del__ implementation from closing that buffer.114+115+ .. versionadded:: 8.3.2116+ """117+ ...118+119 @property120 def name(self) -> str:121 return self._name122 452 unmodified linesadded:tests/test_stream_lifecycle.py+538 added
1+"""Tests for ``CliRunner`` stream lifecycle and ownership.2+3+Covers the stream management bugs tracked across:4+- Issue #824: ``ValueError`` on closed file when logging interacts with ``CliRunner``5+- Issue #2993: Race condition in ``StreamMixer`` finalization (multi-threaded)6+- Issue #3110: Regression from PR #2991's ``__del__`` fix breaking logging7+- PR #3139: The fix - prevent ``_NamedTextIOWrapper`` from closing owned buffers8+9+The tests are organized by category:10+11+1. Stream ownership: ``_NamedTextIOWrapper`` must not close buffers it wraps12+2. ``StreamMixer`` lifecycle: buffers survive wrapper garbage collection13+3. Logging interaction: ``CliRunner`` works with active logging handlers14+4. Multi-threaded safety: concurrent threads don't cause I/O-on-closed-file15+5. Sequential invocations: multiple ``invoke()`` calls don't corrupt state16+6. Stress tests (marked ``stress``): high-iteration reproducers for races17+18+How to run locally19+------------------20+21+Standard tests (fast, ~0.8s) with stress tests excluded by default:22+23+.. code-block:: shell-session24+25+ $ pytest tests/test_stream_lifecycle.py -v26+27+Stress tests only (30k iterations, ~52min):28+29+.. code-block:: shell-session30+31+ $ pytest tests/test_stream_lifecycle.py -m stress -x --override-ini="addopts="32+33+Everything:34+35+.. code-block:: shell-session36+37+ $ pytest tests/test_stream_lifecycle.py --override-ini="addopts=" -x38+"""39+40+from __future__ import annotations41+42+import gc43+import io44+import logging45+import sys46+import threading47+from concurrent.futures import ThreadPoolExecutor48+49+import pytest50+51+import click52+from click.testing import _NamedTextIOWrapper53+from click.testing import BytesIOCopy54+from click.testing import CliRunner55+from click.testing import StreamMixer56+57+# ---------------------------------------------------------------------------58+# Category 1: Stream ownership - ``_NamedTextIOWrapper`` must not close buffers59+# ---------------------------------------------------------------------------60+61+62+def test_wrapper_close_does_not_close_underlying_buffer():63+ """Calling ``close()`` on the wrapper must leave the buffer open."""64+ buf = io.BytesIO()65+ wrapper = _NamedTextIOWrapper(buf, encoding="utf-8", name="t", mode="w")66+ wrapper.write("hello")67+ wrapper.flush()68+ wrapper.close()69+ assert not buf.closed70+ assert buf.getvalue() == b"hello"71+72+73+def test_wrapper_del_does_not_close_underlying_buffer():74+ """Garbage-collecting the wrapper must leave the buffer open."""75+ buf = io.BytesIO()76+ wrapper = _NamedTextIOWrapper(buf, encoding="utf-8", name="t", mode="w")77+ wrapper.write("world")78+ wrapper.flush()79+ del wrapper80+ gc.collect()81+ assert not buf.closed82+ assert buf.getvalue() == b"world"83+84+85+def test_multiple_wrappers_same_buffer():86+ """Multiple wrappers on the same buffer can be closed independently."""87+ buf = io.BytesIO()88+ w1 = _NamedTextIOWrapper(buf, encoding="utf-8", name="a", mode="w")89+ w2 = _NamedTextIOWrapper(buf, encoding="utf-8", name="b", mode="w")90+ w1.write("one")91+ w1.flush()92+ w1.close()93+ # buf survives, second wrapper can still write94+ w2.write("two")95+ w2.flush()96+ w2.close()97+ assert not buf.closed98+ assert buf.getvalue() == b"onetwo"99+100+101+def test_wrapper_preserves_name_and_mode():102+ buf = io.BytesIO()103+ wrapper = _NamedTextIOWrapper(buf, encoding="utf-8", name="<stdout>", mode="w")104+ assert wrapper.name == "<stdout>"105+ assert wrapper.mode == "w"106+107+108+# ---------------------------------------------------------------------------109+# Category 2: ``StreamMixer`` lifecycle110+# ---------------------------------------------------------------------------111+112+113+def test_mixer_buffers_survive_wrapper_gc():114+ """After wrappers are garbage-collected, mixer buffers remain open."""115+ mixer = StreamMixer()116+ out_w = _NamedTextIOWrapper(117+ mixer.stdout, encoding="utf-8", name="<stdout>", mode="w"118+ )119+ err_w = _NamedTextIOWrapper(120+ mixer.stderr, encoding="utf-8", name="<stderr>", mode="w"121+ )122+ out_w.write("out")123+ out_w.flush()124+ err_w.write("err")125+ err_w.flush()126+127+ del out_w, err_w128+ gc.collect()129+130+ assert not mixer.stdout.closed131+ assert not mixer.stderr.closed132+ assert not mixer.output.closed133+ assert mixer.stdout.getvalue() == b"out"134+ assert mixer.stderr.getvalue() == b"err"135+ assert mixer.output.getvalue() == b"outerr"136+137+138+def test_getvalue_after_isolation_exit():139+ """After the isolation context exits, stream values are readable."""140+ runner = CliRunner()141+142+ @click.command()143+ def cli():144+ click.echo("stdout-msg")145+ click.echo("stderr-msg", err=True)146+147+ result = runner.invoke(cli)148+ assert result.exit_code == 0149+ assert result.stdout == "stdout-msg\n"150+ assert result.stderr == "stderr-msg\n"151+ assert "stdout-msg" in result.output152+ assert "stderr-msg" in result.output153+154+155+def test_no_streammixer_del():156+ """``StreamMixer`` should not have a ``__del__`` method.157+158+ PR #2991 added ``__del__`` which caused issue #3110. PR #3139 removes it.159+ """160+ has_del = hasattr(StreamMixer, "__del__")161+ if has_del:162+ assert StreamMixer.__del__ is object.__del__ # type: ignore[attr-defined]163+164+165+def test_bytesiocopy_writes_to_both():166+ """``BytesIOCopy`` writes to itself and to ``copy_to``."""167+ target = io.BytesIO()168+ copier = BytesIOCopy(copy_to=target)169+ copier.write(b"data")170+ copier.flush()171+ assert copier.getvalue() == b"data"172+ assert target.getvalue() == b"data"173+174+175+def test_bytesiocopy_flush_propagates():176+ """``BytesIOCopy.flush()`` also flushes ``copy_to``."""177+ target = io.BytesIO()178+ copier = BytesIOCopy(copy_to=target)179+ copier.write(b"abc")180+ copier.flush()181+ assert target.getvalue() == b"abc"182+183+184+# ---------------------------------------------------------------------------185+# Category 3: Logging interaction (issues #824, #3110)186+# ---------------------------------------------------------------------------187+188+189+def test_invoke_with_logger_warning():190+ """Basic ``logging.warning()`` inside a command must not crash."""191+ logger = logging.getLogger("test_invoke_with_logger_warning")192+193+ @click.command()194+ def cli():195+ logger.warning("a warning")196+ click.echo("done")197+198+ runner = CliRunner()199+ result = runner.invoke(cli)200+ assert result.exit_code == 0201+ assert "done" in result.output202+203+204+def test_invoke_with_logger_and_prompt():205+ """Logging + prompt (the exact #824 reproducer)."""206+ logger = logging.getLogger("test_invoke_with_logger_and_prompt")207+208+ @click.command()209+ @click.option("--name", prompt="Your name")210+ def hello(name):211+ logger.warning("greeting %s", name)212+ click.echo(f"Hello, {name}!")213+214+ runner = CliRunner()215+ result = runner.invoke(hello, input="Peter")216+ assert result.exit_code == 0217+ assert "Your name:" in result.output218+219+220+def test_sequential_invokes_with_logging():221+ """Multiple sequential ``invoke()`` calls with logging (#3110 reproducer).222+223+ Issue #3110: the ``__del__`` from PR #2991 caused logging failures on224+ the second invocation because the first ``StreamMixer``'s ``__del__`` would225+ close buffers that logging still referenced.226+ """227+ logger = logging.getLogger("test_sequential_invokes_with_logging")228+229+ @click.command()230+ @click.argument("msg")231+ def cli(msg):232+ logger.warning("log: %s", msg)233+ click.echo(msg)234+235+ runner = CliRunner()236+ for i in range(5):237+ result = runner.invoke(cli, [f"msg-{i}"])238+ assert result.exit_code == 0, f"Failed on invocation {i}: {result.exception}"239+ assert f"msg-{i}" in result.output240+241+242+def test_invoke_with_stream_handler_on_stderr():243+ """A ``StreamHandler`` explicitly attached to stderr must survive ``invoke()``."""244+ logger = logging.getLogger("test_stream_handler_stderr")245+ logger.setLevel(logging.DEBUG)246+ handler = logging.StreamHandler(sys.stderr)247+ logger.addHandler(handler)248+ try:249+250+ @click.command()251+ def cli():252+ logger.info("message from inside invoke")253+ click.echo("ok")254+255+ runner = CliRunner()256+ result = runner.invoke(cli)257+ assert result.exit_code == 0258+ assert "ok" in result.output259+ finally:260+ logger.removeHandler(handler)261+262+263+def test_logging_with_cli_log_level():264+ """Simulate what ``--log-cli-level`` does: add a handler to root265+ before invoke.266+267+ This reproduces the original #824 scenario without needing pytest268+ CLI flags.269+ """270+ root_logger = logging.getLogger()271+ handler = logging.StreamHandler(sys.stderr)272+ handler.setLevel(logging.WARNING)273+ root_logger.addHandler(handler)274+ original_level = root_logger.level275+ root_logger.setLevel(logging.WARNING)276+ try:277+278+ @click.command()279+ def cli():280+ logging.warning("live log message")281+ click.echo("output")282+283+ runner = CliRunner()284+ result = runner.invoke(cli)285+ assert result.exit_code == 0286+ assert "output" in result.output287+ finally:288+ root_logger.removeHandler(handler)289+ root_logger.setLevel(original_level)290+291+292+# ---------------------------------------------------------------------------293+# Category 4: Multi-threaded safety (issue #2993)294+# ---------------------------------------------------------------------------295+296+297+def test_invoke_with_thread_pool():298+ """Basic ``ThreadPoolExecutor`` usage inside a command."""299+300+ @click.command()301+ def cli():302+ with ThreadPoolExecutor(max_workers=2) as executor:303+ futures = [executor.submit(lambda x: x * 2, i) for i in range(4)]304+ results = [f.result() for f in futures]305+ click.echo(f"results={results}")306+307+ runner = CliRunner()308+ result = runner.invoke(cli)309+ assert result.exit_code == 0310+ assert "results=" in result.output311+312+313+def test_invoke_with_threads_writing_to_streams():314+ """Threads writing to ``click.echo()`` during invocation."""315+316+ @click.command()317+ def cli():318+ barrier = threading.Barrier(3)319+320+ def worker(n):321+ barrier.wait(timeout=5)322+ click.echo(f"worker-{n}")323+324+ threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]325+ for t in threads:326+ t.start()327+ for t in threads:328+ t.join(timeout=10)329+ click.echo("main-done")330+331+ runner = CliRunner()332+ result = runner.invoke(cli)333+ assert result.exit_code == 0334+ assert "main-done" in result.output335+336+337+def test_invoke_with_thread_pool_and_exit():338+ """``ThreadPoolExecutor`` + ``SystemExit`` (the exact #2993 reproducer)."""339+340+ @click.command()341+ @click.argument("args", nargs=-1)342+ def cli(**_kw):343+ with ThreadPoolExecutor() as executor:344+ executor.submit(lambda: None).result()345+ raise SystemExit(1)346+347+ runner = CliRunner()348+ result = runner.invoke(cli, ["test"])349+ assert result.exit_code == 1350+351+352+def test_sequential_threaded_invokes():353+ """Multiple sequential invocations with threads don't leak state."""354+355+ @click.command()356+ @click.argument("n", type=int)357+ def cli(n):358+ with ThreadPoolExecutor(max_workers=2) as pool:359+ val = pool.submit(lambda x: x + 1, n).result()360+ click.echo(str(val))361+362+ runner = CliRunner()363+ for i in range(10):364+ result = runner.invoke(cli, [str(i)])365+ assert result.exit_code == 0366+ assert result.output.strip() == str(i + 1)367+368+369+# ---------------------------------------------------------------------------370+# Category 5: Sequential invocations and state isolation371+# ---------------------------------------------------------------------------372+373+374+def test_output_isolation_across_invokes():375+ """Each ``invoke()`` must capture only its own output."""376+377+ @click.command()378+ @click.argument("msg")379+ def cli(msg):380+ click.echo(msg)381+382+ runner = CliRunner()383+ for word in ("alpha", "beta", "gamma"):384+ result = runner.invoke(cli, [word])385+ assert result.exit_code == 0386+ assert result.output.strip() == word387+388+389+def test_stderr_isolation_across_invokes():390+ """Each ``invoke()`` must capture only its own stderr."""391+392+ @click.command()393+ @click.argument("msg")394+ def cli(msg):395+ click.echo(msg, err=True)396+397+ runner = CliRunner()398+ for word in ("err1", "err2", "err3"):399+ result = runner.invoke(cli, [word])400+ assert result.exit_code == 0401+ assert result.stderr.strip() == word402+ assert result.stdout.strip() == ""403+404+405+def test_mixed_output_order_preserved():406+ """stdout/stderr interleaving is captured in order."""407+408+ @click.command()409+ def cli():410+ click.echo("out1")411+ click.echo("err1", err=True)412+ click.echo("out2")413+ click.echo("err2", err=True)414+415+ runner = CliRunner()416+ result = runner.invoke(cli)417+ assert result.output == "out1\nerr1\nout2\nerr2\n"418+ assert result.stdout == "out1\nout2\n"419+ assert result.stderr == "err1\nerr2\n"420+421+422+def test_exception_does_not_corrupt_next_invoke():423+ """A failed invoke must not break subsequent invocations."""424+ call_count = 0425+426+ @click.command()427+ def cli():428+ nonlocal call_count429+ call_count += 1430+ if call_count == 2:431+ raise RuntimeError("intentional")432+ click.echo(f"call-{call_count}")433+434+ runner = CliRunner()435+436+ r1 = runner.invoke(cli)437+ assert r1.exit_code == 0438+ assert "call-1" in r1.output439+440+ r2 = runner.invoke(cli)441+ assert r2.exit_code == 1442+ assert isinstance(r2.exception, RuntimeError)443+444+ r3 = runner.invoke(cli)445+ assert r3.exit_code == 0446+ assert "call-3" in r3.output447+448+449+def test_sys_streams_restored_after_invoke():450+ """``sys.stdout``/``stderr``/``stdin`` are restored after ``invoke()``."""451+ original_stdout = sys.stdout452+ original_stderr = sys.stderr453+ original_stdin = sys.stdin454+455+ @click.command()456+ def cli():457+ click.echo("inside")458+459+ runner = CliRunner()460+ runner.invoke(cli)461+462+ assert sys.stdout is original_stdout463+ assert sys.stderr is original_stderr464+ assert sys.stdin is original_stdin465+466+467+def test_sys_streams_restored_after_exception():468+ """sys streams are restored even when the command raises."""469+ original_stdout = sys.stdout470+ original_stderr = sys.stderr471+472+ @click.command()473+ def cli():474+ raise RuntimeError("boom")475+476+ runner = CliRunner()477+ runner.invoke(cli)478+479+ assert sys.stdout is original_stdout480+ assert sys.stderr is original_stderr481+482+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.488+# ---------------------------------------------------------------------------489+490+491+@pytest.mark.stress492+@pytest.mark.parametrize("_", range(10_000))493+def test_stress_thread_pool_with_exit(_):494+ """Exact #2993 reproducer: ``ThreadPoolExecutor`` + ``SystemExit``."""495+496+ @click.command()497+ @click.argument("args", nargs=-1)498+ def cli(**_kw):499+ with ThreadPoolExecutor() as executor:500+ executor.submit(lambda: None).result()501+ raise SystemExit(1)502+503+ runner = CliRunner()504+ result = runner.invoke(cli, ["test"])505+ assert result.exit_code == 1506+507+508+@pytest.mark.stress509+@pytest.mark.parametrize("_", range(10_000))510+def test_stress_logging_sequential_invocations(_):511+ """#3110/#824 reproducer: sequential invocations with logging."""512+ logger = logging.getLogger("stress_sequential")513+514+ @click.command()515+ def cli():516+ logger.warning("msg")517+ click.echo("ok")518+519+ runner = CliRunner()520+ result = runner.invoke(cli)521+ assert result.exit_code == 0522+523+524+@pytest.mark.stress525+@pytest.mark.parametrize("_", range(10_000))526+def test_stress_gc_between_invocations(_):527+ """Force GC after each invocation to provoke finalizer races."""528+529+ @click.command()530+ def cli():531+ click.echo("output")532+ click.echo("error", err=True)533+534+ runner = CliRunner()535+ result = runner.invoke(cli)536+ assert result.exit_code == 0537+ assert "output" in result.output538+ gc.collect()modified:CHANGES.rst+6 added
4 unmodified lines5 - Fix handling of ``flag_value`` when ``is_flag=False`` to allow such options to be6 used without an explicit value. :issue:`3084`7 - Hide ``Sentinel.UNSET`` values as ``None`` when using ``lookup_default()``.8 :issue:`3136` :pr:`3199` :pr:`3202` :pr:`3209` :pr:`3212` :pr:`3224`9+- Prevent ``_NamedTextIOWrapper`` from closing streams owned by ``StreamMixer``.10+ :issue:`824` :issue:`2991` :issue:`2993` :issue:`3110` :pr:`3139` :pr:`3140`11+- Add comprehensive tests for ``CliRunner`` stream lifecycle, covering12+ logging interaction, multi-threaded safety, and sequential invocation13+ isolation. Add high-iteration stress tests behind a ``stress`` marker14+ with a dedicated CI job. :pr:`3139`15 16 Version 8.3.117 --------------18 1305 unmodified linesmodified:pyproject.toml+15 added
81 unmodified lines82 testpaths = ["tests"]83 filterwarnings = [84 "error",85 ]86+markers = [87+ "stress: high-iteration stress tests for race conditions (deselect with '-m \"not stress\"')",88+]89+addopts = "-m 'not stress'"90 91 [tool.coverage.run]92 branch = true93 source = ["click", "tests"]51 unmodified lines145 env_list = [146 "py3.14", "py3.13", "py3.12", "py3.11", "py3.10",147 "py3.14t",148 "pypy3.11",149+ "stress-py3.14", "stress-py3.14t",150 "style",151 "typing",152 "docs",153 ]10 unmodified lines164 "pytest", "-v", "--tb=short", "--basetemp={env_tmp_dir}",165 {replace = "posargs", default = [], extend = true},166 ]]167 168+[tool.tox.env.stress]169+description = "stress tests for stream lifecycle race conditions"170+commands = [[171+ "pytest", "-v", "--tb=short", "-x", "-m", "stress",172+ "--basetemp={env_tmp_dir}",173+ "--override-ini=addopts=",174+ "tests/test_stream_lifecycle.py",175+ {replace = "posargs", default = [], extend = true},176+]]177+178 [tool.tox.env.style]179 description = "run all pre-commit hooks on all files"180 dependency_groups = ["pre-commit"]181 skip_install = true41 unmodified lines