Debian Codegraph @

tests/test_stream_lifecycle.py

raw
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 logging
7 - PR #3139: The fix - prevent ``_NamedTextIOWrapper`` from closing owned buffers
8
9 The tests are organized by category:
10
11 1. Stream ownership: ``_NamedTextIOWrapper`` must not close buffers it wraps
12 2. ``StreamMixer`` lifecycle: buffers survive wrapper garbage collection
13 3. Logging interaction: ``CliRunner`` works with active logging handlers
14 4. Multi-threaded safety: concurrent threads don't cause I/O-on-closed-file
15 5. Sequential invocations: multiple ``invoke()`` calls don't corrupt state
16 6. Stress tests (marked ``stress``): high-iteration reproducers for races
17
18 How to run locally
19 ------------------
20
21 Standard tests (fast, ~0.8s) with stress tests excluded by default:
22
23 .. code-block:: shell-session
24
25 $ pytest tests/test_stream_lifecycle.py -v
26
27 Stress tests only (30k iterations, ~52min):
28
29 .. code-block:: shell-session
30
31 $ pytest tests/test_stream_lifecycle.py -m stress -x --override-ini="addopts="
32
33 Everything:
34
35 .. code-block:: shell-session
36
37 $ pytest tests/test_stream_lifecycle.py --override-ini="addopts=" -x
38 """
39
40 from __future__ import annotations
41
42 import gc
43 import io
44 import logging
45 import sys
46 import threading
47 from concurrent.futures import ThreadPoolExecutor
48
49 import pytest
50
51 import click
52 from click.testing import _NamedTextIOWrapper
53 from click.testing import BytesIOCopy
54 from click.testing import CliRunner
55 from click.testing import StreamMixer
56
57 # ---------------------------------------------------------------------------
58 # Category 1: Stream ownership - ``_NamedTextIOWrapper`` must not close buffers
59 # ---------------------------------------------------------------------------
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.closed
70 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 wrapper
80 gc.collect()
81 assert not buf.closed
82 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 write
94 w2.write("two")
95 w2.flush()
96 w2.close()
97 assert not buf.closed
98 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`` lifecycle
110 # ---------------------------------------------------------------------------
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_w
128 gc.collect()
129
130 assert not mixer.stdout.closed
131 assert not mixer.stderr.closed
132 assert not mixer.output.closed
133 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 == 0
149 assert result.stdout == "stdout-msg\n"
150 assert result.stderr == "stderr-msg\n"
151 assert "stdout-msg" in result.output
152 assert "stderr-msg" in result.output
153
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 == 0
201 assert "done" in result.output
202
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 == 0
217 assert "Your name:" in result.output
218
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 on
224 the second invocation because the first ``StreamMixer``'s ``__del__`` would
225 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.output
240
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 == 0
258 assert "ok" in result.output
259 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 root
265 before invoke.
266
267 This reproduces the original #824 scenario without needing pytest
268 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.level
275 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 == 0
286 assert "output" in result.output
287 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 == 0
310 assert "results=" in result.output
311
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 == 0
334 assert "main-done" in result.output
335
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 == 1
350
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 == 0
366 assert result.output.strip() == str(i + 1)
367
368
369 # ---------------------------------------------------------------------------
370 # Category 5: Sequential invocations and state isolation
371 # ---------------------------------------------------------------------------
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 == 0
386 assert result.output.strip() == word
387
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 == 0
401 assert result.stderr.strip() == word
402 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 = 0
425
426 @click.command()
427 def cli():
428 nonlocal call_count
429 call_count += 1
430 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 == 0
438 assert "call-1" in r1.output
439
440 r2 = runner.invoke(cli)
441 assert r2.exit_code == 1
442 assert isinstance(r2.exception, RuntimeError)
443
444 r3 = runner.invoke(cli)
445 assert r3.exit_code == 0
446 assert "call-3" in r3.output
447
448
449 def test_sys_streams_restored_after_invoke():
450 """``sys.stdout``/``stderr``/``stdin`` are restored after ``invoke()``."""
451 original_stdout = sys.stdout
452 original_stderr = sys.stderr
453 original_stdin = sys.stdin
454
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_stdout
463 assert sys.stderr is original_stderr
464 assert sys.stdin is original_stdin
465
466
467 def test_sys_streams_restored_after_exception():
468 """sys streams are restored even when the command raises."""
469 original_stdout = sys.stdout
470 original_stderr = sys.stderr
471
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_stdout
480 assert sys.stderr is original_stderr
481
482
483 # ---------------------------------------------------------------------------
484 # Category 6: Stress tests - high-iteration reproducers for race conditions
485 #
486 # These are marked with ``pytest.mark.stress`` so they can be included or
487 # excluded independently. The CI workflow runs them in a separate job.
488 # ---------------------------------------------------------------------------
489
490
491 @pytest.mark.stress
492 @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 == 1
506
507
508 @pytest.mark.stress
509 @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 == 0
522
523
524 @pytest.mark.stress
525 @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 == 0
537 assert "output" in result.output
538 gc.collect()