test_testing.py
This file
Path
tests/test_testing.py
760 lines · 20.8 KiB · Python
Last changed by
fix I/O operation on closed file error with CliRunner and echo_via_pager (#3482)David Lordbefore adoption5ee8e31
History of this fileTake it
1import faulthandler2import io3import os4import pdb5import sys6from io import BytesIO78import pytest910import click11from click.exceptions import ClickException12from click.testing import CliRunner131415def test_runner():16 @click.command()17 def test():18 i = click.get_binary_stream("stdin")19 o = click.get_binary_stream("stdout")20 while True:21 chunk = i.read(4096)22 if not chunk:23 break24 o.write(chunk)25 o.flush()2627 runner = CliRunner()28 result = runner.invoke(test, input="Hello World!\n")29 assert not result.exception30 assert result.output == "Hello World!\n"313233def test_echo_stdin_stream():34 @click.command()35 def test():36 i = click.get_binary_stream("stdin")37 o = click.get_binary_stream("stdout")38 while True:39 chunk = i.read(4096)40 if not chunk:41 break42 o.write(chunk)43 o.flush()4445 runner = CliRunner(echo_stdin=True)46 result = runner.invoke(test, input="Hello World!\n")47 assert not result.exception48 assert result.output == "Hello World!\nHello World!\n"495051def test_echo_stdin_prompts():52 @click.command()53 def test_python_input():54 foo = input("Foo: ")55 click.echo(f"foo={foo}")5657 runner = CliRunner(echo_stdin=True)58 result = runner.invoke(test_python_input, input="bar bar\n")59 assert not result.exception60 assert result.output == "Foo: bar bar\nfoo=bar bar\n"6162 @click.command()63 @click.option("--foo", prompt=True)64 def test_prompt(foo):65 click.echo(f"foo={foo}")6667 result = runner.invoke(test_prompt, input="bar bar\n")68 assert not result.exception69 assert result.output == "Foo: bar bar\nfoo=bar bar\n"7071 @click.command()72 @click.option("--foo", prompt=True, hide_input=True)73 def test_hidden_prompt(foo):74 click.echo(f"foo={foo}")7576 result = runner.invoke(test_hidden_prompt, input="bar bar\n")77 assert not result.exception78 assert result.output == "Foo: \nfoo=bar bar\n"7980 @click.command()81 @click.option("--foo", prompt=True)82 @click.option("--bar", prompt=True)83 def test_multiple_prompts(foo, bar):84 click.echo(f"foo={foo}, bar={bar}")8586 result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")87 assert not result.exception88 assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"899091def test_runner_with_stream():92 @click.command()93 def test():94 i = click.get_binary_stream("stdin")95 o = click.get_binary_stream("stdout")96 while True:97 chunk = i.read(4096)98 if not chunk:99 break100 o.write(chunk)101 o.flush()102103 runner = CliRunner()104 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))105 assert not result.exception106 assert result.output == "Hello World!\n"107108 runner = CliRunner(echo_stdin=True)109 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))110 assert not result.exception111 assert result.output == "Hello World!\nHello World!\n"112113114def test_prompts():115 @click.command()116 @click.option("--foo", prompt=True)117 def test(foo):118 click.echo(f"foo={foo}")119120 runner = CliRunner()121 result = runner.invoke(test, input="wau wau\n")122 assert not result.exception123 assert result.output == "Foo: wau wau\nfoo=wau wau\n"124125 @click.command()126 @click.option("--foo", prompt=True, hide_input=True)127 def test(foo):128 click.echo(f"foo={foo}")129130 runner = CliRunner()131 result = runner.invoke(test, input="wau wau\n")132 assert not result.exception133 assert result.output == "Foo: \nfoo=wau wau\n"134135136def test_getchar():137 @click.command()138 def continue_it():139 click.echo(click.getchar())140141 runner = CliRunner()142 result = runner.invoke(continue_it, input="y")143 assert not result.exception144 assert result.output == "y\n"145146 runner = CliRunner(echo_stdin=True)147 result = runner.invoke(continue_it, input="y")148 assert not result.exception149 assert result.output == "y\n"150151 @click.command()152 def getchar_echo():153 click.echo(click.getchar(echo=True))154155 runner = CliRunner()156 result = runner.invoke(getchar_echo, input="y")157 assert not result.exception158 assert result.output == "yy\n"159160 runner = CliRunner(echo_stdin=True)161 result = runner.invoke(getchar_echo, input="y")162 assert not result.exception163 assert result.output == "yy\n"164165166def test_catch_exceptions():167 class CustomError(Exception):168 pass169170 @click.command()171 def cli():172 raise CustomError(1)173174 runner = CliRunner()175176 result = runner.invoke(cli)177 assert isinstance(result.exception, CustomError)178 assert type(result.exc_info) is tuple179 assert len(result.exc_info) == 3180181 with pytest.raises(CustomError):182 runner.invoke(cli, catch_exceptions=False)183184 CustomError = SystemExit185186 result = runner.invoke(cli)187 assert result.exit_code == 1188189190def test_catch_exceptions_cli_runner():191 """Test that invoke `catch_exceptions` takes the value from CliRunner if not set192 explicitly."""193194 class CustomError(Exception):195 pass196197 @click.command()198 def cli():199 raise CustomError(1)200201 runner = CliRunner(catch_exceptions=False)202203 result = runner.invoke(cli, catch_exceptions=True)204 assert isinstance(result.exception, CustomError)205 assert type(result.exc_info) is tuple206 assert len(result.exc_info) == 3207208 with pytest.raises(CustomError):209 runner.invoke(cli)210211212def test_with_color():213 @click.command()214 def cli():215 click.secho("hello world", fg="blue")216217 runner = CliRunner()218219 result = runner.invoke(cli)220 assert result.output == "hello world\n"221 assert not result.exception222223 result = runner.invoke(cli, color=True)224 assert result.output == f"{click.style('hello world', fg='blue')}\n"225 assert not result.exception226227228def test_with_color_errors():229 class CLIError(ClickException):230 def format_message(self) -> str:231 return click.style(self.message, fg="red")232233 @click.command()234 def cli():235 raise CLIError("Red error")236237 runner = CliRunner()238239 result = runner.invoke(cli)240 assert result.output == "Error: Red error\n"241 assert result.exception242243 result = runner.invoke(cli, color=True)244 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"245 assert result.exception246247248def test_with_color_but_pause_not_blocking():249 @click.command()250 def cli():251 click.pause()252253 runner = CliRunner()254 result = runner.invoke(cli, color=True)255 assert not result.exception256 assert result.output == ""257258259def test_with_echo_via_pager():260 @click.command()261 def cli():262 click.echo_via_pager("Hello, Click!")263264 runner = CliRunner()265 result = runner.invoke(cli)266 assert not result.exception267 assert result.output == "Hello, Click!\n"268269270def test_exit_code_and_output_from_sys_exit():271 # See issue #362272 @click.command()273 def cli_string():274 click.echo("hello world")275 sys.exit("error")276277 @click.command()278 @click.pass_context279 def cli_string_ctx_exit(ctx):280 click.echo("hello world")281 ctx.exit("error")282283 @click.command()284 def cli_int():285 click.echo("hello world")286 sys.exit(1)287288 @click.command()289 @click.pass_context290 def cli_int_ctx_exit(ctx):291 click.echo("hello world")292 ctx.exit(1)293294 @click.command()295 def cli_float():296 click.echo("hello world")297 sys.exit(1.0)298299 @click.command()300 @click.pass_context301 def cli_float_ctx_exit(ctx):302 click.echo("hello world")303 ctx.exit(1.0)304305 @click.command()306 def cli_no_error():307 click.echo("hello world")308309 runner = CliRunner()310311 result = runner.invoke(cli_string)312 assert result.exit_code == 1313 assert result.output == "hello world\nerror\n"314315 result = runner.invoke(cli_string_ctx_exit)316 assert result.exit_code == 1317 assert result.output == "hello world\nerror\n"318319 result = runner.invoke(cli_int)320 assert result.exit_code == 1321 assert result.output == "hello world\n"322323 result = runner.invoke(cli_int_ctx_exit)324 assert result.exit_code == 1325 assert result.output == "hello world\n"326327 result = runner.invoke(cli_float)328 assert result.exit_code == 1329 assert result.output == "hello world\n1.0\n"330331 result = runner.invoke(cli_float_ctx_exit)332 assert result.exit_code == 1333 assert result.output == "hello world\n1.0\n"334335 result = runner.invoke(cli_no_error)336 assert result.exit_code == 0337 assert result.output == "hello world\n"338339340def test_env():341 @click.command()342 def cli_env():343 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")344345 runner = CliRunner()346347 env_orig = dict(os.environ)348 env = dict(env_orig)349 assert "TEST_CLICK_ENV" not in env350 env["TEST_CLICK_ENV"] = "some_value"351 result = runner.invoke(cli_env, env=env)352 assert result.exit_code == 0353 assert result.output == "ENV=some_value\n"354355 assert os.environ == env_orig356357358def test_stderr():359 @click.command()360 def cli_stderr():361 click.echo("1 - stdout")362 click.echo("2 - stderr", err=True)363 click.echo("3 - stdout")364 click.echo("4 - stderr", err=True)365366 runner_mix = CliRunner()367 result_mix = runner_mix.invoke(cli_stderr)368369 assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"370 assert result_mix.stdout == "1 - stdout\n3 - stdout\n"371 assert result_mix.stderr == "2 - stderr\n4 - stderr\n"372373 @click.command()374 def cli_empty_stderr():375 click.echo("stdout")376377 runner = CliRunner()378 result = runner.invoke(cli_empty_stderr)379380 assert result.output == "stdout\n"381 assert result.stdout == "stdout\n"382 assert result.stderr == ""383384385@pytest.mark.parametrize(386 "args, expected_output",387 [388 (None, "bar\n"),389 ([], "bar\n"),390 ("", "bar\n"),391 (["--foo", "one two"], "one two\n"),392 ('--foo "one two"', "one two\n"),393 ],394)395def test_args(args, expected_output):396 @click.command()397 @click.option("--foo", default="bar")398 def cli_args(foo):399 click.echo(foo)400401 runner = CliRunner()402 result = runner.invoke(cli_args, args=args)403 assert result.exit_code == 0404 assert result.output == expected_output405406407def test_setting_prog_name_in_extra():408 @click.command()409 def cli():410 click.echo("ok")411412 runner = CliRunner()413 result = runner.invoke(cli, prog_name="foobar")414 assert not result.exception415 assert result.output == "ok\n"416417418def test_command_standalone_mode_returns_value():419 @click.command()420 def cli():421 click.echo("ok")422 return "Hello, World!"423424 runner = CliRunner()425 result = runner.invoke(cli, standalone_mode=False)426 assert result.output == "ok\n"427 assert result.return_value == "Hello, World!"428 assert result.exit_code == 0429430431def test_file_stdin_attrs(runner):432 @click.command()433 @click.argument("f", type=click.File())434 def cli(f):435 click.echo(f.name)436 click.echo(f.mode, nl=False)437438 result = runner.invoke(cli, ["-"])439 assert result.output == "<stdin>\nr"440441442def test_isolated_runner(runner):443 with runner.isolated_filesystem() as d:444 assert os.path.exists(d)445446 assert not os.path.exists(d)447448449def test_isolated_runner_custom_tempdir(runner, tmp_path):450 with runner.isolated_filesystem(temp_dir=tmp_path) as d:451 assert os.path.exists(d)452453 assert os.path.exists(d)454 os.rmdir(d)455456457def test_isolation_stderr_errors():458 """Writing to stderr should escape invalid characters instead of459 raising a UnicodeEncodeError.460 """461 runner = CliRunner()462463 with runner.isolation() as (_, err, _):464 click.echo("\udce2", err=True, nl=False)465 assert err.getvalue() == b"\\udce2"466467468def test_isolation_flushes_unflushed_stderr():469 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up470 flushed by the runner at end of invocation.471 """472 runner = CliRunner()473474 with runner.isolation() as (_, err, _):475 click.echo("\udce2", err=True, nl=False)476 assert err.getvalue() == b"\\udce2"477478 @click.command()479 def cli():480 # set end="", flush=False so that it's totally clear that we won't get any481 # auto-flush behaviors482 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)483484 result = runner.invoke(cli)485 assert result.stderr == "gyarados gyarados gyarados"486487488def test_pdb_uses_real_streams():489 """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams490 so that interactive debuggers work instead of reading from the491 captured ``BytesIO`` stdin.492 """493494 @click.command()495 def cli():496 debugger = pdb.Pdb()497 assert debugger.stdin is sys.__stdin__498 assert debugger.stdout is sys.__stdout__499 click.echo("after debugger")500501 runner = CliRunner()502 result = runner.invoke(cli, catch_exceptions=False)503 assert result.output == "after debugger\n"504505506def test_pdb_explicit_streams_honored():507 """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not508 overridden by the ``CliRunner`` patch.509 """510511 @click.command()512 def cli():513 custom_in = sys.stdin514 custom_out = sys.stdout515 debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)516 assert debugger.stdin is custom_in517 assert debugger.stdout is custom_out518519 runner = CliRunner()520 runner.invoke(cli, catch_exceptions=False)521522523def test_pdb_init_restored_after_invoke():524 """``pdb.Pdb.__init__`` is restored to its original after invoke."""525 original = pdb.Pdb.__init__526527 @click.command()528 def cli():529 pass530531 runner = CliRunner()532 runner.invoke(cli)533534 assert pdb.Pdb.__init__ is original535536537needs_fd_capture = pytest.mark.skipif(538 sys.platform == "win32",539 reason="fd capture not supported on Windows",540)541542543def test_capture_invalid_mode():544 """Invalid capture mode raises ValueError."""545 with pytest.raises(ValueError, match="capture"):546 CliRunner(capture="invalid") # type: ignore[arg-type]547548549@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")550def test_capture_fd_windows_error():551 """fd capture raises ValueError on Windows."""552 with pytest.raises(ValueError, match="not supported on Windows"):553 CliRunner(capture="fd")554555556@needs_fd_capture557def test_capture_fd_os_write():558 """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""559560 @click.command()561 def cli():562 click.echo("python stdout")563 os.write(1, b"fd stdout\n")564 os.write(2, b"fd stderr\n")565566 runner = CliRunner(capture="fd")567 result = runner.invoke(cli)568 assert "python stdout" in result.stdout569 assert "fd stdout" in result.stdout570 assert "fd stderr" in result.stderr571572573@needs_fd_capture574def test_capture_fd_stale_reference():575 """capture='fd' captures writes from stale stdout references (issue #2874).576577 Simulates ``from sys import stdout`` at import time, which grabs578 the real stdout connected to fd 1. The stale object's underlying579 FileIO uses fd 1, so redirecting fd 1 captures its writes.580 """581 # open(1, ..., closefd=False) creates a writer whose underlying582 # FileIO uses fd 1 directly. This mirrors the real scenario:583 # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->584 # FileIO(fd=1).585 stale_stdout = open(1, "w", closefd=False) # noqa: SIM115586587 @click.command()588 def cli():589 stale_stdout.write("stale write\n")590 stale_stdout.flush()591 click.echo("normal write")592593 runner = CliRunner(capture="fd")594 result = runner.invoke(cli)595 assert "normal write" in result.stdout596 assert "stale write" in result.stdout597598599@needs_fd_capture600def test_capture_fd_logging_handler(tmp_path):601 """capture='fd' captures logging output from a handler holding a stale602 stderr reference (issue #2827).603604 stdlib logging.StreamHandler grabs sys.stderr at configuration time.605 Under normal CliRunner (sys-level capture), the handler still writes606 to the original stream object and output is lost. fd-level capture607 redirects the underlying file descriptor, so the writes are captured.608 """609 import logging610611 # Create a writer backed by the real fd 2, simulating a handler612 # configured at import time before pytest or CliRunner replaced613 # sys.stderr. open(2, closefd=False) mirrors the real scenario:614 # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->615 # FileIO(fd=2).616 stale_stderr = open(2, "w", closefd=False) # noqa: SIM115617 handler = logging.StreamHandler(stale_stderr)618 handler.setFormatter(logging.Formatter("%(message)s"))619620 logger = logging.getLogger(f"click_test_{tmp_path.name}")621 logger.addHandler(handler)622 logger.setLevel(logging.INFO)623 logger.propagate = False624625 @click.command()626 def cli():627 logger.info("log from stale handler")628 click.echo("normal echo")629630 # sys-level capture misses the log line (it bypasses sys.stderr).631 runner_sys = CliRunner(capture="sys")632 result_sys = runner_sys.invoke(cli)633 assert "normal echo" in result_sys.output634 assert "log from stale handler" not in result_sys.output635636 # fd-level capture catches it by redirecting fd 2.637 runner_fd = CliRunner(capture="fd")638 result_fd = runner_fd.invoke(cli)639 assert "normal echo" in result_fd.output640 assert "log from stale handler" in result_fd.output641642 logger.removeHandler(handler)643644645@needs_fd_capture646def test_capture_fd_faulthandler():647 """faulthandler.enable() works with capture='fd' (issue #2865)."""648649 @click.command()650 def cli():651 faulthandler.enable()652 click.echo("after faulthandler")653654 runner = CliRunner(capture="fd")655 result = runner.invoke(cli)656 assert result.exit_code == 0657 assert "after faulthandler" in result.output658659660def test_capture_sys_fileno_raises():661 """capture='sys' leaves fileno() raising UnsupportedOperation, so user662 code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host663 runner's stdout (issue #3384).664 """665666 @click.command()667 def cli():668 with pytest.raises(io.UnsupportedOperation):669 sys.stdout.fileno()670 with pytest.raises(io.UnsupportedOperation):671 sys.stderr.fileno()672 click.echo("ok")673674 runner = CliRunner(capture="sys")675 result = runner.invoke(cli)676 assert result.exit_code == 0, result.output677 assert "ok" in result.stdout678679680@needs_fd_capture681def test_capture_fd_stderr_separation():682 """capture='fd' properly separates fd-level stdout and stderr."""683684 @click.command()685 def cli():686 click.echo("py-out")687 click.echo("py-err", err=True)688 os.write(1, b"fd-out\n")689 os.write(2, b"fd-err\n")690691 runner = CliRunner(capture="fd")692 result = runner.invoke(cli)693 assert "py-out" in result.stdout694 assert "fd-out" in result.stdout695 assert "py-err" in result.stderr696 assert "fd-err" in result.stderr697 # Mixed output has all of them698 assert "py-out" in result.output699 assert "py-err" in result.output700 assert "fd-out" in result.output701 assert "fd-err" in result.output702703704@needs_fd_capture705def test_capture_fd_nesting():706 """Nested CliRunner.invoke() with fd capture works correctly."""707708 @click.command("inner")709 def inner_cli():710 click.echo("inner")711712 @click.command("outer")713 def outer_cli():714 click.echo("outer")715 os.write(1, b"outer fd\n")716 inner_runner = CliRunner(capture="fd")717 inner_result = inner_runner.invoke(inner_cli)718 click.echo(f"inner captured: {inner_result.stdout.strip()}")719720 runner = CliRunner(capture="fd")721 result = runner.invoke(outer_cli)722 assert "outer" in result.stdout723 assert "outer fd" in result.stdout724 assert "inner captured: inner" in result.stdout725726727@needs_fd_capture728@pytest.mark.parametrize("runner_capture", ["sys", "fd"])729@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])730def test_capture_pytest_matrix(731 request: pytest.FixtureRequest,732 runner_capture: str,733 pytest_fixture: str,734) -> None:735 """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""736 pytest_cap = request.getfixturevalue(pytest_fixture)737738 @click.command()739 def cli() -> None:740 click.echo("inside-stdout")741 click.echo("inside-stderr", err=True)742743 runner = CliRunner(capture=runner_capture)744 result = runner.invoke(cli)745746 # CliRunner sees Click's output.747 assert result.exit_code == 0748 assert "inside-stdout" in result.stdout749 assert "inside-stderr" in result.stderr750751 # Pytest capture machinery is still working after invoke().752 print("post-invoke-stdout")753 print("post-invoke-stderr", file=sys.stderr)754 captured = pytest_cap.readouterr()755 assert "post-invoke-stdout" in captured.out756 assert "post-invoke-stderr" in captured.err757758 # Click output is not leaking into Pytest.759 assert "inside-stdout" not in captured.out760 assert "inside-stderr" not in captured.err