Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

439 lines · 11.0 KiB · Python

Last changed by

Pass 'color' explicitly in error echoing (#2273)Dan Ziringbefore adoption8c842a4

History of this file

Take it

1import os2import sys3from io import BytesIO45import pytest67import click8from click.exceptions import ClickException9from click.testing import CliRunner101112def test_runner():13    @click.command()14    def test():15        i = click.get_binary_stream("stdin")16        o = click.get_binary_stream("stdout")17        while True:18            chunk = i.read(4096)19            if not chunk:20                break21            o.write(chunk)22            o.flush()2324    runner = CliRunner()25    result = runner.invoke(test, input="Hello World!\n")26    assert not result.exception27    assert result.output == "Hello World!\n"282930def test_echo_stdin_stream():31    @click.command()32    def test():33        i = click.get_binary_stream("stdin")34        o = click.get_binary_stream("stdout")35        while True:36            chunk = i.read(4096)37            if not chunk:38                break39            o.write(chunk)40            o.flush()4142    runner = CliRunner(echo_stdin=True)43    result = runner.invoke(test, input="Hello World!\n")44    assert not result.exception45    assert result.output == "Hello World!\nHello World!\n"464748def test_echo_stdin_prompts():49    @click.command()50    def test_python_input():51        foo = input("Foo: ")52        click.echo(f"foo={foo}")5354    runner = CliRunner(echo_stdin=True)55    result = runner.invoke(test_python_input, input="bar bar\n")56    assert not result.exception57    assert result.output == "Foo: bar bar\nfoo=bar bar\n"5859    @click.command()60    @click.option("--foo", prompt=True)61    def test_prompt(foo):62        click.echo(f"foo={foo}")6364    result = runner.invoke(test_prompt, input="bar bar\n")65    assert not result.exception66    assert result.output == "Foo: bar bar\nfoo=bar bar\n"6768    @click.command()69    @click.option("--foo", prompt=True, hide_input=True)70    def test_hidden_prompt(foo):71        click.echo(f"foo={foo}")7273    result = runner.invoke(test_hidden_prompt, input="bar bar\n")74    assert not result.exception75    assert result.output == "Foo: \nfoo=bar bar\n"7677    @click.command()78    @click.option("--foo", prompt=True)79    @click.option("--bar", prompt=True)80    def test_multiple_prompts(foo, bar):81        click.echo(f"foo={foo}, bar={bar}")8283    result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")84    assert not result.exception85    assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"868788def test_runner_with_stream():89    @click.command()90    def test():91        i = click.get_binary_stream("stdin")92        o = click.get_binary_stream("stdout")93        while True:94            chunk = i.read(4096)95            if not chunk:96                break97            o.write(chunk)98            o.flush()99100    runner = CliRunner()101    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))102    assert not result.exception103    assert result.output == "Hello World!\n"104105    runner = CliRunner(echo_stdin=True)106    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))107    assert not result.exception108    assert result.output == "Hello World!\nHello World!\n"109110111def test_prompts():112    @click.command()113    @click.option("--foo", prompt=True)114    def test(foo):115        click.echo(f"foo={foo}")116117    runner = CliRunner()118    result = runner.invoke(test, input="wau wau\n")119    assert not result.exception120    assert result.output == "Foo: wau wau\nfoo=wau wau\n"121122    @click.command()123    @click.option("--foo", prompt=True, hide_input=True)124    def test(foo):125        click.echo(f"foo={foo}")126127    runner = CliRunner()128    result = runner.invoke(test, input="wau wau\n")129    assert not result.exception130    assert result.output == "Foo: \nfoo=wau wau\n"131132133def test_getchar():134    @click.command()135    def continue_it():136        click.echo(click.getchar())137138    runner = CliRunner()139    result = runner.invoke(continue_it, input="y")140    assert not result.exception141    assert result.output == "y\n"142143    runner = CliRunner(echo_stdin=True)144    result = runner.invoke(continue_it, input="y")145    assert not result.exception146    assert result.output == "y\n"147148    @click.command()149    def getchar_echo():150        click.echo(click.getchar(echo=True))151152    runner = CliRunner()153    result = runner.invoke(getchar_echo, input="y")154    assert not result.exception155    assert result.output == "yy\n"156157    runner = CliRunner(echo_stdin=True)158    result = runner.invoke(getchar_echo, input="y")159    assert not result.exception160    assert result.output == "yy\n"161162163def test_catch_exceptions():164    class CustomError(Exception):165        pass166167    @click.command()168    def cli():169        raise CustomError(1)170171    runner = CliRunner()172173    result = runner.invoke(cli)174    assert isinstance(result.exception, CustomError)175    assert type(result.exc_info) is tuple176    assert len(result.exc_info) == 3177178    with pytest.raises(CustomError):179        runner.invoke(cli, catch_exceptions=False)180181    CustomError = SystemExit182183    result = runner.invoke(cli)184    assert result.exit_code == 1185186187def test_with_color():188    @click.command()189    def cli():190        click.secho("hello world", fg="blue")191192    runner = CliRunner()193194    result = runner.invoke(cli)195    assert result.output == "hello world\n"196    assert not result.exception197198    result = runner.invoke(cli, color=True)199    assert result.output == f"{click.style('hello world', fg='blue')}\n"200    assert not result.exception201202203def test_with_color_errors():204    class CLIError(ClickException):205        def format_message(self) -> str:206            return click.style(self.message, fg="red")207208    @click.command()209    def cli():210        raise CLIError("Red error")211212    runner = CliRunner()213214    result = runner.invoke(cli)215    assert result.output == "Error: Red error\n"216    assert result.exception217218    result = runner.invoke(cli, color=True)219    assert result.output == f"Error: {click.style('Red error', fg='red')}\n"220    assert result.exception221222223def test_with_color_but_pause_not_blocking():224    @click.command()225    def cli():226        click.pause()227228    runner = CliRunner()229    result = runner.invoke(cli, color=True)230    assert not result.exception231    assert result.output == ""232233234def test_exit_code_and_output_from_sys_exit():235    # See issue #362236    @click.command()237    def cli_string():238        click.echo("hello world")239        sys.exit("error")240241    @click.command()242    @click.pass_context243    def cli_string_ctx_exit(ctx):244        click.echo("hello world")245        ctx.exit("error")246247    @click.command()248    def cli_int():249        click.echo("hello world")250        sys.exit(1)251252    @click.command()253    @click.pass_context254    def cli_int_ctx_exit(ctx):255        click.echo("hello world")256        ctx.exit(1)257258    @click.command()259    def cli_float():260        click.echo("hello world")261        sys.exit(1.0)262263    @click.command()264    @click.pass_context265    def cli_float_ctx_exit(ctx):266        click.echo("hello world")267        ctx.exit(1.0)268269    @click.command()270    def cli_no_error():271        click.echo("hello world")272273    runner = CliRunner()274275    result = runner.invoke(cli_string)276    assert result.exit_code == 1277    assert result.output == "hello world\nerror\n"278279    result = runner.invoke(cli_string_ctx_exit)280    assert result.exit_code == 1281    assert result.output == "hello world\nerror\n"282283    result = runner.invoke(cli_int)284    assert result.exit_code == 1285    assert result.output == "hello world\n"286287    result = runner.invoke(cli_int_ctx_exit)288    assert result.exit_code == 1289    assert result.output == "hello world\n"290291    result = runner.invoke(cli_float)292    assert result.exit_code == 1293    assert result.output == "hello world\n1.0\n"294295    result = runner.invoke(cli_float_ctx_exit)296    assert result.exit_code == 1297    assert result.output == "hello world\n1.0\n"298299    result = runner.invoke(cli_no_error)300    assert result.exit_code == 0301    assert result.output == "hello world\n"302303304def test_env():305    @click.command()306    def cli_env():307        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")308309    runner = CliRunner()310311    env_orig = dict(os.environ)312    env = dict(env_orig)313    assert "TEST_CLICK_ENV" not in env314    env["TEST_CLICK_ENV"] = "some_value"315    result = runner.invoke(cli_env, env=env)316    assert result.exit_code == 0317    assert result.output == "ENV=some_value\n"318319    assert os.environ == env_orig320321322def test_stderr():323    @click.command()324    def cli_stderr():325        click.echo("stdout")326        click.echo("stderr", err=True)327328    runner = CliRunner(mix_stderr=False)329330    result = runner.invoke(cli_stderr)331332    assert result.output == "stdout\n"333    assert result.stdout == "stdout\n"334    assert result.stderr == "stderr\n"335336    runner_mix = CliRunner(mix_stderr=True)337    result_mix = runner_mix.invoke(cli_stderr)338339    assert result_mix.output == "stdout\nstderr\n"340    assert result_mix.stdout == "stdout\nstderr\n"341342    with pytest.raises(ValueError):343        result_mix.stderr  # noqa B018344345    @click.command()346    def cli_empty_stderr():347        click.echo("stdout")348349    runner = CliRunner(mix_stderr=False)350351    result = runner.invoke(cli_empty_stderr)352353    assert result.output == "stdout\n"354    assert result.stdout == "stdout\n"355    assert result.stderr == ""356357358@pytest.mark.parametrize(359    "args, expected_output",360    [361        (None, "bar\n"),362        ([], "bar\n"),363        ("", "bar\n"),364        (["--foo", "one two"], "one two\n"),365        ('--foo "one two"', "one two\n"),366    ],367)368def test_args(args, expected_output):369    @click.command()370    @click.option("--foo", default="bar")371    def cli_args(foo):372        click.echo(foo)373374    runner = CliRunner()375    result = runner.invoke(cli_args, args=args)376    assert result.exit_code == 0377    assert result.output == expected_output378379380def test_setting_prog_name_in_extra():381    @click.command()382    def cli():383        click.echo("ok")384385    runner = CliRunner()386    result = runner.invoke(cli, prog_name="foobar")387    assert not result.exception388    assert result.output == "ok\n"389390391def test_command_standalone_mode_returns_value():392    @click.command()393    def cli():394        click.echo("ok")395        return "Hello, World!"396397    runner = CliRunner()398    result = runner.invoke(cli, standalone_mode=False)399    assert result.output == "ok\n"400    assert result.return_value == "Hello, World!"401    assert result.exit_code == 0402403404def test_file_stdin_attrs(runner):405    @click.command()406    @click.argument("f", type=click.File())407    def cli(f):408        click.echo(f.name)409        click.echo(f.mode, nl=False)410411    result = runner.invoke(cli, ["-"])412    assert result.output == "<stdin>\nr"413414415def test_isolated_runner(runner):416    with runner.isolated_filesystem() as d:417        assert os.path.exists(d)418419    assert not os.path.exists(d)420421422def test_isolated_runner_custom_tempdir(runner, tmp_path):423    with runner.isolated_filesystem(temp_dir=tmp_path) as d:424        assert os.path.exists(d)425426    assert os.path.exists(d)427    os.rmdir(d)428429430def test_isolation_stderr_errors():431    """Writing to stderr should escape invalid characters instead of432    raising a UnicodeEncodeError.433    """434    runner = CliRunner(mix_stderr=False)435436    with runner.isolation() as (_, err):437        click.echo("\udce2", err=True, nl=False)438439    assert err.getvalue() == b"\\udce2"