Skip to content
Myr

Deprecate a parameter name that is not a Python identifier

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Click 9.0 refuses such a name; warn a release ahead so the break can diffuse. Prepares the ground for #3827, as promised in pull/3827#issuecomment-5583963038.

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 6d5bac5 · Browse files · 6 files+804 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+804 added−8 removed

  • tests:+731 added−4 removed
  • other:+73 added−4 removed

6 files+804 added−8 removed

modified:docs/upgrade-guides.md+2 added
modified:src/click/core.py+69 added-4 removed
16 unmodified lines
17from functools import update_wrapper18from gettext import gettext as _19from gettext import ngettext20from itertools import repeat21from types import FrameType22from types import TracebackType2324from . import types25from ._utils import FLAG_NEEDS_VALUE
78 unmodified lines
104 """Write the final abort message to standard error."""105 echo(_("Aborted!"), file=sys.stderr)106107108def _outside_click_stacklevel() -> int:109 """Depth of the first stack frame outside Click.110111 .. versionadded:: 8.5.1112 """113 frame: FrameType | None = sys._getframe(1)114 level = 1115116 while frame is not None:117 module = frame.f_globals.get("__name__", "")118119 if module != "click" and not module.startswith("click."):120 return level121122 frame = frame.f_back123 level += 1124125 return level126127128def _format_deprecated_label(deprecated: bool | str) -> str:129 """Return the parenthesized deprecation label shown in help text."""130 label = _("deprecated").upper()131 if isinstance(deprecated, str):
2345 unmodified lines
2477 def _parse_decls(2478 self, decls: cabc.Sequence[str], expose_value: bool2479 ) -> tuple[str, list[str], list[str]]: ...24802481 def _check_name_is_identifier(self, name: str, decls: cabc.Sequence[str]) -> None:2482 """Warn about a name Click 9.0 will refuse.24832484 .. versionadded:: 8.5.12485 """2486 if name.isidentifier():2487 return24882489 import warnings24902491 warnings.warn(2492 f"{self.param_type_name.capitalize()} {list(decls)!r} uses {name!r}"2493 " as its name, which is not a valid Python identifier. This is"2494 " deprecated and will raise a TypeError in Click 9.0.",2495 DeprecationWarning,2496 stacklevel=_outside_click_stacklevel(),2497 )24982499 @property2500 def human_readable_name(self) -> str:2501 """Returns the human readable name of this parameter. This is the2502 same as the name for options, but the metavar for arguments.
808 unmodified lines
3311 if self.show_envvar and self.envvar is not None:3312 result += f" (env var: '{self.envvar}')"3313 return result33143315 def _check_name_is_normalized(self, name: str, decls: cabc.Sequence[str]) -> None:3316 """Warn about an explicit name Click 9.0 will spell differently.33173318 .. versionadded:: 8.5.13319 """3320 normalized = name.lower()33213322 if normalized == name:3323 return33243325 import warnings33263327 warnings.warn(3328 f"Option {list(decls)!r} uses {name!r} as its name. Click 9.0"3329 f" lower cases an explicit name like any other declaration, naming"3330 f" {normalized!r} instead.",3331 DeprecationWarning,3332 stacklevel=_outside_click_stacklevel(),3333 )33343335 def _parse_decls(3336 self, decls: cabc.Sequence[str], expose_value: bool3337 ) -> tuple[str, list[str], list[str]]:3338 opts = []3339 secondary_opts = []3340 name = None3341 explicit_name = None3342 possible_names = []33433344 for decl in decls:3345 if decl.isidentifier():3346 if name is not None:3347 raise TypeError(_("Name '{name}' defined twice").format(name=name))3288 name = decl3348 name = explicit_name = decl3349 else:3350 split_char = ";" if decl[:1] == "/" else "/"3351 if split_char in decl:3352 first, second = decl.split(split_char, 1)
17 unmodified lines
33703371 if name is None and possible_names:3372 possible_names.sort(key=lambda x: -len(x[0])) # group long options first3373 name = possible_names[0][1].replace("-", "_").lower()3314 if not name.isidentifier():3315 name = None33743317 if name is None:3375 if name is None or not name.isidentifier():3376 if not expose_value:3377 self._check_name_is_identifier(name or "", decls)3378 return "", opts, secondary_opts33793380 raise TypeError(3381 _(3382 "Could not determine name for option with declarations {decls!r}"3383 ).format(decls=decls)
7 unmodified lines
3391 " you mean to pass '--{name}'?"3392 ).format(name=name)3393 )33943395 if explicit_name is not None:3396 self._check_name_is_normalized(explicit_name, decls)33973398 return name, opts, secondary_opts33993400 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3401 if self.multiple:
439 unmodified lines
3841 self, decls: cabc.Sequence[str], expose_value: bool3842 ) -> tuple[str, list[str], list[str]]:3843 if not decls:3844 if not expose_value:3845 self._check_name_is_identifier("", decls)3846 return "", [], []3847 raise TypeError("Argument is marked as exposed, but does not have a name.")3848 if len(decls) == 1:3849 name = arg = decls[0]
4 unmodified lines
3854 "Arguments take exactly one parameter declaration, got"3855 " {length}: {decls}."3856 ).format(length=len(decls), decls=decls)3857 )3858 self._check_name_is_identifier(name, decls)3859 return name, [arg], []38603861 def get_usage_pieces(self, ctx: Context) -> list[str]:3862 return [self.make_metavar(ctx)]
38 unmodified lines
modified:tests/test_arguments.py+372 added
1import itertools2import sys3import unicodedata4import warnings5from unittest import mock67import pytest8from test_options import ENV_NAMES_ARE_CASE_INSENSITIVE910import click11from click._utils import UNSET12
69 unmodified lines
82 assert result.exit_code == 283 assert "Got unexpected extra argument (bar)" in result.output848586@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]133134# Declarations covering every shape the naming transform accepts.135NAME_SWEEP_DECLS = [136 "",137 "-",138 "--",139 "---",140 "0",141 "--0",142 "0-file",143 "--0-file",144 "foo.bar",145 "--foo.bar",146 "foo bar",147 "x",148 "--x",149 "X_Y",150 "--X-Y",151]152153154@pytest.mark.parametrize("count", [1, 2])155@pytest.mark.parametrize("expose_value", [True, False])156def test_parameter_name_is_an_identifier_or_deprecated(count, expose_value):157 built = 0158159 for decls in itertools.product(NAME_SWEEP_DECLS, repeat=count):160 for cls in (click.Option, click.Argument):161 with warnings.catch_warnings(record=True) as caught:162 warnings.simplefilter("always")163164 try:165 param = cls(list(decls), expose_value=expose_value)166 except (TypeError, ValueError):167 continue168169 built += 1170171 if param.name.isidentifier():172 continue173174 assert any(issubclass(w.category, DeprecationWarning) for w in caught), (175 f"{cls.__name__}({list(decls)!r}, expose_value={expose_value})"176 f" named its parameter {param.name!r} without a warning"177 )178179 assert built, "the sweep built no parameter, so it proves nothing"180181182def test_argument_requires_its_one_declaration():183 """An exposed argument with no declaration is refused, an unexposed one warns."""184 with pytest.raises(TypeError, match="does not have a name"):185 click.Argument([])186187 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):188 assert click.Argument([], expose_value=False).name == ""189190191def test_argument_name_check_applies_when_not_exposed():192 """An unexposed argument keeps the name, and says Click 9.0 will refuse it."""193 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):194 assert click.Argument(["0foo"], expose_value=False).name == "0foo"195196197def test_argument_metavar_renders_what_a_declaration_may_not(runner):198 """``metavar`` carries a display the declaration is no longer allowed to.199200 An argument takes exactly one declaration and has no explicit-name channel,201 so a display such as ``0FOO`` is reached by naming the parameter separately202 and passing the display as ``metavar``.203 """204 seen = []205206 def record(ctx, param, value):207 seen.append(value)208209 @click.command()210 @click.argument("zero_foo", expose_value=False, callback=record, metavar="0FOO")211 def cmd(**kwargs):212 click.echo(repr(kwargs))213214 assert cmd.params[0].name == "zero_foo"215216 result = runner.invoke(cmd, ["value"])217 assert not result.exception218 assert result.output == "{}\n"219 assert seen == ["value"]220221 result = runner.invoke(cmd, ["--help"])222 assert "0FOO" in result.output223224225@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)226@pytest.mark.parametrize(("decl", "expect"), UNICODE_CASE_DECLS)227def test_parameter_name_unicode_case_transform(cls, form, decl, expect):228 """``str.lower()`` is neither one-to-one nor length-preserving."""229 assert cls([form.format(decl=decl)]).name == expect230231232@pytest.mark.parametrize(("decl", "expect"), UNICODE_CASE_DECLS)233def test_option_explicit_name_keeps_its_case(decl, expect):234 """An explicit name is kept as spelled, where Click 9.0 transforms it."""235 if not decl.isidentifier():236 assert click.Option(["--x", decl]).name == "x"237 return238239 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):240 assert click.Option(["--x", decl]).name == decl241242 assert decl.lower() == expect243244245@pytest.mark.parametrize(246 ("arg_decl", "opt_decl", "expect"),247 [248 pytest.param("a-b-c", "--a-b-c", "a_b_c", id="interior-singles"),249 pytest.param("a-----b", "--a-----b", "a_____b", id="interior-run"),250 pytest.param("a--", "--a--", "a__", id="trailing"),251 pytest.param("-a-", "---a-", "_a_", id="leading-survives-the-prefix"),252 pytest.param("-a----b--", "---a----b--", "_a____b__", id="everywhere"),253 pytest.param("--", "----", "__", id="dashes-only"),254 pytest.param("_-_", "--_-_", "___", id="around-an-underscore"),255 ],256)257def test_parameter_name_keeps_every_dash_past_the_prefix(arg_decl, opt_decl, expect):258 """Only an option's leading dashes are considered a prefix."""259 assert click.Argument([arg_decl]).name == expect260 assert click.Option([opt_decl], is_flag=True).name == expect261262263@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)264@pytest.mark.parametrize(265 "decl",266 [267 pytest.param("0foo", id="leading-digit"),268 pytest.param("0", id="digit-only"),269 pytest.param("foo.bar", id="dot"),270 pytest.param("foo bar", id="space"),271 pytest.param("\u0663foo", id="leading-arabic-indic-digit"),272 # Separators that read as a hyphen but are not the one replaced.273 pytest.param("foo\N{NON-BREAKING HYPHEN}bar", id="non-breaking-hyphen"),274 pytest.param("foo\u2013bar", id="en-dash"),275 pytest.param("foo\u2212bar", id="minus-sign"),276 # Characters that occupy no width at all.277 pytest.param("a\N{ZERO WIDTH SPACE}b", id="zero-width-space"),278 pytest.param("a\N{SOFT HYPHEN}b", id="soft-hyphen"),279 pytest.param("a\N{RIGHT-TO-LEFT OVERRIDE}b", id="right-to-left-override"),280 # Even nothing at all, which reaches an option as a bare ``--``.281 pytest.param("", id="empty"),282 ],283)284def test_parameter_name_not_an_identifier_is_deprecated(cls, form, decl):285 """Click 9.0 refuses every one of these; 8.5 keeps them and says so.286287 An exposed option is the exception, since it already refuses them.288 """289 spec = form.format(decl=decl)290291 if cls is click.Option:292 with pytest.raises(TypeError, match="Could not determine name"):293 cls([spec])294 return295296 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):297 param = cls([spec])298299 assert not param.name.isidentifier()300301302@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)303@pytest.mark.parametrize(304 "char",305 [306 pytest.param("\N{ZERO WIDTH JOINER}", id="zero-width-joiner"),307 pytest.param("\N{ZERO WIDTH NON-JOINER}", id="zero-width-non-joiner"),308 ],309)310def test_parameter_name_identifier_check_follows_the_unicode_table(cls, form, char):311 """Python 3.13 allows unicode zero-width joiner and non-joiner in identifiers."""312 name = f"a{char}b"313 assert name.isidentifier() == (sys.version_info >= (3, 13))314 decl = form.format(decl=name)315316 if name.isidentifier():317 assert cls([decl]).name == name318 return319320 if cls is click.Option:321 with pytest.raises(TypeError, match="Could not determine name"):322 cls([decl])323 return324325 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):326 assert cls([decl]).name == name327328329@pytest.mark.parametrize(330 ("decorator", "decl", "argv"),331 [332 pytest.param(click.argument, "fi", ["value"], id="argument"),333 pytest.param(click.option, "--fi", ["--fi", "value"], id="option"),334 ],335)336def test_parameter_name_is_not_nfkc_normalized(runner, decorator, decl, argv):337 """``str.isidentifier()`` is not the test for "can be a parameter name".338339 Python normalizes an identifier written in source to NFKC, so the ligature340 "fi" compiles to the two letters. ``_parse_decls`` runs no normalization,341 so the name keeps the ligature and only ``**kwargs`` can carry it.342 """343344 @click.command()345 @decorator(decl)346 def cmd(**kwargs):347 click.echo(repr(kwargs))348349 name = cmd.params[0].name350 assert name == "fi"351 assert name.isidentifier()352 assert unicodedata.normalize("NFKC", name) == "fi"353354 result = runner.invoke(cmd, argv)355 assert not result.exception356 assert result.output == "{'fi': 'value'}\n"357358359def test_argument_name_keeps_its_normalization_form(runner):360 """A composed and a decomposed declaration are two distinct arguments.361362 Both render as ``café`` and both are valid identifiers, so the pair363 coexists on one command with nothing on screen to tell them apart.364 """365 decomposed = "cafe\N{COMBINING ACUTE ACCENT}"366 composed = unicodedata.normalize("NFC", decomposed)367368 @click.command()369 @click.argument(composed)370 @click.argument(decomposed)371 def cmd(**kwargs):372 click.echo(repr(sorted(kwargs)))373374 assert [p.name for p in cmd.params] == [composed, decomposed]375376 result = runner.invoke(cmd, ["one", "two"])377 assert not result.exception378 assert result.output == f"['{decomposed}', '{composed}']\n"379380381def test_argument_name_case_transform_can_collide(runner):382383 @click.command()384 @click.argument("Foo-Bar")385 @click.argument("foo_bar")386 def cmd(**kwargs):387 click.echo(repr(kwargs))388389 with pytest.warns(UserWarning, match="is used by an argument"):390 result = runner.invoke(cmd, ["one", "two"], catch_exceptions=False)391392 assert result.output == "{'foo_bar': 'two'}\n"393394395def test_argument_name_can_collide_with_an_option(runner):396397 @click.command()398 @click.option("--foo-bar")399 @click.argument("Foo-Bar", required=False)400 def cmd(**kwargs):401 click.echo(repr(kwargs))402403 assert [p.name for p in cmd.params] == ["foo_bar", "foo_bar"]404405 with pytest.warns(UserWarning, match="is used by an argument"):406 result = runner.invoke(407 cmd, ["--foo-bar", "from-option", "from-argument"], catch_exceptions=False408 )409410 assert result.output == "{'foo_bar': 'from-argument'}\n"411412413def test_argument_has_no_auto_envvar(runner):414 """An argument reads only the envvars it names, never a derived one."""415416 @click.command()417 @click.argument("Foo-Bar", required=False)418 def cmd(**kwargs):419 click.echo(repr(kwargs))420421 result = runner.invoke(422 cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}423 )424 assert not result.exception425 assert result.output == "{'foo_bar': None}\n"426427428@pytest.mark.parametrize(429 ("env", "expect"),430 [431 pytest.param({"ArG": "foo"}, "'foo'", id="exact"),432 pytest.param({"ARG": "foo"}, "None", id="upper"),433 pytest.param({"arg": "foo"}, "None", id="lower"),434 ],435)436def test_argument_explicit_envvar_case_sensitivity(runner, env, expect):437 """An argument matches its named envvar exactly, like an option does.438439 And loses the distinction on Windows, like an option does.440 """441442 @click.command()443 @click.argument("arg", envvar="ArG", required=False)444 def cmd(arg):445 click.echo(repr(arg))446447 result = runner.invoke(cmd, [], env=env)448 assert not result.exception449 if ENV_NAMES_ARE_CASE_INSENSITIVE:450 expect = "'foo'"451 assert result.output == f"{expect}\n"452453454def test_bytes_args(runner, monkeypatch):455 @click.command()456 @click.argument("arg")457 def from_bytes(arg):
655 unmodified lines
modified:tests/test_deprecations.py+97 added
1import importlib.metadata2import warnings34import pytest56import click
64 unmodified lines
71def test_isolated_filesystem_deprecated(runner):72 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):73 with runner.isolated_filesystem():74 pass757677@pytest.mark.parametrize(78 "make_param",79 [80 pytest.param(lambda: click.Argument(["0foo"]), id="argument-leading-digit"),81 pytest.param(lambda: click.Argument(["foo.bar"]), id="argument-dot"),82 pytest.param(lambda: click.Argument(["foo bar"]), id="argument-space"),83 pytest.param(lambda: click.Argument([""]), id="argument-empty-decl"),84 pytest.param(85 lambda: click.Argument(["0foo"], expose_value=False),86 id="argument-unexposed",87 ),88 pytest.param(89 lambda: click.Argument([], expose_value=False),90 id="argument-no-decl",91 ),92 pytest.param(93 lambda: click.Option(["--0foo"], expose_value=False),94 id="option-unexposed",95 ),96 pytest.param(97 lambda: click.Option([], expose_value=False),98 id="option-no-decl",99 ),100 ],101)102def test_non_identifier_name_deprecated(make_param):103 """Click 9.0 refuses a name that is not a Python identifier."""104 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):105 make_param()106107108@pytest.mark.parametrize(109 "make_param",110 [111 pytest.param(lambda: click.Argument(["foo-bar"]), id="argument-hyphen"),112 pytest.param(lambda: click.Argument(["Foo_Bar"]), id="argument-case"),113 pytest.param(lambda: click.Option(["--foo-bar"]), id="option-hyphen"),114 pytest.param(lambda: click.Option(["--from"]), id="option-keyword"),115 pytest.param(116 lambda: click.Option(["--0foo", "zero_foo"]), id="option-explicit-name"117 ),118 ],119)120def test_identifier_name_not_deprecated(recwarn, make_param):121 """A usable name keeps working, and says nothing."""122 make_param()123 assert [w for w in recwarn if issubclass(w.category, DeprecationWarning)] == []124125126def test_non_identifier_option_name_still_raises():127 """An exposed option already refuses such a name, and keeps refusing it."""128 with pytest.raises(TypeError, match="Could not determine name"):129 click.Option(["--0foo"])130131132@pytest.mark.parametrize(133 ("decl", "expect"),134 [135 pytest.param("Foo_Bar", "foo_bar", id="mixed-case"),136 pytest.param("X_Y", "x_y", id="upper-case"),137 pytest.param("ΟΔΟΣ", "οδος", id="final-sigma"),138 pytest.param("\N{KELVIN SIGN}", "k", id="kelvin-sign"),139 ],140)141def test_unnormalized_explicit_name_deprecated(decl, expect):142 """Click 9.0 lower cases an explicit name like any other declaration."""143 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):144 param = click.Option(["--x", decl])145146 assert param.name == decl147 assert decl.lower() == expect148149150@pytest.mark.parametrize(151 "decls",152 [153 pytest.param(["--x", "foo_bar"], id="already-lower"),154 pytest.param(["--x", "_from"], id="leading-underscore"),155 pytest.param(["--Foo-Bar"], id="derived-not-explicit"),156 pytest.param(["--x", "café"], id="lower-case-non-ascii"),157 ],158)159def test_normalized_explicit_name_not_deprecated(recwarn, decls):160 """A name already spelled the way 9.0 spells it says nothing."""161 click.Option(decls)162 assert [w for w in recwarn if issubclass(w.category, DeprecationWarning)] == []163164165def test_unnormalized_name_on_a_refused_option_is_silent():166 """An option that cannot be built at all warns about nothing."""167 with pytest.raises(TypeError, match="No options defined"):168 with warnings.catch_warnings():169 warnings.simplefilter("error", DeprecationWarning)170 click.Option(["Foo_Bar"])
modified:tests/test_options.py+262 added-4 removed
1 unmodified line
2import os3import re4import sys5import tempfile6import unicodedata7import warnings8from contextlib import nullcontext9from typing import Literal1011if sys.version_info < (3, 11):12 enum.StrEnum = enum.Enum # type: ignore[assignment]1312import pytest1314import click15from click import Option16from click import UNPROCESSED15import pytest16from click import UNPROCESSED, Option17from click._utils import UNSET18from click.testing import CliRunner1920
791 unmodified lines
812 assert not result.exception813 assert result.output == "foo\n"814815816# CPython upper-cases every key of ``os.environ`` when ``os.name == "nt"``,817# see ``os._createenviron``. ``CliRunner`` writes the ``env`` mapping through818# ``os.environ`` and ``Parameter.resolve_envvar_value`` reads it back the same819# way, so on Windows a variable answers to every spelling of its name and820# elsewhere to exactly one. Both halves are asserted rather than skipped: the821# difference is the behaviour being pinned. See pallets/click#2483.822ENV_NAMES_ARE_CASE_INSENSITIVE = sys.platform == "win32"823824825def test_auto_envvar_uses_the_transformed_name(runner):826 """The auto envvar is built from the name, which the transform lower-cased."""827828 @click.command()829 @click.option("--Foo-Bar")830 def cmd(foo_bar):831 click.echo(foo_bar)832833 result = runner.invoke(834 cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}835 )836 assert not result.exception837 assert result.output == "foo\n"838839840def test_auto_envvar_ignores_decl_case(runner):841 """The case written in the declaration never reaches the auto envvar."""842843 @click.command()844 @click.option("--Foo-Bar")845 def cmd(foo_bar):846 click.echo(repr(foo_bar))847848 result = runner.invoke(849 cmd, [], auto_envvar_prefix="TEST", env={"TEST_Foo_Bar": "foo"}850 )851 assert not result.exception852 expect = "'foo'" if ENV_NAMES_ARE_CASE_INSENSITIVE else "None"853 assert result.output == f"{expect}\n"854855856def test_auto_envvar_prefix_is_upper_cased(runner):857 """A lower-case prefix reaches an upper-case variable, and only that one."""858859 @click.command()860 @click.option("--flag/--no-flag")861 def cmd(flag):862 click.echo(repr(flag))863864 result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"YO_FLAG": "1"})865 assert not result.exception866 assert result.output == "True\n"867868 result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"yo_FLAG": "1"})869 assert not result.exception870 assert result.output == f"{ENV_NAMES_ARE_CASE_INSENSITIVE}\n"871872873def test_auto_envvar_flattens_name_case(runner):874 """Two names differing only by case share one auto envvar."""875 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):876877 @click.command()878 @click.option("--foo-bar")879 @click.option("--other", "Foo_Bar")880 def cmd(**kwargs):881 click.echo(repr(sorted(kwargs.items())))882883 assert [p.name for p in cmd.params if p.name] == ["foo_bar", "Foo_Bar"]884885 result = runner.invoke(886 cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}887 )888 assert not result.exception889 assert result.output == "[('Foo_Bar', 'foo'), ('foo_bar', 'foo')]\n"890891892def test_auto_envvar_upper_can_change_length(runner):893 """Deriving the envvar is not the inverse of deriving the name."""894895 @click.command()896 @click.option("--ẞ")897 def cmd(**kwargs):898 click.echo(repr(kwargs))899900 result = runner.invoke(cmd, [], auto_envvar_prefix="TEST", env={"TEST_SS": "foo"})901 assert not result.exception902 assert result.output == "{'ß': 'foo'}\n"903904905@pytest.mark.parametrize(906 ("env", "expect"),907 [908 pytest.param({"ArG": "foo"}, "'foo'", id="exact"),909 pytest.param({"ARG": "foo"}, "None", id="upper"),910 pytest.param({"arg": "foo"}, "None", id="lower"),911 ],912)913def test_explicit_envvar_case_sensitivity(runner, env, expect):914 """An explicitly named envvar keeps the case it was registered with."""915916 @click.command()917 @click.option("--arg", envvar="ArG")918 def cmd(arg):919 click.echo(repr(arg))920921 result = runner.invoke(cmd, [], env=env)922 assert not result.exception923 if ENV_NAMES_ARE_CASE_INSENSITIVE:924 expect = "'foo'"925 assert result.output == f"{expect}\n"926927928@pytest.mark.parametrize("name", ("FlAg", "sUper"))929def test_explicit_envvar_list_keeps_each_spelling(runner, name):930 """Every name of an envvar list is matched with its own case."""931932 @click.command()933 @click.option("--flag/--no-flag", envvar=["FlAg", "sUper"])934 def cmd(flag):935 click.echo(repr(flag))936937 result = runner.invoke(cmd, [], env={name: "1"})938 assert not result.exception939 assert result.output == "True\n"940941942def test_nargs_envvar(runner):943 @click.command()944 @click.option("--arg", nargs=2)945 def cmd(arg):
452 unmodified lines
1398 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),1399 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),1400 (["--from", "-f", "_from"], "_from"),1401 (["--return", "-r", "_ret"], "_ret"),1402 # A name derived from an option string is lower-cased.1403 (["--Foo-Bar"], "foo_bar"),1404 (["--FOO-BAR", "-F"], "foo_bar"),1405 # An identifier declaration goes through the same transform.1406 (["--foo-bar", "-f", "explicit_name"], "explicit_name"),1407 # Underscores survive, and every dash past the prefix becomes one.1408 (["--foo__bar"], "foo__bar"),1409 (["--foo--bar"], "foo__bar"),1410 (["--_foo"], "_foo"),1411 (["--__foo"], "__foo"),1412 (["---foo"], "_foo"),1413 (["-_"], "_"),1414 # A digit is only refused in the leading position.1415 (["--foo-0"], "foo_0"),1416 ],1417)1418def test_option_names(runner, option_args, expected):1419 @click.command()
8 unmodified lines
1428 result = runner.invoke(cmd, [form])1429 assert result.output == "True\n"143014311432def test_option_name_case_transform_can_collide(runner):1433 """Two declarations that differ can transform to one name, with no warning."""14341435 @click.command()1436 @click.option("--\N{KELVIN SIGN}")1437 @click.option("--k")1438 def cmd(**kwargs):1439 click.echo(repr(kwargs))14401441 assert [p.name for p in cmd.params] == ["k", "k"]14421443 result = runner.invoke(cmd, ["--\N{KELVIN SIGN}", "kelvin", "--k", "ascii"])1444 assert not result.exception1445 assert result.output == "{'k': 'ascii'}\n"144614471448def test_option_name_case_variants_share_one_parameter(runner):1449 """Case variants of one option collapse onto a single parameter."""14501451 @click.command()1452 @click.option("--foo-bar")1453 @click.option("--Foo-Bar")1454 @click.option("--FOO-BAR")1455 def cmd(**kwargs):1456 click.echo(repr(kwargs))14571458 assert [p.name for p in cmd.params] == ["foo_bar"] * 314591460 with warnings.catch_warnings(record=True) as caught:1461 warnings.simplefilter("always")1462 result = runner.invoke(cmd, ["--help"], catch_exceptions=False)14631464 assert not [w for w in caught if issubclass(w.category, UserWarning)]1465 for spelling in ("--foo-bar", "--Foo-Bar", "--FOO-BAR"):1466 assert spelling in result.output14671468 for spelling, value in (("--foo-bar", "a"), ("--Foo-Bar", "b"), ("--FOO-BAR", "c")):1469 result = runner.invoke(cmd, [spelling, value])1470 assert not result.exception1471 assert result.output == f"{{'foo_bar': {value!r}}}\n"14721473 # Sharing one slot, the last spelling on the command line wins.1474 result = runner.invoke(cmd, ["--foo-bar", "a", "--FOO-BAR", "c"])1475 assert result.output == "{'foo_bar': 'c'}\n"147614771478def test_option_name_keeps_its_normalization_form(runner):1479 """A composed and a decomposed declaration are two distinct parameters."""1480 decomposed = "cafe\N{COMBINING ACUTE ACCENT}"1481 composed = unicodedata.normalize("NFC", decomposed)14821483 @click.command()1484 @click.option(f"--{composed}")1485 @click.option(f"--{decomposed}")1486 def cmd(**kwargs):1487 click.echo(repr(sorted(kwargs)))14881489 assert [p.name for p in cmd.params] == [composed, decomposed]14901491 result = runner.invoke(cmd, [])1492 assert not result.exception1493 assert result.output == f"['{decomposed}', '{composed}']\n"149414951496def test_option_name_must_be_an_identifier():1497 """A short option is the one refused shape an argument cannot be written as."""1498 with pytest.raises(TypeError, match="Could not determine name"):1499 click.Option(["-0"])150015011502def test_option_prompt_still_guards_against_a_nameless_option():1503 """An unexposed option can still be named ``""``, which ``prompt=True`` refuses."""1504 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):1505 with pytest.raises(TypeError, match="'name' is required with 'prompt=True'"):1506 click.Option(["--0-file"], expose_value=False, prompt=True)150715081509def test_option_name_check_applies_when_not_exposed():1510 """An unexposed option is named ``""``, and says Click 9.0 will refuse it."""1511 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):1512 assert click.Option(["--0foo"], expose_value=False).name == ""151315141515def test_option_explicit_name_carries_a_refused_declaration(runner):1516 """An explicit name reaches a declaration the transform cannot name."""1517 seen = []15181519 def record(ctx, param, value):1520 seen.append(value)15211522 @click.command()1523 @click.option("--0foo", "zero_foo", expose_value=False, callback=record)1524 def cmd(**kwargs):1525 click.echo(repr(kwargs))15261527 assert cmd.params[0].name == "zero_foo"15281529 result = runner.invoke(cmd, ["--0foo", "value"])1530 assert not result.exception1531 assert result.output == "{}\n"1532 assert seen == ["value"]153315341535def test_option_name_may_be_a_python_keyword(runner):1536 """``str.isidentifier()`` accepts a keyword, so the check lets one through."""15371538 @click.command()1539 @click.option("--from")1540 def cmd(**kwargs):1541 click.echo(repr(kwargs))15421543 assert cmd.params[0].name == "from"15441545 result = runner.invoke(cmd, ["--from", "here"])1546 assert not result.exception1547 assert result.output == "{'from': 'here'}\n"154815491550def test_flag_duplicate_names(runner):1551 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):1552 click.Option(["--foo/--foo"], default=False)1553
2360 unmodified lines
modified:CHANGES.md+2 added
1## Version 8.5.123Unreleased45- A parameter name that is not a valid Python identifier is deprecated and6 raises `TypeError` in Click 9.0. {pr}`3827`7- Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`8- A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,9 or while it exits, no longer escapes as an unhandled traceback. The command still10 exits with the intended code; only the message may be lost. {issue}`3802`
1669 unmodified lines