Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

761 lines · 20.8 KiB · Python

Last changed by

Revert "Deprecate `isolated_filesystem` and document its limits"Kevin Deldyckebefore adoption8ee83dd

History of this file

Take it

1import faulthandler2import io3import os4import pdb5import sys6from io import BytesIO78import pytest910import click11from click.exceptions import ClickException12from click.testing import CliRunner13from click.utils import _get_binary_stream141516def test_runner():17    @click.command()18    def test():19        i = _get_binary_stream("stdin")20        o = _get_binary_stream("stdout")21        while True:22            chunk = i.read(4096)23            if not chunk:24                break25            o.write(chunk)26            o.flush()2728    runner = CliRunner()29    result = runner.invoke(test, input="Hello World!\n")30    assert not result.exception31    assert result.output == "Hello World!\n"323334def test_echo_stdin_stream():35    @click.command()36    def test():37        i = _get_binary_stream("stdin")38        o = _get_binary_stream("stdout")39        while True:40            chunk = i.read(4096)41            if not chunk:42                break43            o.write(chunk)44            o.flush()4546    runner = CliRunner(echo_stdin=True)47    result = runner.invoke(test, input="Hello World!\n")48    assert not result.exception49    assert result.output == "Hello World!\nHello World!\n"505152def test_echo_stdin_prompts():53    @click.command()54    def test_python_input():55        foo = input("Foo: ")56        click.echo(f"foo={foo}")5758    runner = CliRunner(echo_stdin=True)59    result = runner.invoke(test_python_input, input="bar bar\n")60    assert not result.exception61    assert result.output == "Foo: bar bar\nfoo=bar bar\n"6263    @click.command()64    @click.option("--foo", prompt=True)65    def test_prompt(foo):66        click.echo(f"foo={foo}")6768    result = runner.invoke(test_prompt, input="bar bar\n")69    assert not result.exception70    assert result.output == "Foo: bar bar\nfoo=bar bar\n"7172    @click.command()73    @click.option("--foo", prompt=True, hide_input=True)74    def test_hidden_prompt(foo):75        click.echo(f"foo={foo}")7677    result = runner.invoke(test_hidden_prompt, input="bar bar\n")78    assert not result.exception79    assert result.output == "Foo: \nfoo=bar bar\n"8081    @click.command()82    @click.option("--foo", prompt=True)83    @click.option("--bar", prompt=True)84    def test_multiple_prompts(foo, bar):85        click.echo(f"foo={foo}, bar={bar}")8687    result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")88    assert not result.exception89    assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"909192def test_runner_with_stream():93    @click.command()94    def test():95        i = _get_binary_stream("stdin")96        o = _get_binary_stream("stdout")97        while True:98            chunk = i.read(4096)99            if not chunk:100                break101            o.write(chunk)102            o.flush()103104    runner = CliRunner()105    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))106    assert not result.exception107    assert result.output == "Hello World!\n"108109    runner = CliRunner(echo_stdin=True)110    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))111    assert not result.exception112    assert result.output == "Hello World!\nHello World!\n"113114115def test_prompts():116    @click.command()117    @click.option("--foo", prompt=True)118    def test(foo):119        click.echo(f"foo={foo}")120121    runner = CliRunner()122    result = runner.invoke(test, input="wau wau\n")123    assert not result.exception124    assert result.output == "Foo: wau wau\nfoo=wau wau\n"125126    @click.command()127    @click.option("--foo", prompt=True, hide_input=True)128    def test(foo):129        click.echo(f"foo={foo}")130131    runner = CliRunner()132    result = runner.invoke(test, input="wau wau\n")133    assert not result.exception134    assert result.output == "Foo: \nfoo=wau wau\n"135136137def test_getchar():138    @click.command()139    def continue_it():140        click.echo(click.getchar())141142    runner = CliRunner()143    result = runner.invoke(continue_it, input="y")144    assert not result.exception145    assert result.output == "y\n"146147    runner = CliRunner(echo_stdin=True)148    result = runner.invoke(continue_it, input="y")149    assert not result.exception150    assert result.output == "y\n"151152    @click.command()153    def getchar_echo():154        click.echo(click.getchar(echo=True))155156    runner = CliRunner()157    result = runner.invoke(getchar_echo, input="y")158    assert not result.exception159    assert result.output == "yy\n"160161    runner = CliRunner(echo_stdin=True)162    result = runner.invoke(getchar_echo, input="y")163    assert not result.exception164    assert result.output == "yy\n"165166167def test_catch_exceptions():168    class CustomError(Exception):169        pass170171    @click.command()172    def cli():173        raise CustomError(1)174175    runner = CliRunner()176177    result = runner.invoke(cli)178    assert isinstance(result.exception, CustomError)179    assert type(result.exc_info) is tuple180    assert len(result.exc_info) == 3181182    with pytest.raises(CustomError):183        runner.invoke(cli, catch_exceptions=False)184185    CustomError = SystemExit186187    result = runner.invoke(cli)188    assert result.exit_code == 1189190191def test_catch_exceptions_cli_runner():192    """Test that invoke `catch_exceptions` takes the value from CliRunner if not set193    explicitly."""194195    class CustomError(Exception):196        pass197198    @click.command()199    def cli():200        raise CustomError(1)201202    runner = CliRunner(catch_exceptions=False)203204    result = runner.invoke(cli, catch_exceptions=True)205    assert isinstance(result.exception, CustomError)206    assert type(result.exc_info) is tuple207    assert len(result.exc_info) == 3208209    with pytest.raises(CustomError):210        runner.invoke(cli)211212213def test_with_color():214    @click.command()215    def cli():216        click.secho("hello world", fg="blue")217218    runner = CliRunner()219220    result = runner.invoke(cli)221    assert result.output == "hello world\n"222    assert not result.exception223224    result = runner.invoke(cli, color=True)225    assert result.output == f"{click.style('hello world', fg='blue')}\n"226    assert not result.exception227228229def test_with_color_errors():230    class CLIError(ClickException):231        def format_message(self) -> str:232            return click.style(self.message, fg="red")233234    @click.command()235    def cli():236        raise CLIError("Red error")237238    runner = CliRunner()239240    result = runner.invoke(cli)241    assert result.output == "Error: Red error\n"242    assert result.exception243244    result = runner.invoke(cli, color=True)245    assert result.output == f"Error: {click.style('Red error', fg='red')}\n"246    assert result.exception247248249def test_with_color_but_pause_not_blocking():250    @click.command()251    def cli():252        click.pause()253254    runner = CliRunner()255    result = runner.invoke(cli, color=True)256    assert not result.exception257    assert result.output == ""258259260def test_with_echo_via_pager():261    @click.command()262    def cli():263        click.echo_via_pager("Hello, Click!")264265    runner = CliRunner()266    result = runner.invoke(cli)267    assert not result.exception268    assert result.output == "Hello, Click!\n"269270271def test_exit_code_and_output_from_sys_exit():272    # See issue #362273    @click.command()274    def cli_string():275        click.echo("hello world")276        sys.exit("error")277278    @click.command()279    @click.pass_context280    def cli_string_ctx_exit(ctx):281        click.echo("hello world")282        ctx.exit("error")283284    @click.command()285    def cli_int():286        click.echo("hello world")287        sys.exit(1)288289    @click.command()290    @click.pass_context291    def cli_int_ctx_exit(ctx):292        click.echo("hello world")293        ctx.exit(1)294295    @click.command()296    def cli_float():297        click.echo("hello world")298        sys.exit(1.0)299300    @click.command()301    @click.pass_context302    def cli_float_ctx_exit(ctx):303        click.echo("hello world")304        ctx.exit(1.0)305306    @click.command()307    def cli_no_error():308        click.echo("hello world")309310    runner = CliRunner()311312    result = runner.invoke(cli_string)313    assert result.exit_code == 1314    assert result.output == "hello world\nerror\n"315316    result = runner.invoke(cli_string_ctx_exit)317    assert result.exit_code == 1318    assert result.output == "hello world\nerror\n"319320    result = runner.invoke(cli_int)321    assert result.exit_code == 1322    assert result.output == "hello world\n"323324    result = runner.invoke(cli_int_ctx_exit)325    assert result.exit_code == 1326    assert result.output == "hello world\n"327328    result = runner.invoke(cli_float)329    assert result.exit_code == 1330    assert result.output == "hello world\n1.0\n"331332    result = runner.invoke(cli_float_ctx_exit)333    assert result.exit_code == 1334    assert result.output == "hello world\n1.0\n"335336    result = runner.invoke(cli_no_error)337    assert result.exit_code == 0338    assert result.output == "hello world\n"339340341def test_env():342    @click.command()343    def cli_env():344        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")345346    runner = CliRunner()347348    env_orig = dict(os.environ)349    env = dict(env_orig)350    assert "TEST_CLICK_ENV" not in env351    env["TEST_CLICK_ENV"] = "some_value"352    result = runner.invoke(cli_env, env=env)353    assert result.exit_code == 0354    assert result.output == "ENV=some_value\n"355356    assert os.environ == env_orig357358359def test_stderr():360    @click.command()361    def cli_stderr():362        click.echo("1 - stdout")363        click.echo("2 - stderr", err=True)364        click.echo("3 - stdout")365        click.echo("4 - stderr", err=True)366367    runner_mix = CliRunner()368    result_mix = runner_mix.invoke(cli_stderr)369370    assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"371    assert result_mix.stdout == "1 - stdout\n3 - stdout\n"372    assert result_mix.stderr == "2 - stderr\n4 - stderr\n"373374    @click.command()375    def cli_empty_stderr():376        click.echo("stdout")377378    runner = CliRunner()379    result = runner.invoke(cli_empty_stderr)380381    assert result.output == "stdout\n"382    assert result.stdout == "stdout\n"383    assert result.stderr == ""384385386@pytest.mark.parametrize(387    "args, expected_output",388    [389        (None, "bar\n"),390        ([], "bar\n"),391        ("", "bar\n"),392        (["--foo", "one two"], "one two\n"),393        ('--foo "one two"', "one two\n"),394    ],395)396def test_args(args, expected_output):397    @click.command()398    @click.option("--foo", default="bar")399    def cli_args(foo):400        click.echo(foo)401402    runner = CliRunner()403    result = runner.invoke(cli_args, args=args)404    assert result.exit_code == 0405    assert result.output == expected_output406407408def test_setting_prog_name_in_extra():409    @click.command()410    def cli():411        click.echo("ok")412413    runner = CliRunner()414    result = runner.invoke(cli, prog_name="foobar")415    assert not result.exception416    assert result.output == "ok\n"417418419def test_command_standalone_mode_returns_value():420    @click.command()421    def cli():422        click.echo("ok")423        return "Hello, World!"424425    runner = CliRunner()426    result = runner.invoke(cli, standalone_mode=False)427    assert result.output == "ok\n"428    assert result.return_value == "Hello, World!"429    assert result.exit_code == 0430431432def test_file_stdin_attrs(runner):433    @click.command()434    @click.argument("f", type=click.File())435    def cli(f):436        click.echo(f.name)437        click.echo(f.mode, nl=False)438439    result = runner.invoke(cli, ["-"])440    assert result.output == "<stdin>\nr"441442443def test_isolated_runner(runner):444    with runner.isolated_filesystem() as d:445        assert os.path.exists(d)446447    assert not os.path.exists(d)448449450def test_isolated_runner_custom_tempdir(runner, tmp_path):451    with runner.isolated_filesystem(temp_dir=tmp_path) as d:452        assert os.path.exists(d)453454    assert os.path.exists(d)455    os.rmdir(d)456457458def test_isolation_stderr_errors():459    """Writing to stderr should escape invalid characters instead of460    raising a UnicodeEncodeError.461    """462    runner = CliRunner()463464    with runner.isolation() as (_, err, _):465        click.echo("\udce2", err=True, nl=False)466        assert err.getvalue() == b"\\udce2"467468469def test_isolation_flushes_unflushed_stderr():470    """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up471    flushed by the runner at end of invocation.472    """473    runner = CliRunner()474475    with runner.isolation() as (_, err, _):476        click.echo("\udce2", err=True, nl=False)477        assert err.getvalue() == b"\\udce2"478479    @click.command()480    def cli():481        # set end="", flush=False so that it's totally clear that we won't get any482        # auto-flush behaviors483        print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)484485    result = runner.invoke(cli)486    assert result.stderr == "gyarados gyarados gyarados"487488489def test_pdb_uses_real_streams():490    """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams491    so that interactive debuggers work instead of reading from the492    captured ``BytesIO`` stdin.493    """494495    @click.command()496    def cli():497        debugger = pdb.Pdb()498        assert debugger.stdin is sys.__stdin__499        assert debugger.stdout is sys.__stdout__500        click.echo("after debugger")501502    runner = CliRunner()503    result = runner.invoke(cli, catch_exceptions=False)504    assert result.output == "after debugger\n"505506507def test_pdb_explicit_streams_honored():508    """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not509    overridden by the ``CliRunner`` patch.510    """511512    @click.command()513    def cli():514        custom_in = sys.stdin515        custom_out = sys.stdout516        debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)517        assert debugger.stdin is custom_in518        assert debugger.stdout is custom_out519520    runner = CliRunner()521    runner.invoke(cli, catch_exceptions=False)522523524def test_pdb_init_restored_after_invoke():525    """``pdb.Pdb.__init__`` is restored to its original after invoke."""526    original = pdb.Pdb.__init__527528    @click.command()529    def cli():530        pass531532    runner = CliRunner()533    runner.invoke(cli)534535    assert pdb.Pdb.__init__ is original536537538needs_fd_capture = pytest.mark.skipif(539    sys.platform == "win32",540    reason="fd capture not supported on Windows",541)542543544def test_capture_invalid_mode():545    """Invalid capture mode raises ValueError."""546    with pytest.raises(ValueError, match="capture"):547        CliRunner(capture="invalid")  # type: ignore[arg-type]548549550@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")551def test_capture_fd_windows_error():552    """fd capture raises ValueError on Windows."""553    with pytest.raises(ValueError, match="not supported on Windows"):554        CliRunner(capture="fd")555556557@needs_fd_capture558def test_capture_fd_os_write():559    """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""560561    @click.command()562    def cli():563        click.echo("python stdout")564        os.write(1, b"fd stdout\n")565        os.write(2, b"fd stderr\n")566567    runner = CliRunner(capture="fd")568    result = runner.invoke(cli)569    assert "python stdout" in result.stdout570    assert "fd stdout" in result.stdout571    assert "fd stderr" in result.stderr572573574@needs_fd_capture575def test_capture_fd_stale_reference():576    """capture='fd' captures writes from stale stdout references (issue #2874).577578    Simulates ``from sys import stdout`` at import time, which grabs579    the real stdout connected to fd 1.  The stale object's underlying580    FileIO uses fd 1, so redirecting fd 1 captures its writes.581    """582    # open(1, ..., closefd=False) creates a writer whose underlying583    # FileIO uses fd 1 directly. This mirrors the real scenario:584    # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->585    # FileIO(fd=1).586    stale_stdout = open(1, "w", closefd=False)  # noqa: SIM115587588    @click.command()589    def cli():590        stale_stdout.write("stale write\n")591        stale_stdout.flush()592        click.echo("normal write")593594    runner = CliRunner(capture="fd")595    result = runner.invoke(cli)596    assert "normal write" in result.stdout597    assert "stale write" in result.stdout598599600@needs_fd_capture601def test_capture_fd_logging_handler(tmp_path):602    """capture='fd' captures logging output from a handler holding a stale603    stderr reference (issue #2827).604605    stdlib logging.StreamHandler grabs sys.stderr at configuration time.606    Under normal CliRunner (sys-level capture), the handler still writes607    to the original stream object and output is lost. fd-level capture608    redirects the underlying file descriptor, so the writes are captured.609    """610    import logging611612    # Create a writer backed by the real fd 2, simulating a handler613    # configured at import time before pytest or CliRunner replaced614    # sys.stderr. open(2, closefd=False) mirrors the real scenario:615    # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->616    # FileIO(fd=2).617    stale_stderr = open(2, "w", closefd=False)  # noqa: SIM115618    handler = logging.StreamHandler(stale_stderr)619    handler.setFormatter(logging.Formatter("%(message)s"))620621    logger = logging.getLogger(f"click_test_{tmp_path.name}")622    logger.addHandler(handler)623    logger.setLevel(logging.INFO)624    logger.propagate = False625626    @click.command()627    def cli():628        logger.info("log from stale handler")629        click.echo("normal echo")630631    # sys-level capture misses the log line (it bypasses sys.stderr).632    runner_sys = CliRunner(capture="sys")633    result_sys = runner_sys.invoke(cli)634    assert "normal echo" in result_sys.output635    assert "log from stale handler" not in result_sys.output636637    # fd-level capture catches it by redirecting fd 2.638    runner_fd = CliRunner(capture="fd")639    result_fd = runner_fd.invoke(cli)640    assert "normal echo" in result_fd.output641    assert "log from stale handler" in result_fd.output642643    logger.removeHandler(handler)644645646@needs_fd_capture647def test_capture_fd_faulthandler():648    """faulthandler.enable() works with capture='fd' (issue #2865)."""649650    @click.command()651    def cli():652        faulthandler.enable()653        click.echo("after faulthandler")654655    runner = CliRunner(capture="fd")656    result = runner.invoke(cli)657    assert result.exit_code == 0658    assert "after faulthandler" in result.output659660661def test_capture_sys_fileno_raises():662    """capture='sys' leaves fileno() raising UnsupportedOperation, so user663    code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host664    runner's stdout (issue #3384).665    """666667    @click.command()668    def cli():669        with pytest.raises(io.UnsupportedOperation):670            sys.stdout.fileno()671        with pytest.raises(io.UnsupportedOperation):672            sys.stderr.fileno()673        click.echo("ok")674675    runner = CliRunner(capture="sys")676    result = runner.invoke(cli)677    assert result.exit_code == 0, result.output678    assert "ok" in result.stdout679680681@needs_fd_capture682def test_capture_fd_stderr_separation():683    """capture='fd' properly separates fd-level stdout and stderr."""684685    @click.command()686    def cli():687        click.echo("py-out")688        click.echo("py-err", err=True)689        os.write(1, b"fd-out\n")690        os.write(2, b"fd-err\n")691692    runner = CliRunner(capture="fd")693    result = runner.invoke(cli)694    assert "py-out" in result.stdout695    assert "fd-out" in result.stdout696    assert "py-err" in result.stderr697    assert "fd-err" in result.stderr698    # Mixed output has all of them699    assert "py-out" in result.output700    assert "py-err" in result.output701    assert "fd-out" in result.output702    assert "fd-err" in result.output703704705@needs_fd_capture706def test_capture_fd_nesting():707    """Nested CliRunner.invoke() with fd capture works correctly."""708709    @click.command("inner")710    def inner_cli():711        click.echo("inner")712713    @click.command("outer")714    def outer_cli():715        click.echo("outer")716        os.write(1, b"outer fd\n")717        inner_runner = CliRunner(capture="fd")718        inner_result = inner_runner.invoke(inner_cli)719        click.echo(f"inner captured: {inner_result.stdout.strip()}")720721    runner = CliRunner(capture="fd")722    result = runner.invoke(outer_cli)723    assert "outer" in result.stdout724    assert "outer fd" in result.stdout725    assert "inner captured: inner" in result.stdout726727728@needs_fd_capture729@pytest.mark.parametrize("runner_capture", ["sys", "fd"])730@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])731def test_capture_pytest_matrix(732    request: pytest.FixtureRequest,733    runner_capture: str,734    pytest_fixture: str,735) -> None:736    """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""737    pytest_cap = request.getfixturevalue(pytest_fixture)738739    @click.command()740    def cli() -> None:741        click.echo("inside-stdout")742        click.echo("inside-stderr", err=True)743744    runner = CliRunner(capture=runner_capture)745    result = runner.invoke(cli)746747    # CliRunner sees Click's output.748    assert result.exit_code == 0749    assert "inside-stdout" in result.stdout750    assert "inside-stderr" in result.stderr751752    # Pytest capture machinery is still working after invoke().753    print("post-invoke-stdout")754    print("post-invoke-stderr", file=sys.stderr)755    captured = pytest_cap.readouterr()756    assert "post-invoke-stdout" in captured.out757    assert "post-invoke-stderr" in captured.err758759    # Click output is not leaking into Pytest.760    assert "inside-stdout" not in captured.out761    assert "inside-stderr" not in captured.err