test_arguments.py
This file
Path
tests/test_arguments.py
618 lines · 18.4 KiB · Python
Last changed by
Ensure that `type_cast_value` never gets `UNSET` (#3090)Rowlando13before adoption8d4051e
History of this fileTake it
The walk stopped after 200 commits: lines older than 7ab7174 point at it.
Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 1why, one step back1import sysMerge branch '8.1.x'Sagi Buchbinder Shadurbefore adoptionb0538df
line 2why, one step back2from unittest import mockBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 3–6why, one step back34import pytest56import clickMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 7why, one step back7from click._utils import UNSETBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 8–57why, one step back8910def 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"]5657test: add two new tests for `Parameter.__init__` (recreation of #2861) (#3012)Rowlando13before adoptionc096a10
lines 58–66why, one step back58def 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 pass6566Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 67–85why, one step back67def 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):update dev dependenciesDavid Lordbefore adoptionf14b750
lines 86–88why, one step back86 assert isinstance(arg, str), (87 "UTF-8 encoded argument should be implicitly converted to Unicode"88 )Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 89–92why, one step back8990 # Simulate empty locale environment variables91 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")92 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")Merge branch '8.1.x'Sagi Buchbinder Shadurbefore adoptionb0538df
lines 93–96why, one step back93 # 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)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 97–168why, one step back9798 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"Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 169–170why, one step back169 assert result.stdout == "Foo bar baz\n"170 assert not result.stderrBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 171–247why, one step back171172173@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.output246247Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 248–273why, one step back248@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."""Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 274why, one step back274 ctx = click.Context(click.Command(""))Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 275why, one step back275 argument = click.Argument(["a"], required=True)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 276why, one step back276Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 277–280why, one step back277 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"Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 281why, one step back281Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 282–284why, one step back282 else:283 value = argument.process_value(ctx, value)284 assert value == processed_valueBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 285–297why, one step back285286287def 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"296297Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31
lines 298–335why, one step back298def 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)334335Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 336–377why, one step back336def 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')"]376377Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 378–401why, one step back378@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):Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 402why, one step back402 @click.command()Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 403why, one step back403 @click.argument("a", type=int, **argument_params)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 404why, one step back404 def cmd(a):Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 405why, one step back405 click.echo(repr(a), nl=False)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 406why, one step back406Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 407–408why, one step back407 result = runner.invoke(cmd, args)408 assert result.output == repr(expected)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 409–410why, one step back409410Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 411–478why, one step back411@pytest.mark.parametrize(412 ("default", "message"),413 [414 # Non-iterables defaults.415 ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."],416 ["", "Error: Invalid value for '[A]...': Value must be an iterable."],417 [True, "Error: Invalid value for '[A]...': Value must be an iterable."],418 [False, "Error: Invalid value for '[A]...': Value must be an iterable."],419 [12, "Error: Invalid value for '[A]...': Value must be an iterable."],420 [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."],421 # Generator default.422 [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],423 # Unset default.424 [UNSET, "Error: Missing argument 'A...'."],425 # Tuples defaults with wrong length.426 [427 tuple(),428 "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",429 ],430 [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],431 [432 (1, 2, 3),433 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",434 ],435 # Lists defaults with wrong length.436 [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],437 [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],438 [439 [1, 2, 3],440 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",441 ],442 # Sets defaults with wrong length.443 [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],444 [445 set([1]),446 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",447 ],448 [449 set([1, 2, 3]),450 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",451 ],452 # Frozensets defaults with wrong length.453 [454 frozenset(),455 "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",456 ],457 [458 frozenset([1]),459 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",460 ],461 [462 frozenset([1, 2, 3]),463 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",464 ],465 # Dictionaries defaults with wrong length.466 [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],467 [468 {1: "a"},469 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",470 ],471 [472 {1: "a", 2: "b", 3: "c"},473 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",474 ],475 ],476)477def test_bad_defaults_for_nargs(runner, default, message):478 """Some defaults are not valid when nargs is set."""Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 479why, one step back479Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 480–483why, one step back480 @click.command()481 @click.argument("a", nargs=2, type=int, default=default)482 def cmd(a):483 click.echo(repr(a))Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 484why, one step back484Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 485–488why, one step back485 result = runner.invoke(cmd, [])486 assert message in result.stderr487488Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 489–541why, one step back489def test_multiple_param_decls_not_allowed(runner):490 with pytest.raises(TypeError):491492 @click.command()493 @click.argument("x", click.Choice(["a", "b"]))494 def copy(x):495 click.echo(x)496497498def test_multiple_not_allowed():499 with pytest.raises(TypeError, match="multiple"):500 click.Argument(["a"], multiple=True)501502503def test_subcommand_help(runner):504 @click.group()505 @click.argument("name")506 @click.argument("val")507 @click.option("--opt")508 @click.pass_context509 def cli(ctx, name, val, opt):510 ctx.obj = dict(name=name, val=val)511512 @cli.command()513 @click.pass_obj514 def cmd(obj):515 click.echo(f"CMD for {obj['name']} with value {obj['val']}")516517 result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"])518 assert not result.exception519 assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output520521522def test_nested_subcommand_help(runner):523 @click.group()524 @click.argument("arg1")525 @click.option("--opt1")526 def cli(arg1, opt1):527 pass528529 @cli.group()530 @click.argument("arg2")531 @click.option("--opt2")532 def cmd(arg2, opt2):533 pass534535 @cmd.command()536 def subcmd():537 click.echo("subcommand")538539 result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"])540 assert not result.exception541 assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.outputMerge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 542–561why, one step back542543544def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved():545 class CustomArgument(click.Argument):546 pass547548 reusable_argument = click.argument("art", cls=CustomArgument)549550 @click.command()551 @reusable_argument552 def foo(arg):553 pass554555 @click.command()556 @reusable_argument557 def bar(arg):558 pass559560 assert isinstance(foo.params[0], CustomArgument)561 assert isinstance(bar.params[0], CustomArgument)Give a UserWarning when Parameter is overriden by name (#2397)Ed Rogersbefore adoption3800083
lines 562–581why, one step back562563564@pytest.mark.parametrize(565 "args_one,args_two",566 [567 (568 ("aardvark",),569 ("aardvark",),570 ),571 ],572)573def test_duplicate_names_warning(runner, args_one, args_two):574 @click.command()575 @click.argument(*args_one)576 @click.argument(*args_two)577 def cli(one, two):578 pass579580 with pytest.warns(UserWarning):581 runner.invoke(cli, [])Ensure that `type_cast_value` never gets `UNSET` (#3090)Rowlando13before adoption8d4051e
lines 582–618why, one step back582583584@pytest.mark.parametrize(585 ("argument_kwargs", "pass_argv"),586 (587 # there is a large potential parameter space to explore here588 # this is just a very small sample of it589 ({}, ["myvalue"]),590 ({"nargs": -1}, []),591 ({"nargs": -1}, ["myvalue"]),592 ({"default": None}, ["myvalue"]),593 ({"required": False}, []),594 ({"required": False}, ["myvalue"]),595 ),596)597def test_argument_custom_class_can_override_type_cast_value_and_never_sees_unset(598 runner, argument_kwargs, pass_argv599):600 """601 Test that overriding type_cast_value is supported602603 In particular, the argument is never passed an UNSET sentinel value.604 """605606 class CustomArgument(click.Argument):607 def type_cast_value(self, ctx, value):608 assert value is not UNSET609 return value610611 @click.command()612 @click.argument("myarg", **argument_kwargs, cls=CustomArgument)613 def cmd(myarg):614 click.echo("ok")615616 result = runner.invoke(cmd, pass_argv)617 assert not result.exception618 assert result.exit_code == 0