Skip to content
Myr

test_arguments.py

This file

Path

tests/test_arguments.py

629 lines · 18.7 KiB · Python

Last changed by

Add cross-reference to tests from `test_defaults.py` (#3223)Rowlando13before adoptionfa7f035

History of this file

Take it

1import sys2from unittest import mock34import pytest56import click7from click._utils import UNSET8910def test_nargs_star(runner):11    @click.command()12    @click.argument("src", nargs=-1)13    @click.argument("dst")14    def copy(src, dst):15        click.echo(f"src={'|'.join(src)}")16        click.echo(f"dst={dst}")1718    result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])19    assert not result.exception20    assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]212223def test_nargs_tup(runner):24    @click.command()25    @click.argument("name", nargs=1)26    @click.argument("point", nargs=2, type=click.INT)27    def copy(name, point):28        click.echo(f"name={name}")29        x, y = point30        click.echo(f"point={x}/{y}")3132    result = runner.invoke(copy, ["peter", "1", "2"])33    assert not result.exception34    assert result.output.splitlines() == ["name=peter", "point=1/2"]353637@pytest.mark.parametrize(38    "opts",39    [40        dict(type=(str, int)),41        dict(type=click.Tuple([str, int])),42        dict(nargs=2, type=click.Tuple([str, int])),43        dict(nargs=2, type=(str, int)),44    ],45)46def test_nargs_tup_composite(runner, opts):47    @click.command()48    @click.argument("item", **opts)49    def copy(item):50        name, id = item51        click.echo(f"name={name} id={id:d}")5253    result = runner.invoke(copy, ["peter", "1"])54    assert result.exception is None55    assert result.output.splitlines() == ["name=peter id=1"]565758def test_nargs_mismatch_with_tuple_type():59    with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):6061        @click.command()62        @click.argument("test", type=(str, int), nargs=3)63        def cli(_):64            pass656667def test_nargs_err(runner):68    @click.command()69    @click.argument("x")70    def copy(x):71        click.echo(x)7273    result = runner.invoke(copy, ["foo"])74    assert not result.exception75    assert result.output == "foo\n"7677    result = runner.invoke(copy, ["foo", "bar"])78    assert result.exit_code == 279    assert "Got unexpected extra argument (bar)" in result.output808182def test_bytes_args(runner, monkeypatch):83    @click.command()84    @click.argument("arg")85    def from_bytes(arg):86        assert isinstance(arg, str), (87            "UTF-8 encoded argument should be implicitly converted to Unicode"88        )8990    # Simulate empty locale environment variables91    monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")92    monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")93    # sys.stdin.encoding is readonly, needs some extra effort to patch.94    stdin = mock.Mock(wraps=sys.stdin)95    stdin.encoding = "utf-8"96    monkeypatch.setattr(sys, "stdin", stdin)9798    runner.invoke(99        from_bytes,100        ["Something outside of ASCII range: 林".encode()],101        catch_exceptions=False,102    )103104105def test_file_args(runner):106    @click.command()107    @click.argument("input", type=click.File("rb"))108    @click.argument("output", type=click.File("wb"))109    def inout(input, output):110        while True:111            chunk = input.read(1024)112            if not chunk:113                break114            output.write(chunk)115116    with runner.isolated_filesystem():117        result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")118        assert result.output == ""119        assert result.exit_code == 0120        with open("hello.txt", "rb") as f:121            assert f.read() == b"Hey!"122123        result = runner.invoke(inout, ["hello.txt", "-"])124        assert result.output == "Hey!"125        assert result.exit_code == 0126127128def test_path_allow_dash(runner):129    @click.command()130    @click.argument("input", type=click.Path(allow_dash=True))131    def foo(input):132        click.echo(input)133134    result = runner.invoke(foo, ["-"])135    assert result.output == "-\n"136    assert result.exit_code == 0137138139def test_file_atomics(runner):140    @click.command()141    @click.argument("output", type=click.File("wb", atomic=True))142    def inout(output):143        output.write(b"Foo bar baz\n")144        output.flush()145        with open(output.name, "rb") as f:146            old_content = f.read()147            assert old_content == b"OLD\n"148149    with runner.isolated_filesystem():150        with open("foo.txt", "wb") as f:151            f.write(b"OLD\n")152        result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)153        assert result.output == ""154        assert result.exit_code == 0155        with open("foo.txt", "rb") as f:156            assert f.read() == b"Foo bar baz\n"157158159def test_stdout_default(runner):160    @click.command()161    @click.argument("output", type=click.File("w"), default="-")162    def inout(output):163        output.write("Foo bar baz\n")164        output.flush()165166    result = runner.invoke(inout, [])167    assert not result.exception168    assert result.output == "Foo bar baz\n"169    assert result.stdout == "Foo bar baz\n"170    assert not result.stderr171172173@pytest.mark.parametrize(174    ("nargs", "value", "expect"),175    [176        (2, "", None),177        (2, "a", "Takes 2 values but 1 was given."),178        (2, "a b", ("a", "b")),179        (2, "a b c", "Takes 2 values but 3 were given."),180        (-1, "a b c", ("a", "b", "c")),181        (-1, "", ()),182    ],183)184def test_nargs_envvar(runner, nargs, value, expect):185    if nargs == -1:186        param = click.argument("arg", envvar="X", nargs=nargs)187    else:188        param = click.option("--arg", envvar="X", nargs=nargs)189190    @click.command()191    @param192    def cmd(arg):193        return arg194195    result = runner.invoke(cmd, env={"X": value}, standalone_mode=False)196197    if isinstance(expect, str):198        assert isinstance(result.exception, click.BadParameter)199        assert expect in result.exception.format_message()200    else:201        assert result.return_value == expect202203204def test_nargs_envvar_only_if_values_empty(runner):205    @click.command()206    @click.argument("arg", envvar="X", nargs=-1)207    def cli(arg):208        return arg209210    result = runner.invoke(cli, ["a", "b"], standalone_mode=False)211    assert result.return_value == ("a", "b")212213    result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False)214    assert result.return_value == ("a",)215216217def test_empty_nargs(runner):218    @click.command()219    @click.argument("arg", nargs=-1)220    def cmd(arg):221        click.echo(f"arg:{'|'.join(arg)}")222223    result = runner.invoke(cmd, [])224    assert result.exit_code == 0225    assert result.output == "arg:\n"226227    @click.command()228    @click.argument("arg", nargs=-1, required=True)229    def cmd2(arg):230        click.echo(f"arg:{'|'.join(arg)}")231232    result = runner.invoke(cmd2, [])233    assert result.exit_code == 2234    assert "Missing argument 'ARG...'" in result.output235236237def test_missing_arg(runner):238    @click.command()239    @click.argument("arg")240    def cmd(arg):241        click.echo(f"arg:{arg}")242243    result = runner.invoke(cmd, [])244    assert result.exit_code == 2245    assert "Missing argument 'ARG'." in result.output246247248@pytest.mark.parametrize(249    ("value", "expect_missing", "processed_value"),250    [251        # Unspecified type of the argument fallback to string, so everything is252        # processed the click.STRING type.253        ("", False, ""),254        ("  ", False, "  "),255        ("foo", False, "foo"),256        ("12", False, "12"),257        (12, False, "12"),258        (12.1, False, "12.1"),259        (list(), False, "[]"),260        (tuple(), False, "()"),261        (set(), False, "set()"),262        (frozenset(), False, "frozenset()"),263        (dict(), False, "{}"),264        # None is a value that is allowed to be processed by a required argument265        # because at this stage, the process_value method happens after the default is266        # applied.267        (None, False, None),268        # An UNSET required argument will raise MissingParameter.269        (UNSET, True, None),270    ],271)272def test_required_argument(value, expect_missing, processed_value):273    """Test how a required argument is processing the provided values."""274    ctx = click.Context(click.Command(""))275    argument = click.Argument(["a"], required=True)276277    if expect_missing:278        with pytest.raises(click.MissingParameter) as excinfo:279            argument.process_value(ctx, value)280        assert str(excinfo.value) == "Missing parameter: a"281282    else:283        value = argument.process_value(ctx, value)284        assert value == processed_value285286287def test_implicit_non_required(runner):288    @click.command()289    @click.argument("f", default="test")290    def cli(f):291        click.echo(f)292293    result = runner.invoke(cli, [])294    assert result.exit_code == 0295    assert result.output == "test\n"296297298def test_deprecated_usage(runner):299    @click.command()300    @click.argument("f", required=False, deprecated=True)301    def cli(f):302        click.echo(f)303304    result = runner.invoke(cli, ["--help"])305    assert result.exit_code == 0, result.output306    assert "[F!]" in result.output307308309@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])310def test_deprecated_warning(runner, deprecated):311    @click.command()312    @click.argument(313        "my-argument", required=False, deprecated=deprecated, default="default argument"314    )315    def cli(my_argument: str):316        click.echo(f"{my_argument}")317318    # defaults should not give a deprecated warning319    result = runner.invoke(cli, [])320    assert result.exit_code == 0, result.output321    assert "is deprecated" not in result.output322323    result = runner.invoke(cli, ["hello"])324    assert result.exit_code == 0, result.output325    assert "argument 'MY_ARGUMENT' is deprecated" in result.output326327    if isinstance(deprecated, str):328        assert deprecated in result.output329330331def test_deprecated_required(runner):332    with pytest.raises(ValueError, match="is deprecated and still required"):333        click.Argument(["a"], required=True, deprecated=True)334335336def test_eat_options(runner):337    @click.command()338    @click.option("-f")339    @click.argument("files", nargs=-1)340    def cmd(f, files):341        for filename in files:342            click.echo(filename)343        click.echo(f)344345    result = runner.invoke(cmd, ["--", "-foo", "bar"])346    assert result.output.splitlines() == ["-foo", "bar", ""]347348    result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])349    assert result.output.splitlines() == ["-foo", "bar", "-x"]350351352def test_nargs_star_ordering(runner):353    @click.command()354    @click.argument("a", nargs=-1)355    @click.argument("b")356    @click.argument("c")357    def cmd(a, b, c):358        for arg in (a, b, c):359            click.echo(arg)360361    result = runner.invoke(cmd, ["a", "b", "c"])362    assert result.output.splitlines() == ["('a',)", "b", "c"]363364365def test_nargs_specified_plus_star_ordering(runner):366    @click.command()367    @click.argument("a", nargs=-1)368    @click.argument("b")369    @click.argument("c", nargs=2)370    def cmd(a, b, c):371        for arg in (a, b, c):372            click.echo(arg)373374    result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])375    assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]376377378@pytest.mark.parametrize(379    ("argument_params", "args", "expected"),380    [381        # Any iterable with the same number of arguments as nargs is valid.382        [{"nargs": 2, "default": (1, 2)}, [], (1, 2)],383        [{"nargs": 2, "default": (1.1, 2.2)}, [], (1, 2)],384        [{"nargs": 2, "default": ("1", "2")}, [], (1, 2)],385        [{"nargs": 2, "default": (None, None)}, [], (None, None)],386        [{"nargs": 2, "default": [1, 2]}, [], (1, 2)],387        [{"nargs": 2, "default": {1, 2}}, [], (1, 2)],388        [{"nargs": 2, "default": frozenset([1, 2])}, [], (1, 2)],389        [{"nargs": 2, "default": {1: "a", 2: "b"}}, [], (1, 2)],390        # Empty iterable is valid if default is None.391        [{"nargs": 2, "default": None}, [], None],392        # Arguments overrides the default.393        [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)],394        # Unbounded arguments are allowed to have a default.395        # See: https://github.com/pallets/click/issues/2164396        [{"nargs": -1, "default": [42]}, [], (42,)],397        [{"nargs": -1, "default": None}, [], ()],398        [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)],399    ],400)401def test_good_defaults_for_nargs(runner, argument_params, args, expected):402    """Comprehensive check of default-value processing for arguments with403    ``nargs``.404405    .. hint::406        An option-specific equivalent is available in407        ``test_options.py::test_good_defaults_for_multiple``.408409        A smoke test covering a single basic case is in410        ``test_defaults.py::test_nargs_plus_multiple``.411    """412413    @click.command()414    @click.argument("a", type=int, **argument_params)415    def cmd(a):416        click.echo(repr(a), nl=False)417418    result = runner.invoke(cmd, args)419    assert result.output == repr(expected)420421422@pytest.mark.parametrize(423    ("default", "message"),424    [425        # Non-iterables defaults.426        ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."],427        ["", "Error: Invalid value for '[A]...': Value must be an iterable."],428        [True, "Error: Invalid value for '[A]...': Value must be an iterable."],429        [False, "Error: Invalid value for '[A]...': Value must be an iterable."],430        [12, "Error: Invalid value for '[A]...': Value must be an iterable."],431        [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."],432        # Generator default.433        [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],434        # Unset default.435        [UNSET, "Error: Missing argument 'A...'."],436        # Tuples defaults with wrong length.437        [438            tuple(),439            "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",440        ],441        [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],442        [443            (1, 2, 3),444            "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",445        ],446        # Lists defaults with wrong length.447        [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],448        [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],449        [450            [1, 2, 3],451            "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",452        ],453        # Sets defaults with wrong length.454        [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],455        [456            set([1]),457            "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",458        ],459        [460            set([1, 2, 3]),461            "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",462        ],463        # Frozensets defaults with wrong length.464        [465            frozenset(),466            "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",467        ],468        [469            frozenset([1]),470            "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",471        ],472        [473            frozenset([1, 2, 3]),474            "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",475        ],476        # Dictionaries defaults with wrong length.477        [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],478        [479            {1: "a"},480            "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",481        ],482        [483            {1: "a", 2: "b", 3: "c"},484            "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",485        ],486    ],487)488def test_bad_defaults_for_nargs(runner, default, message):489    """Some defaults are not valid when nargs is set."""490491    @click.command()492    @click.argument("a", nargs=2, type=int, default=default)493    def cmd(a):494        click.echo(repr(a))495496    result = runner.invoke(cmd, [])497    assert message in result.stderr498499500def test_multiple_param_decls_not_allowed(runner):501    with pytest.raises(TypeError):502503        @click.command()504        @click.argument("x", click.Choice(["a", "b"]))505        def copy(x):506            click.echo(x)507508509def test_multiple_not_allowed():510    with pytest.raises(TypeError, match="multiple"):511        click.Argument(["a"], multiple=True)512513514def test_subcommand_help(runner):515    @click.group()516    @click.argument("name")517    @click.argument("val")518    @click.option("--opt")519    @click.pass_context520    def cli(ctx, name, val, opt):521        ctx.obj = dict(name=name, val=val)522523    @cli.command()524    @click.pass_obj525    def cmd(obj):526        click.echo(f"CMD for {obj['name']} with value {obj['val']}")527528    result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"])529    assert not result.exception530    assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output531532533def test_nested_subcommand_help(runner):534    @click.group()535    @click.argument("arg1")536    @click.option("--opt1")537    def cli(arg1, opt1):538        pass539540    @cli.group()541    @click.argument("arg2")542    @click.option("--opt2")543    def cmd(arg2, opt2):544        pass545546    @cmd.command()547    def subcmd():548        click.echo("subcommand")549550    result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"])551    assert not result.exception552    assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output553554555def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved():556    class CustomArgument(click.Argument):557        pass558559    reusable_argument = click.argument("art", cls=CustomArgument)560561    @click.command()562    @reusable_argument563    def foo(arg):564        pass565566    @click.command()567    @reusable_argument568    def bar(arg):569        pass570571    assert isinstance(foo.params[0], CustomArgument)572    assert isinstance(bar.params[0], CustomArgument)573574575@pytest.mark.parametrize(576    "args_one,args_two",577    [578        (579            ("aardvark",),580            ("aardvark",),581        ),582    ],583)584def test_duplicate_names_warning(runner, args_one, args_two):585    @click.command()586    @click.argument(*args_one)587    @click.argument(*args_two)588    def cli(one, two):589        pass590591    with pytest.warns(UserWarning):592        runner.invoke(cli, [])593594595@pytest.mark.parametrize(596    ("argument_kwargs", "pass_argv"),597    (598        # there is a large potential parameter space to explore here599        # this is just a very small sample of it600        ({}, ["myvalue"]),601        ({"nargs": -1}, []),602        ({"nargs": -1}, ["myvalue"]),603        ({"default": None}, ["myvalue"]),604        ({"required": False}, []),605        ({"required": False}, ["myvalue"]),606    ),607)608def test_argument_custom_class_can_override_type_cast_value_and_never_sees_unset(609    runner, argument_kwargs, pass_argv610):611    """612    Test that overriding type_cast_value is supported613614    In particular, the argument is never passed an UNSET sentinel value.615    """616617    class CustomArgument(click.Argument):618        def type_cast_value(self, ctx, value):619            assert value is not UNSET620            return value621622    @click.command()623    @click.argument("myarg", **argument_kwargs, cls=CustomArgument)624    def cmd(myarg):625        click.echo("ok")626627    result = runner.invoke(cmd, pass_argv)628    assert not result.exception629    assert result.exit_code == 0