Skip to content

Commit cfa6f4a

Browse files
authored
Flush sys.stderr when CliRunner finalizes (#2933)
2 parents b7cf069 + f3a4363 commit cfa6f4a

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

CHANGES.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Version 8.2.1
66
- Fix flag value handling for flag options with a provided type. :issue:`2894`
77
:issue:`2897` :pr:`2930`
88
- Fix shell completion for nested groups. :issue:`2906` :pr:`2907`
9+
- Flush ``sys.stderr`` at the end of ``CliRunner.invoke``. :issue:`2682`
910

1011
Version 8.2.0
1112
-------------

src/click/testing.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,7 @@ def invoke(
510510
exc_info = sys.exc_info()
511511
finally:
512512
sys.stdout.flush()
513+
sys.stderr.flush()
513514
stdout = outstreams[0].getvalue()
514515
stderr = outstreams[1].getvalue()
515516
output = outstreams[2].getvalue()

tests/test_testing.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,3 +450,24 @@ def test_isolation_stderr_errors():
450450
click.echo("\udce2", err=True, nl=False)
451451

452452
assert err.getvalue() == b"\\udce2"
453+
454+
455+
def test_isolation_flushes_unflushed_stderr():
456+
"""An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up
457+
flushed by the runner at end of invocation.
458+
"""
459+
runner = CliRunner()
460+
461+
with runner.isolation() as (_, err, _):
462+
click.echo("\udce2", err=True, nl=False)
463+
464+
assert err.getvalue() == b"\\udce2"
465+
466+
@click.command()
467+
def cli():
468+
# set end="", flush=False so that it's totally clear that we won't get any
469+
# auto-flush behaviors
470+
print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)
471+
472+
result = runner.invoke(cli)
473+
assert result.stderr == "gyarados gyarados gyarados"

0 commit comments

Comments
 (0)