test_stream_lifecycle.py
This file
Path
tests/test_stream_lifecycle.py
540 lines · 15.9 KiB · Python
Last changed by
Merge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)Kevin Deldyckebefore adoption8a1b1a3
History of this fileTake it
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 ``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.stress494@pytest.mark.parametrize("_", range(10_000))495def test_stress_thread_pool_with_exit(_):496 """Exact #2993 reproducer: ``ThreadPoolExecutor`` + ``SystemExit``."""497498 @click.command()499 @click.argument("args", nargs=-1)500 def cli(**_kw):501 with ThreadPoolExecutor() as executor:502 executor.submit(lambda: None).result()503 raise SystemExit(1)504505 runner = CliRunner()506 result = runner.invoke(cli, ["test"])507 assert result.exit_code == 1508509510@pytest.mark.stress511@pytest.mark.parametrize("_", range(10_000))512def test_stress_logging_sequential_invocations(_):513 """#3110/#824 reproducer: sequential invocations with logging."""514 logger = logging.getLogger("stress_sequential")515516 @click.command()517 def cli():518 logger.warning("msg")519 click.echo("ok")520521 runner = CliRunner()522 result = runner.invoke(cli)523 assert result.exit_code == 0524525526@pytest.mark.stress527@pytest.mark.parametrize("_", range(10_000))528def test_stress_gc_between_invocations(_):529 """Force GC after each invocation to provoke finalizer races."""530531 @click.command()532 def cli():533 click.echo("output")534 click.echo("error", err=True)535536 runner = CliRunner()537 result = runner.invoke(cli)538 assert result.exit_code == 0539 assert "output" in result.output540 gc.collect()