Skip to content
Myr

Add regular and stress tests for ``CliRunner`` stream lifecycle and ownership

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

Closes: #824, #3110 Reverts: #2991 Reproduces #2993 Supersed: #3140

authored by Kevin Deldycke · committed by Kevin Deldycke · parent d8e987e · Browse files · 5 files+577 added−26 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+577 added−26 removed

  • tests:+538 added−25 removed
  • other:+39 added−1 removed

5 files+577 added−26 removed

modified:.github/workflows/tests.yaml+19 added
added:tests/test_stream_lifecycle.py+538 added
1"""Tests for ``CliRunner`` stream lifecycle and ownership.23Covers 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 buffers89The tests are organized by category:10111. Stream ownership: ``_NamedTextIOWrapper`` must not close buffers it wraps122. ``StreamMixer`` lifecycle: buffers survive wrapper garbage collection133. Logging interaction: ``CliRunner`` works with active logging handlers144. Multi-threaded safety: concurrent threads don't cause I/O-on-closed-file155. Sequential invocations: multiple ``invoke()`` calls don't corrupt state166. Stress tests (marked ``stress``): high-iteration reproducers for races1718How to run locally19------------------2021Standard tests (fast, ~0.8s) with stress tests excluded by default:2223.. code-block:: shell-session2425 $ pytest tests/test_stream_lifecycle.py -v2627Stress tests only (30k iterations, ~52min):2829.. code-block:: shell-session3031 $ pytest tests/test_stream_lifecycle.py -m stress -x --override-ini="addopts="3233Everything:3435.. code-block:: shell-session3637 $ pytest tests/test_stream_lifecycle.py --override-ini="addopts=" -x38"""3940from __future__ import annotations4142import gc43import io44import logging45import sys46import threading47from concurrent.futures import ThreadPoolExecutor4849import pytest5051import click52from click.testing import _NamedTextIOWrapper53from click.testing import BytesIOCopy54from click.testing import CliRunner55from click.testing import StreamMixer5657# ---------------------------------------------------------------------------58# Category 1: Stream ownership - ``_NamedTextIOWrapper`` must not close buffers59# ---------------------------------------------------------------------------606162def 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"717273def 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"838485def 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"99100101def 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"106107108# ---------------------------------------------------------------------------109# Category 2: ``StreamMixer`` lifecycle110# ---------------------------------------------------------------------------111112113def 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()126127 del out_w, err_w128 gc.collect()129130 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"136137138def test_getvalue_after_isolation_exit():139 """After the isolation context exits, stream values are readable."""140 runner = CliRunner()141142 @click.command()143 def cli():144 click.echo("stdout-msg")145 click.echo("stderr-msg", err=True)146147 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.output153154155def test_no_streammixer_del():156 """``StreamMixer`` should not have a ``__del__`` method.157158 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]163164165def 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"173174175def 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"182183184# ---------------------------------------------------------------------------185# Category 3: Logging interaction (issues #824, #3110)186# ---------------------------------------------------------------------------187188189def test_invoke_with_logger_warning():190 """Basic ``logging.warning()`` inside a command must not crash."""191 logger = logging.getLogger("test_invoke_with_logger_warning")192193 @click.command()194 def cli():195 logger.warning("a warning")196 click.echo("done")197198 runner = CliRunner()199 result = runner.invoke(cli)200 assert result.exit_code == 0201 assert "done" in result.output202203204def test_invoke_with_logger_and_prompt():205 """Logging + prompt (the exact #824 reproducer)."""206 logger = logging.getLogger("test_invoke_with_logger_and_prompt")207208 @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}!")213214 runner = CliRunner()215 result = runner.invoke(hello, input="Peter")216 assert result.exit_code == 0217 assert "Your name:" in result.output218219220def test_sequential_invokes_with_logging():221 """Multiple sequential ``invoke()`` calls with logging (#3110 reproducer).222223 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")228229 @click.command()230 @click.argument("msg")231 def cli(msg):232 logger.warning("log: %s", msg)233 click.echo(msg)234235 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.output240241242def 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:249250 @click.command()251 def cli():252 logger.info("message from inside invoke")253 click.echo("ok")254255 runner = CliRunner()256 result = runner.invoke(cli)257 assert result.exit_code == 0258 assert "ok" in result.output259 finally:260 logger.removeHandler(handler)261262263def test_logging_with_cli_log_level():264 """Simulate what ``--log-cli-level`` does: add a handler to root265 before invoke.266267 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:277278 @click.command()279 def cli():280 logging.warning("live log message")281 click.echo("output")282283 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)290291292# ---------------------------------------------------------------------------293# Category 4: Multi-threaded safety (issue #2993)294# ---------------------------------------------------------------------------295296297def test_invoke_with_thread_pool():298 """Basic ``ThreadPoolExecutor`` usage inside a command."""299300 @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}")306307 runner = CliRunner()308 result = runner.invoke(cli)309 assert result.exit_code == 0310 assert "results=" in result.output311312313def test_invoke_with_threads_writing_to_streams():314 """Threads writing to ``click.echo()`` during invocation."""315316 @click.command()317 def cli():318 barrier = threading.Barrier(3)319320 def worker(n):321 barrier.wait(timeout=5)322 click.echo(f"worker-{n}")323324 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")330331 runner = CliRunner()332 result = runner.invoke(cli)333 assert result.exit_code == 0334 assert "main-done" in result.output335336337def test_invoke_with_thread_pool_and_exit():338 """``ThreadPoolExecutor`` + ``SystemExit`` (the exact #2993 reproducer)."""339340 @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)346347 runner = CliRunner()348 result = runner.invoke(cli, ["test"])349 assert result.exit_code == 1350351352def test_sequential_threaded_invokes():353 """Multiple sequential invocations with threads don't leak state."""354355 @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))361362 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)367368369# ---------------------------------------------------------------------------370# Category 5: Sequential invocations and state isolation371# ---------------------------------------------------------------------------372373374def test_output_isolation_across_invokes():375 """Each ``invoke()`` must capture only its own output."""376377 @click.command()378 @click.argument("msg")379 def cli(msg):380 click.echo(msg)381382 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() == word387388389def test_stderr_isolation_across_invokes():390 """Each ``invoke()`` must capture only its own stderr."""391392 @click.command()393 @click.argument("msg")394 def cli(msg):395 click.echo(msg, err=True)396397 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() == ""403404405def test_mixed_output_order_preserved():406 """stdout/stderr interleaving is captured in order."""407408 @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)414415 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"420421422def test_exception_does_not_corrupt_next_invoke():423 """A failed invoke must not break subsequent invocations."""424 call_count = 0425426 @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}")433434 runner = CliRunner()435436 r1 = runner.invoke(cli)437 assert r1.exit_code == 0438 assert "call-1" in r1.output439440 r2 = runner.invoke(cli)441 assert r2.exit_code == 1442 assert isinstance(r2.exception, RuntimeError)443444 r3 = runner.invoke(cli)445 assert r3.exit_code == 0446 assert "call-3" in r3.output447448449def 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.stdin454455 @click.command()456 def cli():457 click.echo("inside")458459 runner = CliRunner()460 runner.invoke(cli)461462 assert sys.stdout is original_stdout463 assert sys.stderr is original_stderr464 assert sys.stdin is original_stdin465466467def test_sys_streams_restored_after_exception():468 """sys streams are restored even when the command raises."""469 original_stdout = sys.stdout470 original_stderr = sys.stderr471472 @click.command()473 def cli():474 raise RuntimeError("boom")475476 runner = CliRunner()477 runner.invoke(cli)478479 assert sys.stdout is original_stdout480 assert sys.stderr is original_stderr481482483# ---------------------------------------------------------------------------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# ---------------------------------------------------------------------------489490491@pytest.mark.stress492@pytest.mark.parametrize("_", range(10_000))493def test_stress_thread_pool_with_exit(_):494 """Exact #2993 reproducer: ``ThreadPoolExecutor`` + ``SystemExit``."""495496 @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)502503 runner = CliRunner()504 result = runner.invoke(cli, ["test"])505 assert result.exit_code == 1506507508@pytest.mark.stress509@pytest.mark.parametrize("_", range(10_000))510def test_stress_logging_sequential_invocations(_):511 """#3110/#824 reproducer: sequential invocations with logging."""512 logger = logging.getLogger("stress_sequential")513514 @click.command()515 def cli():516 logger.warning("msg")517 click.echo("ok")518519 runner = CliRunner()520 result = runner.invoke(cli)521 assert result.exit_code == 0522523524@pytest.mark.stress525@pytest.mark.parametrize("_", range(10_000))526def test_stress_gc_between_invocations(_):527 """Force GC after each invocation to provoke finalizer races."""528529 @click.command()530 def cli():531 click.echo("output")532 click.echo("error", err=True)533534 runner = CliRunner()535 result = runner.invoke(cli)536 assert result.exit_code == 0537 assert "output" in result.output538 gc.collect()
deleted:tests/test_testing_logging.py-25 removed
1import logging23import click4from click.testing import CliRunner567# Minimized version of:8# https://github.com/pallets/click/issues/824#issuecomment-30272632629#10# Test needs to be run as "pytest --log-cli-level 30 tests/test_testing_logging.py"11# to test the intended functionality.12def test_runner_logger():13 logger = logging.getLogger(__name__)1415 @click.command()16 @click.option("--name", prompt="Your name", help="The person to greet.")17 def hello(name):18 logger.warning("Greeting user now...")19 click.echo(f"Hello, {name}!")2021 runner = CliRunner()22 result = runner.invoke(hello, input="Peter")23 assert result.exit_code == 024 # FIXME: second half of the output is missing with --log-cli-level 30.25 assert result.output in ("Your name: Peter\n", "Your name: Peter\nHello, Peter!\n")
modified:CHANGES.rst+5 added-1 removed
5 unmodified lines
6 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:`2993` :pr:`3139`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`1516Version 8.3.117--------------18
1305 unmodified lines
modified:pyproject.toml+15 added
81 unmodified lines
82testpaths = ["tests"]83filterwarnings = [84 "error",85]86markers = [87 "stress: high-iteration stress tests for race conditions (deselect with '-m \"not stress\"')",88]89addopts = "-m 'not stress'"9091[tool.coverage.run]92branch = true93source = ["click", "tests"]
51 unmodified lines
145env_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 lines
164 "pytest", "-v", "--tb=short", "--basetemp={env_tmp_dir}",165 {replace = "posargs", default = [], extend = true},166]]167168[tool.tox.env.stress]169description = "stress tests for stream lifecycle race conditions"170commands = [[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]]177178[tool.tox.env.style]179description = "run all pre-commit hooks on all files"180dependency_groups = ["pre-commit"]181skip_install = true
41 unmodified lines