Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

749 lines · 20.6 KiB · Python

Last changed by

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

History of this file

Take 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_exit_code_and_output_from_sys_exit():260    # See issue #362261    @click.command()262    def cli_string():263        click.echo("hello world")264        sys.exit("error")265266    @click.command()267    @click.pass_context268    def cli_string_ctx_exit(ctx):269        click.echo("hello world")270        ctx.exit("error")271272    @click.command()273    def cli_int():274        click.echo("hello world")275        sys.exit(1)276277    @click.command()278    @click.pass_context279    def cli_int_ctx_exit(ctx):280        click.echo("hello world")281        ctx.exit(1)282283    @click.command()284    def cli_float():285        click.echo("hello world")286        sys.exit(1.0)287288    @click.command()289    @click.pass_context290    def cli_float_ctx_exit(ctx):291        click.echo("hello world")292        ctx.exit(1.0)293294    @click.command()295    def cli_no_error():296        click.echo("hello world")297298    runner = CliRunner()299300    result = runner.invoke(cli_string)301    assert result.exit_code == 1302    assert result.output == "hello world\nerror\n"303304    result = runner.invoke(cli_string_ctx_exit)305    assert result.exit_code == 1306    assert result.output == "hello world\nerror\n"307308    result = runner.invoke(cli_int)309    assert result.exit_code == 1310    assert result.output == "hello world\n"311312    result = runner.invoke(cli_int_ctx_exit)313    assert result.exit_code == 1314    assert result.output == "hello world\n"315316    result = runner.invoke(cli_float)317    assert result.exit_code == 1318    assert result.output == "hello world\n1.0\n"319320    result = runner.invoke(cli_float_ctx_exit)321    assert result.exit_code == 1322    assert result.output == "hello world\n1.0\n"323324    result = runner.invoke(cli_no_error)325    assert result.exit_code == 0326    assert result.output == "hello world\n"327328329def test_env():330    @click.command()331    def cli_env():332        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")333334    runner = CliRunner()335336    env_orig = dict(os.environ)337    env = dict(env_orig)338    assert "TEST_CLICK_ENV" not in env339    env["TEST_CLICK_ENV"] = "some_value"340    result = runner.invoke(cli_env, env=env)341    assert result.exit_code == 0342    assert result.output == "ENV=some_value\n"343344    assert os.environ == env_orig345346347def test_stderr():348    @click.command()349    def cli_stderr():350        click.echo("1 - stdout")351        click.echo("2 - stderr", err=True)352        click.echo("3 - stdout")353        click.echo("4 - stderr", err=True)354355    runner_mix = CliRunner()356    result_mix = runner_mix.invoke(cli_stderr)357358    assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"359    assert result_mix.stdout == "1 - stdout\n3 - stdout\n"360    assert result_mix.stderr == "2 - stderr\n4 - stderr\n"361362    @click.command()363    def cli_empty_stderr():364        click.echo("stdout")365366    runner = CliRunner()367    result = runner.invoke(cli_empty_stderr)368369    assert result.output == "stdout\n"370    assert result.stdout == "stdout\n"371    assert result.stderr == ""372373374@pytest.mark.parametrize(375    "args, expected_output",376    [377        (None, "bar\n"),378        ([], "bar\n"),379        ("", "bar\n"),380        (["--foo", "one two"], "one two\n"),381        ('--foo "one two"', "one two\n"),382    ],383)384def test_args(args, expected_output):385    @click.command()386    @click.option("--foo", default="bar")387    def cli_args(foo):388        click.echo(foo)389390    runner = CliRunner()391    result = runner.invoke(cli_args, args=args)392    assert result.exit_code == 0393    assert result.output == expected_output394395396def test_setting_prog_name_in_extra():397    @click.command()398    def cli():399        click.echo("ok")400401    runner = CliRunner()402    result = runner.invoke(cli, prog_name="foobar")403    assert not result.exception404    assert result.output == "ok\n"405406407def test_command_standalone_mode_returns_value():408    @click.command()409    def cli():410        click.echo("ok")411        return "Hello, World!"412413    runner = CliRunner()414    result = runner.invoke(cli, standalone_mode=False)415    assert result.output == "ok\n"416    assert result.return_value == "Hello, World!"417    assert result.exit_code == 0418419420def test_file_stdin_attrs(runner):421    @click.command()422    @click.argument("f", type=click.File())423    def cli(f):424        click.echo(f.name)425        click.echo(f.mode, nl=False)426427    result = runner.invoke(cli, ["-"])428    assert result.output == "<stdin>\nr"429430431def test_isolated_runner(runner):432    with runner.isolated_filesystem() as d:433        assert os.path.exists(d)434435    assert not os.path.exists(d)436437438def test_isolated_runner_custom_tempdir(runner, tmp_path):439    with runner.isolated_filesystem(temp_dir=tmp_path) as d:440        assert os.path.exists(d)441442    assert os.path.exists(d)443    os.rmdir(d)444445446def test_isolation_stderr_errors():447    """Writing to stderr should escape invalid characters instead of448    raising a UnicodeEncodeError.449    """450    runner = CliRunner()451452    with runner.isolation() as (_, err, _):453        click.echo("\udce2", err=True, nl=False)454        assert err.getvalue() == b"\\udce2"455456457def test_isolation_flushes_unflushed_stderr():458    """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up459    flushed by the runner at end of invocation.460    """461    runner = CliRunner()462463    with runner.isolation() as (_, err, _):464        click.echo("\udce2", err=True, nl=False)465        assert err.getvalue() == b"\\udce2"466467    @click.command()468    def cli():469        # set end="", flush=False so that it's totally clear that we won't get any470        # auto-flush behaviors471        print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)472473    result = runner.invoke(cli)474    assert result.stderr == "gyarados gyarados gyarados"475476477def test_pdb_uses_real_streams():478    """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams479    so that interactive debuggers work instead of reading from the480    captured ``BytesIO`` stdin.481    """482483    @click.command()484    def cli():485        debugger = pdb.Pdb()486        assert debugger.stdin is sys.__stdin__487        assert debugger.stdout is sys.__stdout__488        click.echo("after debugger")489490    runner = CliRunner()491    result = runner.invoke(cli, catch_exceptions=False)492    assert result.output == "after debugger\n"493494495def test_pdb_explicit_streams_honored():496    """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not497    overridden by the ``CliRunner`` patch.498    """499500    @click.command()501    def cli():502        custom_in = sys.stdin503        custom_out = sys.stdout504        debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)505        assert debugger.stdin is custom_in506        assert debugger.stdout is custom_out507508    runner = CliRunner()509    runner.invoke(cli, catch_exceptions=False)510511512def test_pdb_init_restored_after_invoke():513    """``pdb.Pdb.__init__`` is restored to its original after invoke."""514    original = pdb.Pdb.__init__515516    @click.command()517    def cli():518        pass519520    runner = CliRunner()521    runner.invoke(cli)522523    assert pdb.Pdb.__init__ is original524525526needs_fd_capture = pytest.mark.skipif(527    sys.platform == "win32",528    reason="fd capture not supported on Windows",529)530531532def test_capture_invalid_mode():533    """Invalid capture mode raises ValueError."""534    with pytest.raises(ValueError, match="capture"):535        CliRunner(capture="invalid")  # type: ignore[arg-type]536537538@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")539def test_capture_fd_windows_error():540    """fd capture raises ValueError on Windows."""541    with pytest.raises(ValueError, match="not supported on Windows"):542        CliRunner(capture="fd")543544545@needs_fd_capture546def test_capture_fd_os_write():547    """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""548549    @click.command()550    def cli():551        click.echo("python stdout")552        os.write(1, b"fd stdout\n")553        os.write(2, b"fd stderr\n")554555    runner = CliRunner(capture="fd")556    result = runner.invoke(cli)557    assert "python stdout" in result.stdout558    assert "fd stdout" in result.stdout559    assert "fd stderr" in result.stderr560561562@needs_fd_capture563def test_capture_fd_stale_reference():564    """capture='fd' captures writes from stale stdout references (issue #2874).565566    Simulates ``from sys import stdout`` at import time, which grabs567    the real stdout connected to fd 1.  The stale object's underlying568    FileIO uses fd 1, so redirecting fd 1 captures its writes.569    """570    # open(1, ..., closefd=False) creates a writer whose underlying571    # FileIO uses fd 1 directly. This mirrors the real scenario:572    # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->573    # FileIO(fd=1).574    stale_stdout = open(1, "w", closefd=False)  # noqa: SIM115575576    @click.command()577    def cli():578        stale_stdout.write("stale write\n")579        stale_stdout.flush()580        click.echo("normal write")581582    runner = CliRunner(capture="fd")583    result = runner.invoke(cli)584    assert "normal write" in result.stdout585    assert "stale write" in result.stdout586587588@needs_fd_capture589def test_capture_fd_logging_handler(tmp_path):590    """capture='fd' captures logging output from a handler holding a stale591    stderr reference (issue #2827).592593    stdlib logging.StreamHandler grabs sys.stderr at configuration time.594    Under normal CliRunner (sys-level capture), the handler still writes595    to the original stream object and output is lost. fd-level capture596    redirects the underlying file descriptor, so the writes are captured.597    """598    import logging599600    # Create a writer backed by the real fd 2, simulating a handler601    # configured at import time before pytest or CliRunner replaced602    # sys.stderr. open(2, closefd=False) mirrors the real scenario:603    # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->604    # FileIO(fd=2).605    stale_stderr = open(2, "w", closefd=False)  # noqa: SIM115606    handler = logging.StreamHandler(stale_stderr)607    handler.setFormatter(logging.Formatter("%(message)s"))608609    logger = logging.getLogger(f"click_test_{tmp_path.name}")610    logger.addHandler(handler)611    logger.setLevel(logging.INFO)612    logger.propagate = False613614    @click.command()615    def cli():616        logger.info("log from stale handler")617        click.echo("normal echo")618619    # sys-level capture misses the log line (it bypasses sys.stderr).620    runner_sys = CliRunner(capture="sys")621    result_sys = runner_sys.invoke(cli)622    assert "normal echo" in result_sys.output623    assert "log from stale handler" not in result_sys.output624625    # fd-level capture catches it by redirecting fd 2.626    runner_fd = CliRunner(capture="fd")627    result_fd = runner_fd.invoke(cli)628    assert "normal echo" in result_fd.output629    assert "log from stale handler" in result_fd.output630631    logger.removeHandler(handler)632633634@needs_fd_capture635def test_capture_fd_faulthandler():636    """faulthandler.enable() works with capture='fd' (issue #2865)."""637638    @click.command()639    def cli():640        faulthandler.enable()641        click.echo("after faulthandler")642643    runner = CliRunner(capture="fd")644    result = runner.invoke(cli)645    assert result.exit_code == 0646    assert "after faulthandler" in result.output647648649def test_capture_sys_fileno_raises():650    """capture='sys' leaves fileno() raising UnsupportedOperation, so user651    code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host652    runner's stdout (issue #3384).653    """654655    @click.command()656    def cli():657        with pytest.raises(io.UnsupportedOperation):658            sys.stdout.fileno()659        with pytest.raises(io.UnsupportedOperation):660            sys.stderr.fileno()661        click.echo("ok")662663    runner = CliRunner(capture="sys")664    result = runner.invoke(cli)665    assert result.exit_code == 0, result.output666    assert "ok" in result.stdout667668669@needs_fd_capture670def test_capture_fd_stderr_separation():671    """capture='fd' properly separates fd-level stdout and stderr."""672673    @click.command()674    def cli():675        click.echo("py-out")676        click.echo("py-err", err=True)677        os.write(1, b"fd-out\n")678        os.write(2, b"fd-err\n")679680    runner = CliRunner(capture="fd")681    result = runner.invoke(cli)682    assert "py-out" in result.stdout683    assert "fd-out" in result.stdout684    assert "py-err" in result.stderr685    assert "fd-err" in result.stderr686    # Mixed output has all of them687    assert "py-out" in result.output688    assert "py-err" in result.output689    assert "fd-out" in result.output690    assert "fd-err" in result.output691692693@needs_fd_capture694def test_capture_fd_nesting():695    """Nested CliRunner.invoke() with fd capture works correctly."""696697    @click.command("inner")698    def inner_cli():699        click.echo("inner")700701    @click.command("outer")702    def outer_cli():703        click.echo("outer")704        os.write(1, b"outer fd\n")705        inner_runner = CliRunner(capture="fd")706        inner_result = inner_runner.invoke(inner_cli)707        click.echo(f"inner captured: {inner_result.stdout.strip()}")708709    runner = CliRunner(capture="fd")710    result = runner.invoke(outer_cli)711    assert "outer" in result.stdout712    assert "outer fd" in result.stdout713    assert "inner captured: inner" in result.stdout714715716@needs_fd_capture717@pytest.mark.parametrize("runner_capture", ["sys", "fd"])718@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])719def test_capture_pytest_matrix(720    request: pytest.FixtureRequest,721    runner_capture: str,722    pytest_fixture: str,723) -> None:724    """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""725    pytest_cap = request.getfixturevalue(pytest_fixture)726727    @click.command()728    def cli() -> None:729        click.echo("inside-stdout")730        click.echo("inside-stderr", err=True)731732    runner = CliRunner(capture=runner_capture)733    result = runner.invoke(cli)734735    # CliRunner sees Click's output.736    assert result.exit_code == 0737    assert "inside-stdout" in result.stdout738    assert "inside-stderr" in result.stderr739740    # Pytest capture machinery is still working after invoke().741    print("post-invoke-stdout")742    print("post-invoke-stderr", file=sys.stderr)743    captured = pytest_cap.readouterr()744    assert "post-invoke-stdout" in captured.out745    assert "post-invoke-stderr" in captured.err746747    # Click output is not leaking into Pytest.748    assert "inside-stdout" not in captured.out749    assert "inside-stderr" not in captured.err