Skip to content
Myr

test_arguments.py

This file

Path

tests/test_arguments.py

379 lines · 10.3 KiB · Python

Last changed by

Merge branch '8.0.x'David Lordbefore adoption29df879

History of this file

Take it

1import sys23import pytest45import click678def test_nargs_star(runner):9    @click.command()10    @click.argument("src", nargs=-1)11    @click.argument("dst")12    def copy(src, dst):13        click.echo(f"src={'|'.join(src)}")14        click.echo(f"dst={dst}")1516    result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])17    assert not result.exception18    assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]192021def test_argument_unbounded_nargs_cant_have_default(runner):22    with pytest.raises(TypeError, match="nargs=-1"):2324        @click.command()25        @click.argument("src", nargs=-1, default=["42"])26        def copy(src):27            pass282930def test_nargs_tup(runner):31    @click.command()32    @click.argument("name", nargs=1)33    @click.argument("point", nargs=2, type=click.INT)34    def copy(name, point):35        click.echo(f"name={name}")36        x, y = point37        click.echo(f"point={x}/{y}")3839    result = runner.invoke(copy, ["peter", "1", "2"])40    assert not result.exception41    assert result.output.splitlines() == ["name=peter", "point=1/2"]424344def test_nargs_tup_composite(runner):45    variations = [46        dict(type=(str, int)),47        dict(type=click.Tuple([str, int])),48        dict(nargs=2, type=click.Tuple([str, int])),49        dict(nargs=2, type=(str, int)),50    ]5152    for opts in variations:5354        @click.command()55        @click.argument("item", **opts)56        def copy(item):57            name, id = item58            click.echo(f"name={name} id={id:d}")5960        result = runner.invoke(copy, ["peter", "1"])61        assert not result.exception62        assert result.output.splitlines() == ["name=peter id=1"]636465def test_nargs_err(runner):66    @click.command()67    @click.argument("x")68    def copy(x):69        click.echo(x)7071    result = runner.invoke(copy, ["foo"])72    assert not result.exception73    assert result.output == "foo\n"7475    result = runner.invoke(copy, ["foo", "bar"])76    assert result.exit_code == 277    assert "Got unexpected extra argument (bar)" in result.output787980def test_bytes_args(runner, monkeypatch):81    @click.command()82    @click.argument("arg")83    def from_bytes(arg):84        assert isinstance(85            arg, str86        ), "UTF-8 encoded argument should be implicitly converted to Unicode"8788    # Simulate empty locale environment variables89    monkeypatch.setattr(sys.stdin, "encoding", "utf-8")90    monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")91    monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")9293    runner.invoke(94        from_bytes,95        ["Something outside of ASCII range: 林".encode()],96        catch_exceptions=False,97    )9899100def test_file_args(runner):101    @click.command()102    @click.argument("input", type=click.File("rb"))103    @click.argument("output", type=click.File("wb"))104    def inout(input, output):105        while True:106            chunk = input.read(1024)107            if not chunk:108                break109            output.write(chunk)110111    with runner.isolated_filesystem():112        result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")113        assert result.output == ""114        assert result.exit_code == 0115        with open("hello.txt", "rb") as f:116            assert f.read() == b"Hey!"117118        result = runner.invoke(inout, ["hello.txt", "-"])119        assert result.output == "Hey!"120        assert result.exit_code == 0121122123def test_path_args(runner):124    @click.command()125    @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True))126    def foo(input):127        click.echo(input)128129    result = runner.invoke(foo, ["-"])130    assert result.output == "-\n"131    assert result.exit_code == 0132133134def test_file_atomics(runner):135    @click.command()136    @click.argument("output", type=click.File("wb", atomic=True))137    def inout(output):138        output.write(b"Foo bar baz\n")139        output.flush()140        with open(output.name, "rb") as f:141            old_content = f.read()142            assert old_content == b"OLD\n"143144    with runner.isolated_filesystem():145        with open("foo.txt", "wb") as f:146            f.write(b"OLD\n")147        result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)148        assert result.output == ""149        assert result.exit_code == 0150        with open("foo.txt", "rb") as f:151            assert f.read() == b"Foo bar baz\n"152153154def test_stdout_default(runner):155    @click.command()156    @click.argument("output", type=click.File("w"), default="-")157    def inout(output):158        output.write("Foo bar baz\n")159        output.flush()160161    result = runner.invoke(inout, [])162    assert not result.exception163    assert result.output == "Foo bar baz\n"164165166@pytest.mark.parametrize(167    ("nargs", "value", "expect"),168    [169        (2, "", None),170        (2, "a", "Takes 2 values but 1 was given."),171        (2, "a b", ("a", "b")),172        (2, "a b c", "Takes 2 values but 3 were given."),173        (-1, "a b c", ("a", "b", "c")),174        (-1, "", ()),175    ],176)177def test_nargs_envvar(runner, nargs, value, expect):178    if nargs == -1:179        param = click.argument("arg", envvar="X", nargs=nargs)180    else:181        param = click.option("--arg", envvar="X", nargs=nargs)182183    @click.command()184    @param185    def cmd(arg):186        return arg187188    result = runner.invoke(cmd, env={"X": value}, standalone_mode=False)189190    if isinstance(expect, str):191        assert isinstance(result.exception, click.BadParameter)192        assert expect in result.exception.format_message()193    else:194        assert result.return_value == expect195196197def test_nargs_envvar_only_if_values_empty(runner):198    @click.command()199    @click.argument("arg", envvar="X", nargs=-1)200    def cli(arg):201        return arg202203    result = runner.invoke(cli, ["a", "b"], standalone_mode=False)204    assert result.return_value == ("a", "b")205206    result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False)207    assert result.return_value == ("a",)208209210def test_empty_nargs(runner):211    @click.command()212    @click.argument("arg", nargs=-1)213    def cmd(arg):214        click.echo(f"arg:{'|'.join(arg)}")215216    result = runner.invoke(cmd, [])217    assert result.exit_code == 0218    assert result.output == "arg:\n"219220    @click.command()221    @click.argument("arg", nargs=-1, required=True)222    def cmd2(arg):223        click.echo(f"arg:{'|'.join(arg)}")224225    result = runner.invoke(cmd2, [])226    assert result.exit_code == 2227    assert "Missing argument 'ARG...'" in result.output228229230def test_missing_arg(runner):231    @click.command()232    @click.argument("arg")233    def cmd(arg):234        click.echo(f"arg:{arg}")235236    result = runner.invoke(cmd, [])237    assert result.exit_code == 2238    assert "Missing argument 'ARG'." in result.output239240241def test_missing_argument_string_cast():242    ctx = click.Context(click.Command(""))243244    with pytest.raises(click.MissingParameter) as excinfo:245        click.Argument(["a"], required=True).process_value(ctx, None)246247    assert str(excinfo.value) == "Missing parameter: a"248249250def test_implicit_non_required(runner):251    @click.command()252    @click.argument("f", default="test")253    def cli(f):254        click.echo(f)255256    result = runner.invoke(cli, [])257    assert result.exit_code == 0258    assert result.output == "test\n"259260261def test_eat_options(runner):262    @click.command()263    @click.option("-f")264    @click.argument("files", nargs=-1)265    def cmd(f, files):266        for filename in files:267            click.echo(filename)268        click.echo(f)269270    result = runner.invoke(cmd, ["--", "-foo", "bar"])271    assert result.output.splitlines() == ["-foo", "bar", ""]272273    result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])274    assert result.output.splitlines() == ["-foo", "bar", "-x"]275276277def test_nargs_star_ordering(runner):278    @click.command()279    @click.argument("a", nargs=-1)280    @click.argument("b")281    @click.argument("c")282    def cmd(a, b, c):283        for arg in (a, b, c):284            click.echo(arg)285286    result = runner.invoke(cmd, ["a", "b", "c"])287    assert result.output.splitlines() == ["('a',)", "b", "c"]288289290def test_nargs_specified_plus_star_ordering(runner):291    @click.command()292    @click.argument("a", nargs=-1)293    @click.argument("b")294    @click.argument("c", nargs=2)295    def cmd(a, b, c):296        for arg in (a, b, c):297            click.echo(arg)298299    result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])300    assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]301302303def test_defaults_for_nargs(runner):304    @click.command()305    @click.argument("a", nargs=2, type=int, default=(1, 2))306    def cmd(a):307        x, y = a308        click.echo(x + y)309310    result = runner.invoke(cmd, [])311    assert result.output.strip() == "3"312313    result = runner.invoke(cmd, ["3", "4"])314    assert result.output.strip() == "7"315316    result = runner.invoke(cmd, ["3"])317    assert result.exception is not None318    assert "Argument 'a' takes 2 values." in result.output319320321def test_multiple_param_decls_not_allowed(runner):322    with pytest.raises(TypeError):323324        @click.command()325        @click.argument("x", click.Choice(["a", "b"]))326        def copy(x):327            click.echo(x)328329330def test_multiple_not_allowed():331    with pytest.raises(TypeError, match="multiple"):332        click.Argument(["a"], multiple=True)333334335@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])336def test_nargs_bad_default(runner, value):337    with pytest.raises(ValueError, match="nargs=2"):338        click.Argument(["a"], nargs=2, default=value)339340341def test_subcommand_help(runner):342    @click.group()343    @click.argument("name")344    @click.argument("val")345    @click.option("--opt")346    @click.pass_context347    def cli(ctx, name, val, opt):348        ctx.obj = dict(name=name, val=val)349350    @cli.command()351    @click.pass_obj352    def cmd(obj):353        click.echo(f"CMD for {obj['name']} with value {obj['val']}")354355    result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"])356    assert not result.exception357    assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output358359360def test_nested_subcommand_help(runner):361    @click.group()362    @click.argument("arg1")363    @click.option("--opt1")364    def cli(arg1, opt1):365        pass366367    @cli.group()368    @click.argument("arg2")369    @click.option("--opt2")370    def cmd(arg2, opt2):371        pass372373    @cmd.command()374    def subcmd():375        click.echo("subcommand")376377    result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"])378    assert not result.exception379    assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output