Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

521 lines · 13.4 KiB · Python

Last changed by

Allow debugger interactions in tests (#3235)Rowlando13before adoptionac2dd7a

History of this file

Take it

1import os2import pdb3import sys4from io import BytesIO56import pytest78import click9from click.exceptions import ClickException10from click.testing import CliRunner111213def test_runner():14    @click.command()15    def test():16        i = click.get_binary_stream("stdin")17        o = click.get_binary_stream("stdout")18        while True:19            chunk = i.read(4096)20            if not chunk:21                break22            o.write(chunk)23            o.flush()2425    runner = CliRunner()26    result = runner.invoke(test, input="Hello World!\n")27    assert not result.exception28    assert result.output == "Hello World!\n"293031def test_echo_stdin_stream():32    @click.command()33    def test():34        i = click.get_binary_stream("stdin")35        o = click.get_binary_stream("stdout")36        while True:37            chunk = i.read(4096)38            if not chunk:39                break40            o.write(chunk)41            o.flush()4243    runner = CliRunner(echo_stdin=True)44    result = runner.invoke(test, input="Hello World!\n")45    assert not result.exception46    assert result.output == "Hello World!\nHello World!\n"474849def test_echo_stdin_prompts():50    @click.command()51    def test_python_input():52        foo = input("Foo: ")53        click.echo(f"foo={foo}")5455    runner = CliRunner(echo_stdin=True)56    result = runner.invoke(test_python_input, input="bar bar\n")57    assert not result.exception58    assert result.output == "Foo: bar bar\nfoo=bar bar\n"5960    @click.command()61    @click.option("--foo", prompt=True)62    def test_prompt(foo):63        click.echo(f"foo={foo}")6465    result = runner.invoke(test_prompt, input="bar bar\n")66    assert not result.exception67    assert result.output == "Foo: bar bar\nfoo=bar bar\n"6869    @click.command()70    @click.option("--foo", prompt=True, hide_input=True)71    def test_hidden_prompt(foo):72        click.echo(f"foo={foo}")7374    result = runner.invoke(test_hidden_prompt, input="bar bar\n")75    assert not result.exception76    assert result.output == "Foo: \nfoo=bar bar\n"7778    @click.command()79    @click.option("--foo", prompt=True)80    @click.option("--bar", prompt=True)81    def test_multiple_prompts(foo, bar):82        click.echo(f"foo={foo}, bar={bar}")8384    result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")85    assert not result.exception86    assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"878889def test_runner_with_stream():90    @click.command()91    def test():92        i = click.get_binary_stream("stdin")93        o = click.get_binary_stream("stdout")94        while True:95            chunk = i.read(4096)96            if not chunk:97                break98            o.write(chunk)99            o.flush()100101    runner = CliRunner()102    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))103    assert not result.exception104    assert result.output == "Hello World!\n"105106    runner = CliRunner(echo_stdin=True)107    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))108    assert not result.exception109    assert result.output == "Hello World!\nHello World!\n"110111112def test_prompts():113    @click.command()114    @click.option("--foo", prompt=True)115    def test(foo):116        click.echo(f"foo={foo}")117118    runner = CliRunner()119    result = runner.invoke(test, input="wau wau\n")120    assert not result.exception121    assert result.output == "Foo: wau wau\nfoo=wau wau\n"122123    @click.command()124    @click.option("--foo", prompt=True, hide_input=True)125    def test(foo):126        click.echo(f"foo={foo}")127128    runner = CliRunner()129    result = runner.invoke(test, input="wau wau\n")130    assert not result.exception131    assert result.output == "Foo: \nfoo=wau wau\n"132133134def test_getchar():135    @click.command()136    def continue_it():137        click.echo(click.getchar())138139    runner = CliRunner()140    result = runner.invoke(continue_it, input="y")141    assert not result.exception142    assert result.output == "y\n"143144    runner = CliRunner(echo_stdin=True)145    result = runner.invoke(continue_it, input="y")146    assert not result.exception147    assert result.output == "y\n"148149    @click.command()150    def getchar_echo():151        click.echo(click.getchar(echo=True))152153    runner = CliRunner()154    result = runner.invoke(getchar_echo, input="y")155    assert not result.exception156    assert result.output == "yy\n"157158    runner = CliRunner(echo_stdin=True)159    result = runner.invoke(getchar_echo, input="y")160    assert not result.exception161    assert result.output == "yy\n"162163164def test_catch_exceptions():165    class CustomError(Exception):166        pass167168    @click.command()169    def cli():170        raise CustomError(1)171172    runner = CliRunner()173174    result = runner.invoke(cli)175    assert isinstance(result.exception, CustomError)176    assert type(result.exc_info) is tuple177    assert len(result.exc_info) == 3178179    with pytest.raises(CustomError):180        runner.invoke(cli, catch_exceptions=False)181182    CustomError = SystemExit183184    result = runner.invoke(cli)185    assert result.exit_code == 1186187188def test_catch_exceptions_cli_runner():189    """Test that invoke `catch_exceptions` takes the value from CliRunner if not set190    explicitly."""191192    class CustomError(Exception):193        pass194195    @click.command()196    def cli():197        raise CustomError(1)198199    runner = CliRunner(catch_exceptions=False)200201    result = runner.invoke(cli, catch_exceptions=True)202    assert isinstance(result.exception, CustomError)203    assert type(result.exc_info) is tuple204    assert len(result.exc_info) == 3205206    with pytest.raises(CustomError):207        runner.invoke(cli)208209210def test_with_color():211    @click.command()212    def cli():213        click.secho("hello world", fg="blue")214215    runner = CliRunner()216217    result = runner.invoke(cli)218    assert result.output == "hello world\n"219    assert not result.exception220221    result = runner.invoke(cli, color=True)222    assert result.output == f"{click.style('hello world', fg='blue')}\n"223    assert not result.exception224225226def test_with_color_errors():227    class CLIError(ClickException):228        def format_message(self) -> str:229            return click.style(self.message, fg="red")230231    @click.command()232    def cli():233        raise CLIError("Red error")234235    runner = CliRunner()236237    result = runner.invoke(cli)238    assert result.output == "Error: Red error\n"239    assert result.exception240241    result = runner.invoke(cli, color=True)242    assert result.output == f"Error: {click.style('Red error', fg='red')}\n"243    assert result.exception244245246def test_with_color_but_pause_not_blocking():247    @click.command()248    def cli():249        click.pause()250251    runner = CliRunner()252    result = runner.invoke(cli, color=True)253    assert not result.exception254    assert result.output == ""255256257def test_exit_code_and_output_from_sys_exit():258    # See issue #362259    @click.command()260    def cli_string():261        click.echo("hello world")262        sys.exit("error")263264    @click.command()265    @click.pass_context266    def cli_string_ctx_exit(ctx):267        click.echo("hello world")268        ctx.exit("error")269270    @click.command()271    def cli_int():272        click.echo("hello world")273        sys.exit(1)274275    @click.command()276    @click.pass_context277    def cli_int_ctx_exit(ctx):278        click.echo("hello world")279        ctx.exit(1)280281    @click.command()282    def cli_float():283        click.echo("hello world")284        sys.exit(1.0)285286    @click.command()287    @click.pass_context288    def cli_float_ctx_exit(ctx):289        click.echo("hello world")290        ctx.exit(1.0)291292    @click.command()293    def cli_no_error():294        click.echo("hello world")295296    runner = CliRunner()297298    result = runner.invoke(cli_string)299    assert result.exit_code == 1300    assert result.output == "hello world\nerror\n"301302    result = runner.invoke(cli_string_ctx_exit)303    assert result.exit_code == 1304    assert result.output == "hello world\nerror\n"305306    result = runner.invoke(cli_int)307    assert result.exit_code == 1308    assert result.output == "hello world\n"309310    result = runner.invoke(cli_int_ctx_exit)311    assert result.exit_code == 1312    assert result.output == "hello world\n"313314    result = runner.invoke(cli_float)315    assert result.exit_code == 1316    assert result.output == "hello world\n1.0\n"317318    result = runner.invoke(cli_float_ctx_exit)319    assert result.exit_code == 1320    assert result.output == "hello world\n1.0\n"321322    result = runner.invoke(cli_no_error)323    assert result.exit_code == 0324    assert result.output == "hello world\n"325326327def test_env():328    @click.command()329    def cli_env():330        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")331332    runner = CliRunner()333334    env_orig = dict(os.environ)335    env = dict(env_orig)336    assert "TEST_CLICK_ENV" not in env337    env["TEST_CLICK_ENV"] = "some_value"338    result = runner.invoke(cli_env, env=env)339    assert result.exit_code == 0340    assert result.output == "ENV=some_value\n"341342    assert os.environ == env_orig343344345def test_stderr():346    @click.command()347    def cli_stderr():348        click.echo("1 - stdout")349        click.echo("2 - stderr", err=True)350        click.echo("3 - stdout")351        click.echo("4 - stderr", err=True)352353    runner_mix = CliRunner()354    result_mix = runner_mix.invoke(cli_stderr)355356    assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"357    assert result_mix.stdout == "1 - stdout\n3 - stdout\n"358    assert result_mix.stderr == "2 - stderr\n4 - stderr\n"359360    @click.command()361    def cli_empty_stderr():362        click.echo("stdout")363364    runner = CliRunner()365    result = runner.invoke(cli_empty_stderr)366367    assert result.output == "stdout\n"368    assert result.stdout == "stdout\n"369    assert result.stderr == ""370371372@pytest.mark.parametrize(373    "args, expected_output",374    [375        (None, "bar\n"),376        ([], "bar\n"),377        ("", "bar\n"),378        (["--foo", "one two"], "one two\n"),379        ('--foo "one two"', "one two\n"),380    ],381)382def test_args(args, expected_output):383    @click.command()384    @click.option("--foo", default="bar")385    def cli_args(foo):386        click.echo(foo)387388    runner = CliRunner()389    result = runner.invoke(cli_args, args=args)390    assert result.exit_code == 0391    assert result.output == expected_output392393394def test_setting_prog_name_in_extra():395    @click.command()396    def cli():397        click.echo("ok")398399    runner = CliRunner()400    result = runner.invoke(cli, prog_name="foobar")401    assert not result.exception402    assert result.output == "ok\n"403404405def test_command_standalone_mode_returns_value():406    @click.command()407    def cli():408        click.echo("ok")409        return "Hello, World!"410411    runner = CliRunner()412    result = runner.invoke(cli, standalone_mode=False)413    assert result.output == "ok\n"414    assert result.return_value == "Hello, World!"415    assert result.exit_code == 0416417418def test_file_stdin_attrs(runner):419    @click.command()420    @click.argument("f", type=click.File())421    def cli(f):422        click.echo(f.name)423        click.echo(f.mode, nl=False)424425    result = runner.invoke(cli, ["-"])426    assert result.output == "<stdin>\nr"427428429def test_isolated_runner(runner):430    with runner.isolated_filesystem() as d:431        assert os.path.exists(d)432433    assert not os.path.exists(d)434435436def test_isolated_runner_custom_tempdir(runner, tmp_path):437    with runner.isolated_filesystem(temp_dir=tmp_path) as d:438        assert os.path.exists(d)439440    assert os.path.exists(d)441    os.rmdir(d)442443444def test_isolation_stderr_errors():445    """Writing to stderr should escape invalid characters instead of446    raising a UnicodeEncodeError.447    """448    runner = CliRunner()449450    with runner.isolation() as (_, err, _):451        click.echo("\udce2", err=True, nl=False)452        assert err.getvalue() == b"\\udce2"453454455def test_isolation_flushes_unflushed_stderr():456    """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up457    flushed by the runner at end of invocation.458    """459    runner = CliRunner()460461    with runner.isolation() as (_, err, _):462        click.echo("\udce2", err=True, nl=False)463        assert err.getvalue() == b"\\udce2"464465    @click.command()466    def cli():467        # set end="", flush=False so that it's totally clear that we won't get any468        # auto-flush behaviors469        print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)470471    result = runner.invoke(cli)472    assert result.stderr == "gyarados gyarados gyarados"473474475def test_pdb_uses_real_streams():476    """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams477    so that interactive debuggers work instead of reading from the478    captured ``BytesIO`` stdin.479    """480481    @click.command()482    def cli():483        debugger = pdb.Pdb()484        assert debugger.stdin is sys.__stdin__485        assert debugger.stdout is sys.__stdout__486        click.echo("after debugger")487488    runner = CliRunner()489    result = runner.invoke(cli, catch_exceptions=False)490    assert result.output == "after debugger\n"491492493def test_pdb_explicit_streams_honored():494    """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not495    overridden by the ``CliRunner`` patch.496    """497498    @click.command()499    def cli():500        custom_in = sys.stdin501        custom_out = sys.stdout502        debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)503        assert debugger.stdin is custom_in504        assert debugger.stdout is custom_out505506    runner = CliRunner()507    runner.invoke(cli, catch_exceptions=False)508509510def test_pdb_init_restored_after_invoke():511    """``pdb.Pdb.__init__`` is restored to its original after invoke."""512    original = pdb.Pdb.__init__513514    @click.command()515    def cli():516        pass517518    runner = CliRunner()519    runner.invoke(cli)520521    assert pdb.Pdb.__init__ is original