Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

310 lines · 7.5 KiB · Python

Last changed by

Merge pull request #1312 from tom-dalton-fanduel/allow-testing-command-result-captureDavid Lordbefore adoption990ca8e

History of this file

Take it

1import os2import sys3from io import BytesIO45import pytest67import click8from click._compat import WIN9from 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 1: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"2829    runner = CliRunner(echo_stdin=True)30    result = runner.invoke(test, input="Hello World!\n")31    assert not result.exception32    assert result.output == "Hello World!\nHello World!\n"333435def test_runner_with_stream():36    @click.command()37    def test():38        i = click.get_binary_stream("stdin")39        o = click.get_binary_stream("stdout")40        while 1:41            chunk = i.read(4096)42            if not chunk:43                break44            o.write(chunk)45            o.flush()4647    runner = CliRunner()48    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))49    assert not result.exception50    assert result.output == "Hello World!\n"5152    runner = CliRunner(echo_stdin=True)53    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))54    assert not result.exception55    assert result.output == "Hello World!\nHello World!\n"565758def test_prompts():59    @click.command()60    @click.option("--foo", prompt=True)61    def test(foo):62        click.echo(f"foo={foo}")6364    runner = CliRunner()65    result = runner.invoke(test, input="wau wau\n")66    assert not result.exception67    assert result.output == "Foo: wau wau\nfoo=wau wau\n"6869    @click.command()70    @click.option("--foo", prompt=True, hide_input=True)71    def test(foo):72        click.echo(f"foo={foo}")7374    runner = CliRunner()75    result = runner.invoke(test, input="wau wau\n")76    assert not result.exception77    assert result.output == "Foo: \nfoo=wau wau\n"787980def test_getchar():81    @click.command()82    def continue_it():83        click.echo(click.getchar())8485    runner = CliRunner()86    result = runner.invoke(continue_it, input="y")87    assert not result.exception88    assert result.output == "y\n"899091def test_catch_exceptions():92    class CustomError(Exception):93        pass9495    @click.command()96    def cli():97        raise CustomError(1)9899    runner = CliRunner()100101    result = runner.invoke(cli)102    assert isinstance(result.exception, CustomError)103    assert type(result.exc_info) is tuple104    assert len(result.exc_info) == 3105106    with pytest.raises(CustomError):107        runner.invoke(cli, catch_exceptions=False)108109    CustomError = SystemExit110111    result = runner.invoke(cli)112    assert result.exit_code == 1113114115@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")116def test_with_color():117    @click.command()118    def cli():119        click.secho("hello world", fg="blue")120121    runner = CliRunner()122123    result = runner.invoke(cli)124    assert result.output == "hello world\n"125    assert not result.exception126127    result = runner.invoke(cli, color=True)128    assert result.output == f"{click.style('hello world', fg='blue')}\n"129    assert not result.exception130131132def test_with_color_but_pause_not_blocking():133    @click.command()134    def cli():135        click.pause()136137    runner = CliRunner()138    result = runner.invoke(cli, color=True)139    assert not result.exception140    assert result.output == ""141142143def test_exit_code_and_output_from_sys_exit():144    # See issue #362145    @click.command()146    def cli_string():147        click.echo("hello world")148        sys.exit("error")149150    @click.command()151    @click.pass_context152    def cli_string_ctx_exit(ctx):153        click.echo("hello world")154        ctx.exit("error")155156    @click.command()157    def cli_int():158        click.echo("hello world")159        sys.exit(1)160161    @click.command()162    @click.pass_context163    def cli_int_ctx_exit(ctx):164        click.echo("hello world")165        ctx.exit(1)166167    @click.command()168    def cli_float():169        click.echo("hello world")170        sys.exit(1.0)171172    @click.command()173    @click.pass_context174    def cli_float_ctx_exit(ctx):175        click.echo("hello world")176        ctx.exit(1.0)177178    @click.command()179    def cli_no_error():180        click.echo("hello world")181182    runner = CliRunner()183184    result = runner.invoke(cli_string)185    assert result.exit_code == 1186    assert result.output == "hello world\nerror\n"187188    result = runner.invoke(cli_string_ctx_exit)189    assert result.exit_code == 1190    assert result.output == "hello world\nerror\n"191192    result = runner.invoke(cli_int)193    assert result.exit_code == 1194    assert result.output == "hello world\n"195196    result = runner.invoke(cli_int_ctx_exit)197    assert result.exit_code == 1198    assert result.output == "hello world\n"199200    result = runner.invoke(cli_float)201    assert result.exit_code == 1202    assert result.output == "hello world\n1.0\n"203204    result = runner.invoke(cli_float_ctx_exit)205    assert result.exit_code == 1206    assert result.output == "hello world\n1.0\n"207208    result = runner.invoke(cli_no_error)209    assert result.exit_code == 0210    assert result.output == "hello world\n"211212213def test_env():214    @click.command()215    def cli_env():216        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")217218    runner = CliRunner()219220    env_orig = dict(os.environ)221    env = dict(env_orig)222    assert "TEST_CLICK_ENV" not in env223    env["TEST_CLICK_ENV"] = "some_value"224    result = runner.invoke(cli_env, env=env)225    assert result.exit_code == 0226    assert result.output == "ENV=some_value\n"227228    assert os.environ == env_orig229230231def test_stderr():232    @click.command()233    def cli_stderr():234        click.echo("stdout")235        click.echo("stderr", err=True)236237    runner = CliRunner(mix_stderr=False)238239    result = runner.invoke(cli_stderr)240241    assert result.output == "stdout\n"242    assert result.stdout == "stdout\n"243    assert result.stderr == "stderr\n"244245    runner_mix = CliRunner(mix_stderr=True)246    result_mix = runner_mix.invoke(cli_stderr)247248    assert result_mix.output == "stdout\nstderr\n"249    assert result_mix.stdout == "stdout\nstderr\n"250251    with pytest.raises(ValueError):252        result_mix.stderr253254    @click.command()255    def cli_empty_stderr():256        click.echo("stdout")257258    runner = CliRunner(mix_stderr=False)259260    result = runner.invoke(cli_empty_stderr)261262    assert result.output == "stdout\n"263    assert result.stdout == "stdout\n"264    assert result.stderr == ""265266267@pytest.mark.parametrize(268    "args, expected_output",269    [270        (None, "bar\n"),271        ([], "bar\n"),272        ("", "bar\n"),273        (["--foo", "one two"], "one two\n"),274        ('--foo "one two"', "one two\n"),275    ],276)277def test_args(args, expected_output):278    @click.command()279    @click.option("--foo", default="bar")280    def cli_args(foo):281        click.echo(foo)282283    runner = CliRunner()284    result = runner.invoke(cli_args, args=args)285    assert result.exit_code == 0286    assert result.output == expected_output287288289def test_setting_prog_name_in_extra():290    @click.command()291    def cli():292        click.echo("ok")293294    runner = CliRunner()295    result = runner.invoke(cli, prog_name="foobar")296    assert not result.exception297    assert result.output == "ok\n"298299300def test_command_standalone_mode_returns_value():301    @click.command()302    def cli():303        click.echo("ok")304        return "Hello, World!"305306    runner = CliRunner()307    result = runner.invoke(cli, standalone_mode=False)308    assert result.output == "ok\n"309    assert result.return_value == "Hello, World!"310    assert result.exit_code == 0