test_arguments.py
This file
Path
tests/test_arguments.py
1,229 lines · 38.0 KiB · Python
Last changed by
History of this fileTake it
The walk stopped after 200 commits: lines older than 9ce34f2 point at it.
Deprecate parameter names that are: not a Python identifier, or a Python Keyword, or not lower-cased (#3866)Rowlando13before adoption06b2a67
line 1why, one step back1import itertoolsMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 2why, one step back2import sysDeprecate parameter names that are: not a Python identifier, or a Python Keyword, or not lower-cased (#3866)Rowlando13before adoption06b2a67
lines 3–4why, one step back3import unicodedata4import warningsMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 5–7why, one step back5from unittest import mock67import pytestDeprecate parameter names that are: not a Python identifier, or a Python Keyword, or not lower-cased (#3866)Rowlando13before adoption06b2a67
line 8why, one step back8from test_options import ENV_NAMES_ARE_CASE_INSENSITIVEMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 9–10why, one step back910import clickMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 11why, one step back11from click._utils import UNSETMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 12–61why, one step back121314def test_nargs_star(runner):15 @click.command()16 @click.argument("src", nargs=-1)17 @click.argument("dst")18 def copy(src, dst):19 click.echo(f"src={'|'.join(src)}")20 click.echo(f"dst={dst}")2122 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])23 assert not result.exception24 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]252627def test_nargs_tup(runner):28 @click.command()29 @click.argument("name", nargs=1)30 @click.argument("point", nargs=2, type=click.INT)31 def copy(name, point):32 click.echo(f"name={name}")33 x, y = point34 click.echo(f"point={x}/{y}")3536 result = runner.invoke(copy, ["peter", "1", "2"])37 assert not result.exception38 assert result.output.splitlines() == ["name=peter", "point=1/2"]394041@pytest.mark.parametrize(42 "opts",43 [44 dict(type=(str, int)),45 dict(type=click.Tuple([str, int])),46 dict(nargs=2, type=click.Tuple([str, int])),47 dict(nargs=2, type=(str, int)),48 ],49)50def test_nargs_tup_composite(runner, opts):51 @click.command()52 @click.argument("item", **opts)53 def copy(item):54 name, id = item55 click.echo(f"name={name} id={id:d}")5657 result = runner.invoke(copy, ["peter", "1"])58 assert result.exception is None59 assert result.output.splitlines() == ["name=peter id=1"]6061test: add two new tests for `Parameter.__init__` (recreation of #2861) (#3012)Rowlando13before adoptionc096a10
lines 62–70why, one step back62def test_nargs_mismatch_with_tuple_type():63 with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):6465 @click.command()66 @click.argument("test", type=(str, int), nargs=3)67 def cli(_):68 pass6970Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 71–83why, one step back71def test_nargs_err(runner):72 @click.command()73 @click.argument("x")74 def copy(x):75 click.echo(x)7677 result = runner.invoke(copy, ["foo"])78 assert not result.exception79 assert result.output == "foo\n"8081 result = runner.invoke(copy, ["foo", "bar"])82 assert result.exit_code == 283 assert "Got unexpected extra argument (bar)" in result.outputDeprecate parameter names that are: not a Python identifier, or a Python Keyword, or not lower-cased (#3866)Rowlando13before adoption06b2a67
lines 84–445why, one step back848586@pytest.mark.parametrize(87 ("decl", "expect"),88 [89 ("src", "src"),90 ("foo-bar", "foo_bar"),91 ("FOO-BAR", "foo_bar"),92 ("Foo_Bar", "foo_bar"),93 ("foo__bar", "foo__bar"),94 ("_foo", "_foo"),95 ("__foo", "__foo"),96 ],97)98def test_argument_names(runner, decl, expect):99 @click.command()100 @click.argument(decl)101 def cmd(**kwargs):102 click.echo(kwargs[expect])103104 assert cmd.params[0].name == expect105106 result = runner.invoke(cmd, ["value"])107 assert not result.exception108 assert result.output == "value\n"109110111def test_argument_normalizes_an_identifier_decl():112 """An argument transforms its declaration; an option keeps an explicit name."""113 assert click.Argument(["Foo_Bar"]).name == "foo_bar"114115 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):116 assert click.Option(["--x", "Foo_Bar"]).name == "Foo_Bar"117118119PARAM_KINDS = [120 pytest.param(click.Argument, "{decl}", id="argument"),121 pytest.param(click.Option, "--{decl}", id="option"),122]123124# Declarations whose lower casing is neither one-to-one nor length-preserving.125UNICODE_CASE_DECLS = [126 pytest.param("Ω", "ω", id="omega"),127 pytest.param("İ", "i\N{COMBINING DOT ABOVE}", id="dotted-capital-i"),128 pytest.param("ΟΔΟΣ", "οδος", id="final-sigma"),129 pytest.param("ẞ", "ß", id="capital-sharp-s"),130 pytest.param("\N{KELVIN SIGN}", "k", id="kelvin-sign"),131 pytest.param("foo-٣", "foo_٣", id="arabic-indic-digit"),132]133134NAME_TRANSFORM_DECLS = UNICODE_CASE_DECLS + [135 pytest.param("a-b-c", "a_b_c", id="interior-singles"),136 pytest.param("a-----b", "a_____b", id="interior-run"),137 pytest.param("a--", "a__", id="trailing"),138 pytest.param("-a-", "_a_", id="leading-survives-the-prefix"),139 pytest.param("-a----b--", "_a____b__", id="everywhere"),140 pytest.param("--", "__", id="dashes-only"),141 pytest.param("_-_", "___", id="around-an-underscore"),142]143144# Declarations covering every shape the naming transform accepts.145NAME_SWEEP_DECLS = [146 "",147 "-",148 "--",149 "---",150 "0",151 "--0",152 "0-file",153 "--0-file",154 "foo.bar",155 "--foo.bar",156 "foo bar",157 "x",158 "--x",159 "X_Y",160 "--X-Y",161]162163164@pytest.mark.parametrize("count", [1, 2])165@pytest.mark.parametrize("expose_value", [True, False])166def test_parameter_name_is_an_identifier_or_deprecated(count, expose_value):167 built = 0168169 for decls in itertools.product(NAME_SWEEP_DECLS, repeat=count):170 for cls in (click.Option, click.Argument):171 with warnings.catch_warnings(record=True) as caught:172 warnings.simplefilter("always")173174 try:175 param = cls(list(decls), expose_value=expose_value)176 except (TypeError, ValueError):177 continue178179 built += 1180181 if param.name.isidentifier():182 continue183184 assert any(issubclass(w.category, DeprecationWarning) for w in caught), (185 f"{cls.__name__}({list(decls)!r}, expose_value={expose_value})"186 f" named its parameter {param.name!r} without a warning"187 )188189 assert built, "the sweep built no parameter, so it proves nothing"190191192def test_argument_requires_its_one_declaration():193 """An exposed argument with no declaration is refused, an unexposed one warns."""194 with pytest.raises(TypeError, match="does not have a name"):195 click.Argument([])196197 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):198 assert click.Argument([], expose_value=False).name == ""199200201def test_argument_name_check_applies_when_not_exposed():202 """An unexposed argument keeps the name, and says Click 9.0 will refuse it."""203 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):204 assert click.Argument(["0foo"], expose_value=False).name == "0foo"205206207def test_argument_metavar_renders_what_a_declaration_may_not(runner):208 """``metavar`` carries a display the declaration is no longer allowed to.209210 An argument takes exactly one declaration and has no explicit-name channel,211 so a display such as ``0FOO`` is reached by naming the parameter separately212 and passing the display as ``metavar``.213 """214 seen = []215216 def record(ctx, param, value):217 seen.append(value)218219 @click.command()220 @click.argument("zero_foo", expose_value=False, callback=record, metavar="0FOO")221 def cmd(**kwargs):222 click.echo(repr(kwargs))223224 assert cmd.params[0].name == "zero_foo"225226 result = runner.invoke(cmd, ["value"])227 assert not result.exception228 assert result.output == "{}\n"229 assert seen == ["value"]230231 result = runner.invoke(cmd, ["--help"])232 assert "0FOO" in result.output233234235@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)236@pytest.mark.parametrize(("decl", "expect"), NAME_TRANSFORM_DECLS)237def test_parameter_name_transform(cls, form, decl, expect):238 """``str.lower()`` is neither one-to-one nor length-preserving, and a239 dash becomes an underscore everywhere except an option's prefix.240 """241 assert cls([form.format(decl=decl)]).name == expect242243244@pytest.mark.parametrize(("decl", "expect"), UNICODE_CASE_DECLS)245def test_option_explicit_name_keeps_its_case(decl, expect):246 """An explicit name is kept as spelled, where Click 9.0 transforms it."""247 if not decl.isidentifier():248 assert click.Option(["--x", decl]).name == "x"249 return250251 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):252 assert click.Option(["--x", decl]).name == decl253254 assert decl.lower() == expect255256257@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)258@pytest.mark.parametrize(259 "decl",260 [261 pytest.param("0foo", id="leading-digit"),262 pytest.param("0", id="digit-only"),263 pytest.param("foo.bar", id="dot"),264 pytest.param("foo bar", id="space"),265 pytest.param("\u0663foo", id="leading-arabic-indic-digit"),266 # Separators that read as a hyphen but are not the one replaced.267 pytest.param("foo\N{NON-BREAKING HYPHEN}bar", id="non-breaking-hyphen"),268 pytest.param("foo\u2013bar", id="en-dash"),269 pytest.param("foo\u2212bar", id="minus-sign"),270 # Characters that occupy no width at all.271 pytest.param("a\N{ZERO WIDTH SPACE}b", id="zero-width-space"),272 pytest.param("a\N{SOFT HYPHEN}b", id="soft-hyphen"),273 pytest.param("a\N{RIGHT-TO-LEFT OVERRIDE}b", id="right-to-left-override"),274 # Even nothing at all, which reaches an option as a bare ``--``.275 pytest.param("", id="empty"),276 ],277)278def test_parameter_name_not_an_identifier_is_deprecated(cls, form, decl):279 """Click 9.0 refuses every one of these; 8.6 keeps them and says so.280281 An exposed option is the exception, since it already refuses them.282 """283 spec = form.format(decl=decl)284285 if cls is click.Option:286 with pytest.raises(TypeError, match="Could not determine name"):287 cls([spec])288 return289290 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):291 param = cls([spec])292293 assert not param.name.isidentifier()294295296@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)297@pytest.mark.parametrize(298 "char",299 [300 pytest.param("\N{ZERO WIDTH JOINER}", id="zero-width-joiner"),301 pytest.param("\N{ZERO WIDTH NON-JOINER}", id="zero-width-non-joiner"),302 ],303)304def test_parameter_name_identifier_check_follows_the_unicode_table(cls, form, char):305 """Python 3.13 allows unicode zero-width joiner and non-joiner in identifiers."""306 name = f"a{char}b"307 assert name.isidentifier() == (sys.version_info >= (3, 13))308 decl = form.format(decl=name)309310 if name.isidentifier():311 assert cls([decl]).name == name312 return313314 if cls is click.Option:315 with pytest.raises(TypeError, match="Could not determine name"):316 cls([decl])317 return318319 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):320 assert cls([decl]).name == name321322323@pytest.mark.parametrize(324 ("decorator", "decl", "argv"),325 [326 pytest.param(click.argument, "fi", ["value"], id="argument"),327 pytest.param(click.option, "--fi", ["--fi", "value"], id="option"),328 ],329)330def test_parameter_name_is_not_nfkc_normalized(runner, decorator, decl, argv):331 """``str.isidentifier()`` is not the test for "can be a parameter name".332333 Python normalizes an identifier written in source to NFKC, so the ligature334 "fi" compiles to the two letters. ``_parse_decls`` runs no normalization,335 so the name keeps the ligature and only ``**kwargs`` can carry it.336 """337338 @click.command()339 @decorator(decl)340 def cmd(**kwargs):341 click.echo(repr(kwargs))342343 name = cmd.params[0].name344 assert name == "fi"345 assert name.isidentifier()346 assert unicodedata.normalize("NFKC", name) == "fi"347348 result = runner.invoke(cmd, argv)349 assert not result.exception350 assert result.output == "{'fi': 'value'}\n"351352353def test_argument_name_keeps_its_normalization_form(runner):354 """A composed and a decomposed declaration are two distinct arguments.355356 Both render as ``café`` and both are valid identifiers, so the pair357 coexists on one command with nothing on screen to tell them apart.358 """359 decomposed = "cafe\N{COMBINING ACUTE ACCENT}"360 composed = unicodedata.normalize("NFC", decomposed)361362 @click.command()363 @click.argument(composed)364 @click.argument(decomposed)365 def cmd(**kwargs):366 click.echo(repr(sorted(kwargs)))367368 assert [p.name for p in cmd.params] == [composed, decomposed]369370 result = runner.invoke(cmd, ["one", "two"])371 assert not result.exception372 assert result.output == f"['{decomposed}', '{composed}']\n"373374375def test_argument_name_case_transform_can_collide(runner):376377 @click.command()378 @click.argument("Foo-Bar")379 @click.argument("foo_bar")380 def cmd(**kwargs):381 click.echo(repr(kwargs))382383 with pytest.warns(UserWarning, match="is used by an argument"):384 result = runner.invoke(cmd, ["one", "two"], catch_exceptions=False)385386 assert result.output == "{'foo_bar': 'two'}\n"387388389def test_argument_name_can_collide_with_an_option(runner):390391 @click.command()392 @click.option("--foo-bar")393 @click.argument("Foo-Bar", required=False)394 def cmd(**kwargs):395 click.echo(repr(kwargs))396397 assert [p.name for p in cmd.params] == ["foo_bar", "foo_bar"]398399 with pytest.warns(UserWarning, match="is used by an argument"):400 result = runner.invoke(401 cmd, ["--foo-bar", "from-option", "from-argument"], catch_exceptions=False402 )403404 assert result.output == "{'foo_bar': 'from-argument'}\n"405406407def test_argument_has_no_auto_envvar(runner):408 """An argument reads only the envvars it names, never a derived one."""409410 @click.command()411 @click.argument("Foo-Bar", required=False)412 def cmd(**kwargs):413 click.echo(repr(kwargs))414415 result = runner.invoke(416 cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}417 )418 assert not result.exception419 assert result.output == "{'foo_bar': None}\n"420421422@pytest.mark.parametrize(423 ("env", "expect"),424 [425 pytest.param({"ArG": "foo"}, "'foo'", id="exact"),426 pytest.param({"ARG": "foo"}, "None", id="upper"),427 pytest.param({"arg": "foo"}, "None", id="lower"),428 ],429)430def test_argument_explicit_envvar_case_sensitivity(runner, env, expect):431 """An argument matches its named envvar exactly, like an option does.432433 And loses the distinction on Windows, like an option does.434 """435436 @click.command()437 @click.argument("arg", envvar="ArG", required=False)438 def cmd(arg):439 click.echo(repr(arg))440441 result = runner.invoke(cmd, [], env=env)442 assert not result.exception443 if ENV_NAMES_ARE_CASE_INSENSITIVE:444 expect = "'foo'"445 assert result.output == f"{expect}\n"Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 446–470why, one step back446447448def test_bytes_args(runner, monkeypatch):449 @click.command()450 @click.argument("arg")451 def from_bytes(arg):452 assert isinstance(arg, str), (453 "UTF-8 encoded argument should be implicitly converted to Unicode"454 )455456 # Simulate empty locale environment variables457 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")458 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")459 # sys.stdin.encoding is readonly, needs some extra effort to patch.460 stdin = mock.Mock(wraps=sys.stdin)461 stdin.encoding = "utf-8"462 monkeypatch.setattr(sys, "stdin", stdin)463464 runner.invoke(465 from_bytes,466 ["Something outside of ASCII range: 林".encode()],467 catch_exceptions=False,468 )469470Deprecate `isolated_filesystem` and document its limits (#3704)Rowlando13before adoptioncfa01ee
line 471why, one step back471def test_file_args(runner, tmp_path):Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 472–481why, one step back472 @click.command()473 @click.argument("input", type=click.File("rb"))474 @click.argument("output", type=click.File("wb"))475 def inout(input, output):476 while True:477 chunk = input.read(1024)478 if not chunk:479 break480 output.write(chunk)481Deprecate `isolated_filesystem` and document its limits (#3704)Rowlando13before adoptioncfa01ee
lines 482–486why, one step back482 hello = tmp_path / "hello.txt"483 result = runner.invoke(inout, ["-", str(hello)], input="Hey!")484 assert result.output == ""485 assert result.exit_code == 0486 assert hello.read_bytes() == b"Hey!"Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 487why, one step back487Deprecate `isolated_filesystem` and document its limits (#3704)Rowlando13before adoptioncfa01ee
lines 488–490why, one step back488 result = runner.invoke(inout, [str(hello), "-"])489 assert result.output == "Hey!"490 assert result.exit_code == 0Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 491–503why, one step back491492493def test_path_allow_dash(runner):494 @click.command()495 @click.argument("input", type=click.Path(allow_dash=True))496 def foo(input):497 click.echo(input)498499 result = runner.invoke(foo, ["-"])500 assert result.output == "-\n"501 assert result.exit_code == 0502503Deprecate `isolated_filesystem` and document its limits (#3704)Rowlando13before adoptioncfa01ee
line 504why, one step back504def test_file_atomics(runner, tmp_path):Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 505–513why, one step back505 @click.command()506 @click.argument("output", type=click.File("wb", atomic=True))507 def inout(output):508 output.write(b"Foo bar baz\n")509 output.flush()510 with open(output.name, "rb") as f:511 old_content = f.read()512 assert old_content == b"OLD\n"513Deprecate `isolated_filesystem` and document its limits (#3704)Rowlando13before adoptioncfa01ee
lines 514–519why, one step back514 foo = tmp_path / "foo.txt"515 foo.write_bytes(b"OLD\n")516 result = runner.invoke(inout, [str(foo)], input="Hey!", catch_exceptions=False)517 assert result.output == ""518 assert result.exit_code == 0519 assert foo.read_bytes() == b"Foo bar baz\n"Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 520–531why, one step back520521522def test_stdout_default(runner):523 @click.command()524 @click.argument("output", type=click.File("w"), default="-")525 def inout(output):526 output.write("Foo bar baz\n")527 output.flush()528529 result = runner.invoke(inout, [])530 assert not result.exception531 assert result.output == "Foo bar baz\n"Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 532–533why, one step back532 assert result.stdout == "Foo bar baz\n"533 assert not result.stderrMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 534–610why, one step back534535536@pytest.mark.parametrize(537 ("nargs", "value", "expect"),538 [539 (2, "", None),540 (2, "a", "Takes 2 values but 1 was given."),541 (2, "a b", ("a", "b")),542 (2, "a b c", "Takes 2 values but 3 were given."),543 (-1, "a b c", ("a", "b", "c")),544 (-1, "", ()),545 ],546)547def test_nargs_envvar(runner, nargs, value, expect):548 if nargs == -1:549 param = click.argument("arg", envvar="X", nargs=nargs)550 else:551 param = click.option("--arg", envvar="X", nargs=nargs)552553 @click.command()554 @param555 def cmd(arg):556 return arg557558 result = runner.invoke(cmd, env={"X": value}, standalone_mode=False)559560 if isinstance(expect, str):561 assert isinstance(result.exception, click.BadParameter)562 assert expect in result.exception.format_message()563 else:564 assert result.return_value == expect565566567def test_nargs_envvar_only_if_values_empty(runner):568 @click.command()569 @click.argument("arg", envvar="X", nargs=-1)570 def cli(arg):571 return arg572573 result = runner.invoke(cli, ["a", "b"], standalone_mode=False)574 assert result.return_value == ("a", "b")575576 result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False)577 assert result.return_value == ("a",)578579580def test_empty_nargs(runner):581 @click.command()582 @click.argument("arg", nargs=-1)583 def cmd(arg):584 click.echo(f"arg:{'|'.join(arg)}")585586 result = runner.invoke(cmd, [])587 assert result.exit_code == 0588 assert result.output == "arg:\n"589590 @click.command()591 @click.argument("arg", nargs=-1, required=True)592 def cmd2(arg):593 click.echo(f"arg:{'|'.join(arg)}")594595 result = runner.invoke(cmd2, [])596 assert result.exit_code == 2597 assert "Missing argument 'ARG...'" in result.output598599600def test_missing_arg(runner):601 @click.command()602 @click.argument("arg")603 def cmd(arg):604 click.echo(f"arg:{arg}")605606 result = runner.invoke(cmd, [])607 assert result.exit_code == 2608 assert "Missing argument 'ARG'." in result.output609610Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 611–636why, one step back611@pytest.mark.parametrize(612 ("value", "expect_missing", "processed_value"),613 [614 # Unspecified type of the argument fallback to string, so everything is615 # processed the click.STRING type.616 ("", False, ""),617 (" ", False, " "),618 ("foo", False, "foo"),619 ("12", False, "12"),620 (12, False, "12"),621 (12.1, False, "12.1"),622 (list(), False, "[]"),623 (tuple(), False, "()"),624 (set(), False, "set()"),625 (frozenset(), False, "frozenset()"),626 (dict(), False, "{}"),627 # None is a value that is allowed to be processed by a required argument628 # because at this stage, the process_value method happens after the default is629 # applied.630 (None, False, None),631 # An UNSET required argument will raise MissingParameter.632 (UNSET, True, None),633 ],634)635def test_required_argument(value, expect_missing, processed_value):636 """Test how a required argument is processing the provided values."""Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 637why, one step back637 ctx = click.Context(click.Command(""))Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 638why, one step back638 argument = click.Argument(["a"], required=True)Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 639why, one step back639Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 640–643why, one step back640 if expect_missing:641 with pytest.raises(click.MissingParameter) as excinfo:642 argument.process_value(ctx, value)643 assert str(excinfo.value) == "Missing parameter: a"Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 644why, one step back644Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 645–647why, one step back645 else:646 value = argument.process_value(ctx, value)647 assert value == processed_valueMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 648–660why, one step back648649650def test_implicit_non_required(runner):651 @click.command()652 @click.argument("f", default="test")653 def cli(f):654 click.echo(f)655656 result = runner.invoke(cli, [])657 assert result.exit_code == 0658 assert result.output == "test\n"659660Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
lines 661–692why, one step back661def test_argument_help(runner):662 @click.command()663 @click.argument("name", help="The name to print")664 @click.option("--count", default=1, help="number of greetings")665 def cli(name, count):666 pass667668 result = runner.invoke(cli, ["--help"])669 assert result.exit_code == 0, result.output670 assert "Positional arguments:" in result.output671 assert "NAME" in result.output672 assert "The name to print" in result.output673 assert "Options:" in result.output674 assert "number of greetings" in result.output675 assert result.output.index("Positional arguments:") < result.output.index(676 "Options:"677 )678679680def test_argument_help_options_only_no_arguments_section(runner):681 @click.command()682 @click.option("--count", default=1, help="number of greetings")683 def cli(count):684 pass685686 result = runner.invoke(cli, ["--help"])687 assert result.exit_code == 0, result.output688 assert "Positional arguments:" not in result.output689 assert "Options:" in result.output690 assert "number of greetings" in result.output691692Merge stable into main (#3876)Rowlando13before adoption3cbaa76
lines 693–785why, one step back693def test_argument_help_lists_undocumented_arguments(runner):694 """One documented argument makes the section list all of them."""695696 @click.command()697 @click.argument("src", help="Source path")698 @click.argument("dst")699 @click.argument("extra", nargs=-1)700 def cli(src, dst, extra):701 pass702703 result = runner.invoke(cli, ["--help"])704 assert result.exit_code == 0, result.output705 lines = result.output.splitlines()706 start = lines.index("Positional arguments:")707 assert lines[start : start + 4] == [708 "Positional arguments:",709 " SRC Source path",710 " DST",711 " [EXTRA]...",712 ]713714715def test_argument_help_undocumented_arguments_only_no_section(runner):716 """Arguments alone produce no section: at least one needs a help."""717718 @click.command()719 @click.argument("src")720 @click.argument("dst")721 def cli(src, dst):722 pass723724 result = runner.invoke(cli, ["--help"])725 assert result.exit_code == 0, result.output726 assert "Positional arguments:" not in result.output727728729def test_argument_help_deprecated_without_help_lists_all(runner):730 """A deprecation label counts as help and brings every argument into view."""731732 @click.command()733 @click.argument("src", required=False, deprecated=True)734 @click.argument("dst")735 def cli(src, dst):736 pass737738 result = runner.invoke(cli, ["--help"])739 assert result.exit_code == 0, result.output740 lines = result.output.splitlines()741 start = lines.index("Positional arguments:")742 assert lines[start : start + 3] == [743 "Positional arguments:",744 " [SRC!] (DEPRECATED)",745 " DST",746 ]747748749def test_argument_help_empty_string_lists_all(runner):750 """An explicit empty help opens the section, the same way an empty option help751 keeps its option listed.752 """753754 @click.command()755 @click.argument("src", help="")756 @click.argument("dst")757 def cli(src, dst):758 pass759760 result = runner.invoke(cli, ["--help"])761 assert result.exit_code == 0, result.output762 lines = result.output.splitlines()763 start = lines.index("Positional arguments:")764 assert lines[start : start + 3] == [765 "Positional arguments:",766 " SRC",767 " DST",768 ]769770771@pytest.mark.parametrize(772 ("help_text", "expected"),773 [774 pytest.param(None, ("SRC", ""), id="None"),775 pytest.param("", ("SRC", ""), id="empty"),776 pytest.param("Source path", ("SRC", "Source path"), id="documented"),777 ],778)779def test_argument_get_help_record_never_none(help_text, expected):780 """Every argument gets a row, even an undocumented one."""781 arg = click.Argument(["src"], help=help_text)782 ctx = click.Context(click.Command("cli"))783 assert arg.get_help_record(ctx) == expected784785Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
lines 786–797why, one step back786def test_argument_help_optional_metavar(runner):787 @click.command()788 @click.argument("name", required=False, default="", help="The name to print")789 def cli(name):790 pass791792 result = runner.invoke(cli, ["--help"])793 assert result.exit_code == 0, result.output794 assert "[NAME]" in result.output795 assert "The name to print" in result.output796797Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 798–808why, one step back798def test_deprecated_usage(runner):799 @click.command()800 @click.argument("f", required=False, deprecated=True)801 def cli(f):802 click.echo(f)803804 result = runner.invoke(cli, ["--help"])805 assert result.exit_code == 0, result.output806 assert "[F!]" in result.output807808Merge stable into main (#3521)Rowlando13before adoption1a994ad
lines 809–832why, one step back809@pytest.mark.parametrize(810 ("kwargs", "expected"),811 [812 ({}, "FOO"),813 ({"required": True}, "FOO"),814 ({"required": False}, "[FOO]"),815 ({"default": "x"}, "[FOO]"),816 ({"nargs": -1}, "[FOO]..."),817 ({"nargs": -1, "required": True}, "FOO..."),818 ({"nargs": 2}, "FOO..."),819 ({"nargs": 2, "required": False}, "[FOO]..."),820 ],821)822def test_argument_metavar_marks_optional(runner, kwargs, expected):823 """An argument is bracketed in the usage line only when it is optional."""824825 @click.command()826 @click.argument("foo", **kwargs)827 def cli(foo):828 pass829830 result = runner.invoke(cli, ["--help"])831 assert result.exit_code == 0832 assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {expected}"Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
lines 833–865why, one step back833834835@pytest.mark.parametrize(836 ("deprecated", "expected_label"),837 [(True, "(DEPRECATED)"), ("use g instead", "(DEPRECATED: use g instead)")],838)839def test_deprecated_usage_help_record(runner, deprecated, expected_label):840 @click.command()841 @click.argument("f", required=False, deprecated=deprecated, help="path to the file")842 def cli(f):843 click.echo(f)844845 result = runner.invoke(cli, ["--help"])846 assert result.exit_code == 0, result.output847 assert "Positional arguments:" in result.output848 assert "[F!]" in result.output849 assert f"path to the file {expected_label}" in result.output850851852def test_deprecated_usage_help_record_without_help(runner):853 @click.command()854 @click.argument("f", required=False, deprecated=True)855 def cli(f):856 click.echo(f)857858 result = runner.invoke(cli, ["--help"])859 assert result.exit_code == 0, result.output860 # Deprecation alone produces a help row with just the deprecation label.861 assert "Positional arguments:" in result.output862 assert "(DEPRECATED)" in result.output863864865@pytest.mark.parametrize(866 ("kwargs", "expected_spec", "expected_help_spec"),867 [868 ({}, "FILENAME", "FILENAME"),869 ({"required": False}, "FILENAME", "[FILENAME]"),870 ({"nargs": -1}, "FILENAME", "[FILENAME]..."),871 ({"metavar": "<file>"}, "<file>", "<file>"),872 ],873)874def test_spec_and_help_spec(kwargs, expected_spec, expected_help_spec):875 """The spec names the argument, while the help spec decorates it with the876 optionality and repetition markers shown on the help page.877 """878 arg = click.Argument(["filename"], **kwargs)879 ctx = click.Context(click.Command("cli"))880 assert arg.spec == expected_spec881 assert arg.get_help_spec(ctx) == expected_help_spec882883884@pytest.mark.parametrize("help_text", [None, "path to the file"])885def test_help_spec_matches_help_record(help_text):886 """The help spec is the left column of the argument's help record, whether887 or not the argument documents itself.888 """889 arg = click.Argument(["filename"], help=help_text)890 ctx = click.Context(click.Command("cli"))891 assert arg.get_help_spec(ctx) == "FILENAME"892 assert arg.get_help_record(ctx)[0] == arg.get_help_spec(ctx)893894895@pytest.mark.parametrize(Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
lines 896–906why, one step back896 ("deprecated", "expected"),897 [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],898)899@pytest.mark.parametrize("help_text", ["", None])900def test_deprecated_empty_help_no_leading_space(help_text, deprecated, expected):901 """An argument with empty or missing help text must not gain a stray leading902 space before the deprecation label.903 """904 arg = click.Argument(["foo"], required=False, help=help_text, deprecated=deprecated)905 ctx = click.Context(click.Command("cli"))906 assert arg.get_help_record(ctx)[1] == expectedMerge stable into main (#3521)Rowlando13before adoption1a994ad
lines 907–908why, one step back907908Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 909–977why, one step back909@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])910def test_deprecated_warning(runner, deprecated):911 @click.command()912 @click.argument(913 "my-argument", required=False, deprecated=deprecated, default="default argument"914 )915 def cli(my_argument: str):916 click.echo(f"{my_argument}")917918 # defaults should not give a deprecated warning919 result = runner.invoke(cli, [])920 assert result.exit_code == 0, result.output921 assert "is deprecated" not in result.output922923 result = runner.invoke(cli, ["hello"])924 assert result.exit_code == 0, result.output925 assert "argument 'MY_ARGUMENT' is deprecated" in result.output926927 if isinstance(deprecated, str):928 assert deprecated in result.output929930931def test_deprecated_required(runner):932 with pytest.raises(ValueError, match="is deprecated and still required"):933 click.Argument(["a"], required=True, deprecated=True)934935936def test_eat_options(runner):937 @click.command()938 @click.option("-f")939 @click.argument("files", nargs=-1)940 def cmd(f, files):941 for filename in files:942 click.echo(filename)943 click.echo(f)944945 result = runner.invoke(cmd, ["--", "-foo", "bar"])946 assert result.output.splitlines() == ["-foo", "bar", ""]947948 result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])949 assert result.output.splitlines() == ["-foo", "bar", "-x"]950951952def test_nargs_star_ordering(runner):953 @click.command()954 @click.argument("a", nargs=-1)955 @click.argument("b")956 @click.argument("c")957 def cmd(a, b, c):958 for arg in (a, b, c):959 click.echo(arg)960961 result = runner.invoke(cmd, ["a", "b", "c"])962 assert result.output.splitlines() == ["('a',)", "b", "c"]963964965def test_nargs_specified_plus_star_ordering(runner):966 @click.command()967 @click.argument("a", nargs=-1)968 @click.argument("b")969 @click.argument("c", nargs=2)970 def cmd(a, b, c):971 for arg in (a, b, c):972 click.echo(arg)973974 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])975 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]976977Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 978–1001why, one step back978@pytest.mark.parametrize(979 ("argument_params", "args", "expected"),980 [981 # Any iterable with the same number of arguments as nargs is valid.982 [{"nargs": 2, "default": (1, 2)}, [], (1, 2)],983 [{"nargs": 2, "default": (1.1, 2.2)}, [], (1, 2)],984 [{"nargs": 2, "default": ("1", "2")}, [], (1, 2)],985 [{"nargs": 2, "default": (None, None)}, [], (None, None)],986 [{"nargs": 2, "default": [1, 2]}, [], (1, 2)],987 [{"nargs": 2, "default": {1, 2}}, [], (1, 2)],988 [{"nargs": 2, "default": frozenset([1, 2])}, [], (1, 2)],989 [{"nargs": 2, "default": {1: "a", 2: "b"}}, [], (1, 2)],990 # Empty iterable is valid if default is None.991 [{"nargs": 2, "default": None}, [], None],992 # Arguments overrides the default.993 [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)],994 # Unbounded arguments are allowed to have a default.995 # See: https://github.com/pallets/click/issues/2164996 [{"nargs": -1, "default": [42]}, [], (42,)],997 [{"nargs": -1, "default": None}, [], ()],998 [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)],999 ],1000)1001def test_good_defaults_for_nargs(runner, argument_params, args, expected):Add cross-reference to tests from `test_defaults.py` (#3223)Rowlando13before adoptionfa7f035
lines 1002–1012why, one step back1002 """Comprehensive check of default-value processing for arguments with1003 ``nargs``.10041005 .. hint::1006 An option-specific equivalent is available in1007 ``test_options.py::test_good_defaults_for_multiple``.10081009 A smoke test covering a single basic case is in1010 ``test_defaults.py::test_nargs_plus_multiple``.1011 """1012Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 1013why, one step back1013 @click.command()Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 1014why, one step back1014 @click.argument("a", type=int, **argument_params)Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 1015why, one step back1015 def cmd(a):Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 1016why, one step back1016 click.echo(repr(a), nl=False)Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 1017why, one step back1017Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 1018–1019why, one step back1018 result = runner.invoke(cmd, args)1019 assert result.output == repr(expected)Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 1020–1021why, one step back10201021Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 1022–1089why, one step back1022@pytest.mark.parametrize(1023 ("default", "message"),1024 [1025 # Non-iterables defaults.1026 ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."],1027 ["", "Error: Invalid value for '[A]...': Value must be an iterable."],1028 [True, "Error: Invalid value for '[A]...': Value must be an iterable."],1029 [False, "Error: Invalid value for '[A]...': Value must be an iterable."],1030 [12, "Error: Invalid value for '[A]...': Value must be an iterable."],1031 [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."],1032 # Generator default.1033 [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],1034 # Unset default.1035 [UNSET, "Error: Missing argument 'A...'."],1036 # Tuples defaults with wrong length.1037 [1038 tuple(),1039 "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",1040 ],1041 [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],1042 [1043 (1, 2, 3),1044 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",1045 ],1046 # Lists defaults with wrong length.1047 [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],1048 [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],1049 [1050 [1, 2, 3],1051 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",1052 ],1053 # Sets defaults with wrong length.1054 [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],1055 [1056 set([1]),1057 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",1058 ],1059 [1060 set([1, 2, 3]),1061 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",1062 ],1063 # Frozensets defaults with wrong length.1064 [1065 frozenset(),1066 "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",1067 ],1068 [1069 frozenset([1]),1070 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",1071 ],1072 [1073 frozenset([1, 2, 3]),1074 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",1075 ],1076 # Dictionaries defaults with wrong length.1077 [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],1078 [1079 {1: "a"},1080 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",1081 ],1082 [1083 {1: "a", 2: "b", 3: "c"},1084 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",1085 ],1086 ],1087)1088def test_bad_defaults_for_nargs(runner, default, message):1089 """Some defaults are not valid when nargs is set."""Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 1090why, one step back1090Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 1091–1094why, one step back1091 @click.command()1092 @click.argument("a", nargs=2, type=int, default=default)1093 def cmd(a):1094 click.echo(repr(a))Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
line 1095why, one step back1095Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 1096–1099why, one step back1096 result = runner.invoke(cmd, [])1097 assert message in result.stderr10981099Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 1100–1192why, one step back1100def test_multiple_param_decls_not_allowed(runner):1101 with pytest.raises(TypeError):11021103 @click.command()1104 @click.argument("x", click.Choice(["a", "b"]))1105 def copy(x):1106 click.echo(x)110711081109def test_multiple_not_allowed():1110 with pytest.raises(TypeError, match="multiple"):1111 click.Argument(["a"], multiple=True)111211131114def test_subcommand_help(runner):1115 @click.group()1116 @click.argument("name")1117 @click.argument("val")1118 @click.option("--opt")1119 @click.pass_context1120 def cli(ctx, name, val, opt):1121 ctx.obj = dict(name=name, val=val)11221123 @cli.command()1124 @click.pass_obj1125 def cmd(obj):1126 click.echo(f"CMD for {obj['name']} with value {obj['val']}")11271128 result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"])1129 assert not result.exception1130 assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output113111321133def test_nested_subcommand_help(runner):1134 @click.group()1135 @click.argument("arg1")1136 @click.option("--opt1")1137 def cli(arg1, opt1):1138 pass11391140 @cli.group()1141 @click.argument("arg2")1142 @click.option("--opt2")1143 def cmd(arg2, opt2):1144 pass11451146 @cmd.command()1147 def subcmd():1148 click.echo("subcommand")11491150 result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"])1151 assert not result.exception1152 assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output115311541155def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved():1156 class CustomArgument(click.Argument):1157 pass11581159 reusable_argument = click.argument("art", cls=CustomArgument)11601161 @click.command()1162 @reusable_argument1163 def foo(arg):1164 pass11651166 @click.command()1167 @reusable_argument1168 def bar(arg):1169 pass11701171 assert isinstance(foo.params[0], CustomArgument)1172 assert isinstance(bar.params[0], CustomArgument)117311741175@pytest.mark.parametrize(1176 "args_one,args_two",1177 [1178 (1179 ("aardvark",),1180 ("aardvark",),1181 ),1182 ],1183)1184def test_duplicate_names_warning(runner, args_one, args_two):1185 @click.command()1186 @click.argument(*args_one)1187 @click.argument(*args_two)1188 def cli(one, two):1189 pass11901191 with pytest.warns(UserWarning):1192 runner.invoke(cli, [])Ensure that `type_cast_value` never gets `UNSET` (#3090)Rowlando13before adoption8d4051e
lines 1193–1229why, one step back119311941195@pytest.mark.parametrize(1196 ("argument_kwargs", "pass_argv"),1197 (1198 # there is a large potential parameter space to explore here1199 # this is just a very small sample of it1200 ({}, ["myvalue"]),1201 ({"nargs": -1}, []),1202 ({"nargs": -1}, ["myvalue"]),1203 ({"default": None}, ["myvalue"]),1204 ({"required": False}, []),1205 ({"required": False}, ["myvalue"]),1206 ),1207)1208def test_argument_custom_class_can_override_type_cast_value_and_never_sees_unset(1209 runner, argument_kwargs, pass_argv1210):1211 """1212 Test that overriding type_cast_value is supported12131214 In particular, the argument is never passed an UNSET sentinel value.1215 """12161217 class CustomArgument(click.Argument):1218 def type_cast_value(self, ctx, value):1219 assert value is not UNSET1220 return value12211222 @click.command()1223 @click.argument("myarg", **argument_kwargs, cls=CustomArgument)1224 def cmd(myarg):1225 click.echo("ok")12261227 result = runner.invoke(cmd, pass_argv)1228 assert not result.exception1229 assert result.exit_code == 0