Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/click/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@ def __init__(self) -> None:
self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)
self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)

def __del__(self) -> None:
"""
Guarantee that embedded file-like objects are closed in a
predictable order, protecting against races between
self.output being closed and other streams being flushed on close

.. versionadded:: 8.2.2
"""
self.stderr.close()
self.stdout.close()
self.output.close()


class _NamedTextIOWrapper(io.TextIOWrapper):
def __init__(
Expand Down
6 changes: 2 additions & 4 deletions tests/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,8 +448,7 @@ def test_isolation_stderr_errors():

with runner.isolation() as (_, err, _):
click.echo("\udce2", err=True, nl=False)

assert err.getvalue() == b"\\udce2"
Copy link
Copy Markdown
Contributor Author

@neutrinoceros neutrinoceros Jul 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With my patch, stream objects yielded from runner.isolation, including err, may be closed as the context manager exits, dereferencing (hence, allowing gc to collect) its internal StreamMixer reference. Comparable tests already do it this way, so I'm hoping that this change is acceptable.

assert err.getvalue() == b"\\udce2"


def test_isolation_flushes_unflushed_stderr():
Expand All @@ -460,8 +459,7 @@ def test_isolation_flushes_unflushed_stderr():

with runner.isolation() as (_, err, _):
click.echo("\udce2", err=True, nl=False)

assert err.getvalue() == b"\\udce2"
assert err.getvalue() == b"\\udce2"

@click.command()
def cli():
Expand Down
Loading