Skip to content
Myr

Deprecate a parameter name that Click 9.0 will refuse or lower case

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

Prepares the ground for #3827

authored by Kevin Deldycke · committed by Kevin Deldycke · parent a59f7c6 · Browse files · 6 files+871 added−5 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+871 added−5 removed

  • tests:+774 added−1 removed
  • other:+97 added−4 removed

6 files+871 added−5 removed

modified:docs/upgrade-guides.md+2 added
11 unmodified lines
1213### Deprecations1415For each deprecation, provide a brief explanation, and direct users to new function / class if available.16- A parameter name that is not a valid Python identifier, or that is a [Python keyword](https://docs.python.org/3/reference/lexical_analysis.html#keywords), is deprecated and raises `TypeError` in 9.0. [`str.isidentifier()`](https://docs.python.org/3/library/stdtypes.html#str.isidentifier) decides the first case, so `click.argument("0foo")` fails it. It accepts a keyword, so `click.option("--from")` names a parameter `from`, which no callback can declare. [Soft keywords](https://docs.python.org/3/reference/lexical_analysis.html#soft-keywords) such as `match` and `type` are contextual and unaffected, and `--True` and `--None` lower case out of the keyword set. To migrate, pass an explicit name (`click.option("--from", "source")`, `click.option("--0-file", "zero_file")`). An argument takes one declaration and has no explicit-name channel, so rename it and pass `metavar` to keep its old display (`click.argument("zero_file", metavar="0-FILE")`). See [#3827](https://github.com/pallets/click/pull/3827) and [#3866](https://github.com/pallets/click/pull/3866).17- An option name written as a Python identifier is deprecated when it is not already lower cased: `click.option("--x", "Foo_Bar")` names `foo_bar` rather than `Foo_Bar`. To migrate, spell the name the way the callback declares it. See [#3827](https://github.com/pallets/click/pull/3827).18- `CliRunner.isolated_filesystem()` is deprecated and will be removed in Click 9.0. The helper predates Python 3 and modern pytest, and it relies on `os.chdir`, which mutates process-global state and is therefore not thread-safe. Replace it with a temporary directory (`tempfile.TemporaryDirectory`, or pytest's `tmp_path` fixture) and pass absolute paths to the command instead of relying on the current working directory. To run commands in parallel, use process-based isolation (such as `pytest-xdist`) rather than threads, since `CliRunner.invoke()` also redirects the process-global standard streams and other interpreter-wide state. See [#3700](https://github.com/pallets/click/issues/3700), [#3501](https://github.com/pallets/click/issues/3501) and the [testing guide](testing.md#running-tests-in-parallel).1920### Removals with prior deprecation21
15 unmodified lines
modified:src/click/core.py+90 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.6.0112 """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):
2346 unmodified lines
2478 def _parse_decls(2479 self, decls: cabc.Sequence[str], expose_value: bool2480 ) -> tuple[str, list[str], list[str]]: ...24812482 def _check_name_is_usable(self, name: str, decls: cabc.Sequence[str]) -> None:2483 """Warn about a name Click 9.0 will refuse.24842485 A name is refused for one of two reasons, and never for both: it is not2486 an identifier (``0-file``), or it is a keyword (``from``).2487 ``str.isidentifier`` accepts a keyword, so ``--from`` names a parameter2488 ``from`` today. No callback can declare that, which leaves the value2489 reachable through ``**kwargs`` alone.24902491 Soft keywords such as ``match`` and ``type`` are contextual and name a2492 parameter fine, so :func:`keyword.iskeyword` passes them.24932494 Both imports are local because neither :mod:`keyword` nor2495 :mod:`warnings` is on the allow-list ``tests/test_imports.py`` holds2496 Click's import footprint to.24972498 .. versionadded:: 8.6.02499 """2500 import keyword25012502 if keyword.iskeyword(name):2503 reason = "which is a Python keyword"2504 elif not name.isidentifier():2505 reason = "which is not a valid Python identifier"2506 else:2507 return25082509 import warnings25102511 warnings.warn(2512 f"{self.param_type_name.capitalize()} {list(decls)!r} uses {name!r}"2513 f" as its name, {reason}. This is deprecated and will raise a"2514 " TypeError in Click 9.0.",2515 DeprecationWarning,2516 stacklevel=_outside_click_stacklevel(),2517 )25182519 @property2520 def human_readable_name(self) -> str:2521 """Returns the human readable name of this parameter. This is the2522 same as the name for options, but the metavar for arguments.
808 unmodified lines
3331 if self.show_envvar and self.envvar is not None:3332 result += f" (env var: '{self.envvar}')"3333 return result33343335 def _check_name_is_normalized(self, name: str, decls: cabc.Sequence[str]) -> None:3336 """Warn about an explicit name Click 9.0 will spell differently.33373338 .. versionadded:: 8.6.03339 """3340 normalized = name.lower()33413342 if normalized == name:3343 return33443345 import warnings33463347 warnings.warn(3348 f"Option {list(decls)!r} uses {name!r} as its name. Click 9.0"3349 f" lower cases an explicit name like any other declaration, naming"3350 f" {normalized!r} instead.",3351 DeprecationWarning,3352 stacklevel=_outside_click_stacklevel(),3353 )33543355 def _parse_decls(3356 self, decls: cabc.Sequence[str], expose_value: bool3357 ) -> tuple[str, list[str], list[str]]:3358 opts = []3359 secondary_opts = []3360 name = None3361 explicit_name = None3362 possible_names = []33633364 for decl in decls:3365 if decl.isidentifier():3366 if name is not None:3367 raise TypeError(_("Name '{name}' defined twice").format(name=name))3289 name = decl3368 name = explicit_name = decl3369 else:3370 split_char = ";" if decl[:1] == "/" else "/"3371 if split_char in decl:3372 first, second = decl.split(split_char, 1)
17 unmodified lines
33903391 if name is None and possible_names:3392 possible_names.sort(key=lambda x: -len(x[0])) # group long options first3393 name = possible_names[0][1].replace("-", "_").lower()3315 if not name.isidentifier():3316 name = None33943318 if name is None:3395 if name is None or not name.isidentifier():3396 if not expose_value:3397 self._check_name_is_usable(name or "", decls)3398 return "", opts, secondary_opts33993400 raise TypeError(3401 _(3402 "Could not determine name for option with declarations {decls!r}"3403 ).format(decls=decls)
7 unmodified lines
3411 " you mean to pass '--{name}'?"3412 ).format(name=name)3413 )34143415 if explicit_name is not None:3416 self._check_name_is_normalized(explicit_name, decls)34173418 self._check_name_is_usable(name, decls)34193420 return name, opts, secondary_opts34213422 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3423 if self.multiple:
439 unmodified lines
3863 self, decls: cabc.Sequence[str], expose_value: bool3864 ) -> tuple[str, list[str], list[str]]:3865 if not decls:3866 if not expose_value:3867 self._check_name_is_usable("", decls)3868 return "", [], []3869 raise TypeError("Argument is marked as exposed, but does not have a name.")3870 if len(decls) == 1:3871 name = arg = decls[0]
4 unmodified lines
3876 "Arguments take exactly one parameter declaration, got"3877 " {length}: {decls}."3878 ).format(length=len(decls), decls=decls)3879 )3880 self._check_name_is_usable(name, decls)3881 return name, [arg], []38823883 def get_usage_pieces(self, ctx: Context) -> list[str]:3884 return [self.make_metavar(ctx)]
45 unmodified lines
modified:tests/test_arguments.py+366 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]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"446447448def test_bytes_args(runner, monkeypatch):449 @click.command()450 @click.argument("arg")451 def from_bytes(arg):
748 unmodified lines
modified:tests/test_deprecations.py+146 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", "match"),79 [80 pytest.param(81 lambda: click.Argument(["0foo"]),82 "not a valid Python identifier",83 id="argument-leading-digit",84 ),85 pytest.param(86 lambda: click.Argument(["foo.bar"]),87 "not a valid Python identifier",88 id="argument-dot",89 ),90 pytest.param(91 lambda: click.Argument(["foo bar"]),92 "not a valid Python identifier",93 id="argument-space",94 ),95 pytest.param(96 lambda: click.Argument([""]),97 "not a valid Python identifier",98 id="argument-empty-decl",99 ),100 pytest.param(101 lambda: click.Argument(["0foo"], expose_value=False),102 "not a valid Python identifier",103 id="argument-unexposed",104 ),105 pytest.param(106 lambda: click.Argument([], expose_value=False),107 "not a valid Python identifier",108 id="argument-no-decl",109 ),110 pytest.param(111 lambda: click.Option(["--0foo"], expose_value=False),112 "not a valid Python identifier",113 id="option-unexposed",114 ),115 pytest.param(116 lambda: click.Option([], expose_value=False),117 "not a valid Python identifier",118 id="option-no-decl",119 ),120 # A keyword is an identifier too, so this rule alone reports it.121 pytest.param(122 lambda: click.Option(["--from"]),123 "is a Python keyword",124 id="option-from",125 ),126 pytest.param(127 lambda: click.Option(["--import"]),128 "is a Python keyword",129 id="option-import",130 ),131 pytest.param(132 lambda: click.Argument(["class"]),133 "is a Python keyword",134 id="argument-class",135 ),136 ],137)138def test_unusable_name_deprecated(make_param, match):139 """A name Click 9.0 refuses reports which of its two rules it broke."""140 with pytest.warns(DeprecationWarning, match=match):141 make_param()142143144@pytest.mark.parametrize(145 "make_param",146 [147 pytest.param(lambda: click.Argument(["foo-bar"]), id="argument-hyphen"),148 pytest.param(lambda: click.Argument(["Foo_Bar"]), id="argument-case"),149 pytest.param(lambda: click.Option(["--foo-bar"]), id="option-hyphen"),150 pytest.param(151 lambda: click.Option(["--0foo", "zero_foo"]), id="option-explicit-name"152 ),153 # Soft keywords are contextual and name a parameter fine.154 pytest.param(lambda: click.Option(["--match"]), id="soft-keyword-match"),155 pytest.param(lambda: click.Argument(["type"]), id="soft-keyword-type"),156 # These lower case out of the keyword set.157 pytest.param(lambda: click.Option(["--True"]), id="true"),158 pytest.param(lambda: click.Option(["--None"]), id="none"),159 ],160)161def test_usable_name_not_deprecated(recwarn, make_param):162 """A name a callback can declare keeps working, and says nothing."""163 make_param()164 assert [w for w in recwarn if issubclass(w.category, DeprecationWarning)] == []165166167@pytest.mark.parametrize(168 "make_param",169 [170 pytest.param(lambda: click.Option(["--from"]), id="keyword"),171 pytest.param(lambda: click.Argument(["0foo"]), id="non-identifier"),172 ],173)174def test_unusable_name_names_the_release_that_refuses_it(make_param):175 """Both refusals name the release that turns the warning into an error."""176 match = r"will raise a TypeError in Click 9\.0"177 with pytest.warns(DeprecationWarning, match=match):178 make_param()179180181@pytest.mark.parametrize(182 ("decl", "expect"),183 [184 pytest.param("Foo_Bar", "foo_bar", id="mixed-case"),185 pytest.param("X_Y", "x_y", id="upper-case"),186 pytest.param("ΟΔΟΣ", "οδος", id="final-sigma"),187 pytest.param("\N{KELVIN SIGN}", "k", id="kelvin-sign"),188 ],189)190def test_unnormalized_explicit_name_deprecated(decl, expect):191 """Click 9.0 lower cases an explicit name like any other declaration."""192 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):193 param = click.Option(["--x", decl])194195 assert param.name == decl196 assert decl.lower() == expect197198199@pytest.mark.parametrize(200 "decls",201 [202 pytest.param(["--x", "foo_bar"], id="already-lower"),203 pytest.param(["--x", "_from"], id="leading-underscore"),204 pytest.param(["--Foo-Bar"], id="derived-not-explicit"),205 pytest.param(["--x", "café"], id="lower-case-non-ascii"),206 ],207)208def test_normalized_explicit_name_not_deprecated(recwarn, decls):209 """A name already spelled the way 9.0 spells it says nothing."""210 click.Option(decls)211 assert [w for w in recwarn if issubclass(w.category, DeprecationWarning)] == []212213214def test_unnormalized_name_on_a_refused_option_is_silent():215 """An option that cannot be built at all warns about nothing."""216 with pytest.raises(TypeError, match="No options defined"):217 with warnings.catch_warnings():218 warnings.simplefilter("error", DeprecationWarning)219 click.Option(["Foo_Bar"])
modified:tests/test_options.py+262 added-1 removed
1 unmodified line
2import os3import re4import sys5import tempfile6import unicodedata7import warnings8from contextlib import nullcontext9from typing import Literal1011if sys.version_info < (3, 11):
783 unmodified lines
795 Type casting is only applied to defaults in processing, not when796 getting the default value.797 """798 option = click.Option(797 ["--in"], type=click.File(), default=__file__, show_default=True799 ["--infile"], type=click.File(), default=__file__, show_default=True800 )801 context = click.Context(click.Command("test"))802 assert option.get_help_extra(context) == {"default": __file__}803 result = option.get_help_record(context)[1]
10 unmodified lines
814 assert not result.exception815 assert result.output == "foo\n"816817818# CPython upper-cases every key of ``os.environ`` when ``os.name == "nt"``,819# see ``os._createenviron``. ``CliRunner`` writes the ``env`` mapping through820# ``os.environ`` and ``Parameter.resolve_envvar_value`` reads it back the same821# way, so on Windows a variable answers to every spelling of its name and822# elsewhere to exactly one. Both halves are asserted rather than skipped: the823# difference is the behaviour being pinned. See pallets/click#2483.824ENV_NAMES_ARE_CASE_INSENSITIVE = sys.platform == "win32"825826827def test_auto_envvar_uses_the_transformed_name(runner):828 """The auto envvar is built from the name, which the transform lower-cased."""829830 @click.command()831 @click.option("--Foo-Bar")832 def cmd(foo_bar):833 click.echo(foo_bar)834835 result = runner.invoke(836 cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}837 )838 assert not result.exception839 assert result.output == "foo\n"840841842def test_auto_envvar_ignores_decl_case(runner):843 """The case written in the declaration never reaches the auto envvar."""844845 @click.command()846 @click.option("--Foo-Bar")847 def cmd(foo_bar):848 click.echo(repr(foo_bar))849850 result = runner.invoke(851 cmd, [], auto_envvar_prefix="TEST", env={"TEST_Foo_Bar": "foo"}852 )853 assert not result.exception854 expect = "'foo'" if ENV_NAMES_ARE_CASE_INSENSITIVE else "None"855 assert result.output == f"{expect}\n"856857858def test_auto_envvar_prefix_is_upper_cased(runner):859 """A lower-case prefix reaches an upper-case variable, and only that one."""860861 @click.command()862 @click.option("--flag/--no-flag")863 def cmd(flag):864 click.echo(repr(flag))865866 result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"YO_FLAG": "1"})867 assert not result.exception868 assert result.output == "True\n"869870 result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"yo_FLAG": "1"})871 assert not result.exception872 assert result.output == f"{ENV_NAMES_ARE_CASE_INSENSITIVE}\n"873874875def test_auto_envvar_flattens_name_case(runner):876 """Two names differing only by case share one auto envvar."""877 with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):878879 @click.command()880 @click.option("--foo-bar")881 @click.option("--other", "Foo_Bar")882 def cmd(**kwargs):883 click.echo(repr(sorted(kwargs.items())))884885 assert [p.name for p in cmd.params if p.name] == ["foo_bar", "Foo_Bar"]886887 result = runner.invoke(888 cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}889 )890 assert not result.exception891 assert result.output == "[('Foo_Bar', 'foo'), ('foo_bar', 'foo')]\n"892893894def test_auto_envvar_upper_can_change_length(runner):895 """Deriving the envvar is not the inverse of deriving the name."""896897 @click.command()898 @click.option("--ẞ")899 def cmd(**kwargs):900 click.echo(repr(kwargs))901902 result = runner.invoke(cmd, [], auto_envvar_prefix="TEST", env={"TEST_SS": "foo"})903 assert not result.exception904 assert result.output == "{'ß': 'foo'}\n"905906907@pytest.mark.parametrize(908 ("env", "expect"),909 [910 pytest.param({"ArG": "foo"}, "'foo'", id="exact"),911 pytest.param({"ARG": "foo"}, "None", id="upper"),912 pytest.param({"arg": "foo"}, "None", id="lower"),913 ],914)915def test_explicit_envvar_case_sensitivity(runner, env, expect):916 """An explicitly named envvar keeps the case it was registered with."""917918 @click.command()919 @click.option("--arg", envvar="ArG")920 def cmd(arg):921 click.echo(repr(arg))922923 result = runner.invoke(cmd, [], env=env)924 assert not result.exception925 if ENV_NAMES_ARE_CASE_INSENSITIVE:926 expect = "'foo'"927 assert result.output == f"{expect}\n"928929930@pytest.mark.parametrize("name", ("FlAg", "sUper"))931def test_explicit_envvar_list_keeps_each_spelling(runner, name):932 """Every name of an envvar list is matched with its own case."""933934 @click.command()935 @click.option("--flag/--no-flag", envvar=["FlAg", "sUper"])936 def cmd(flag):937 click.echo(repr(flag))938939 result = runner.invoke(cmd, [], env={name: "1"})940 assert not result.exception941 assert result.output == "True\n"942943944def test_nargs_envvar(runner):945 @click.command()946 @click.option("--arg", nargs=2)947 def cmd(arg):
452 unmodified lines
1400 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),1401 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),1402 (["--from", "-f", "_from"], "_from"),1403 (["--return", "-r", "_ret"], "_ret"),1404 # A name derived from an option string is lower-cased.1405 (["--Foo-Bar"], "foo_bar"),1406 (["--FOO-BAR", "-F"], "foo_bar"),1407 # An identifier declaration goes through the same transform.1408 (["--foo-bar", "-f", "explicit_name"], "explicit_name"),1409 # Underscores survive, and every dash past the prefix becomes one.1410 (["--foo__bar"], "foo__bar"),1411 (["--foo--bar"], "foo__bar"),1412 (["--_foo"], "_foo"),1413 (["--__foo"], "__foo"),1414 (["---foo"], "_foo"),1415 (["-_"], "_"),1416 # A digit is only refused in the leading position.1417 (["--foo-0"], "foo_0"),1418 ],1419)1420def test_option_names(runner, option_args, expected):1421 @click.command()
8 unmodified lines
1430 result = runner.invoke(cmd, [form])1431 assert result.output == "True\n"143214331434def test_option_name_case_transform_can_collide(runner):1435 """Two declarations that differ can transform to one name, with no warning."""14361437 @click.command()1438 @click.option("--\N{KELVIN SIGN}")1439 @click.option("--k")1440 def cmd(**kwargs):1441 click.echo(repr(kwargs))14421443 assert [p.name for p in cmd.params] == ["k", "k"]14441445 result = runner.invoke(cmd, ["--\N{KELVIN SIGN}", "kelvin", "--k", "ascii"])1446 assert not result.exception1447 assert result.output == "{'k': 'ascii'}\n"144814491450def test_option_name_case_variants_share_one_parameter(runner):1451 """Case variants of one option collapse onto a single parameter."""14521453 @click.command()1454 @click.option("--foo-bar")1455 @click.option("--Foo-Bar")1456 @click.option("--FOO-BAR")1457 def cmd(**kwargs):1458 click.echo(repr(kwargs))14591460 assert [p.name for p in cmd.params] == ["foo_bar"] * 314611462 with warnings.catch_warnings(record=True) as caught:1463 warnings.simplefilter("always")1464 result = runner.invoke(cmd, ["--help"], catch_exceptions=False)14651466 assert not [w for w in caught if issubclass(w.category, UserWarning)]1467 for spelling in ("--foo-bar", "--Foo-Bar", "--FOO-BAR"):1468 assert spelling in result.output14691470 for spelling, value in (("--foo-bar", "a"), ("--Foo-Bar", "b"), ("--FOO-BAR", "c")):1471 result = runner.invoke(cmd, [spelling, value])1472 assert not result.exception1473 assert result.output == f"{{'foo_bar': {value!r}}}\n"14741475 # Sharing one slot, the last spelling on the command line wins.1476 result = runner.invoke(cmd, ["--foo-bar", "a", "--FOO-BAR", "c"])1477 assert result.output == "{'foo_bar': 'c'}\n"147814791480def test_option_name_keeps_its_normalization_form(runner):1481 """A composed and a decomposed declaration are two distinct parameters."""1482 decomposed = "cafe\N{COMBINING ACUTE ACCENT}"1483 composed = unicodedata.normalize("NFC", decomposed)14841485 @click.command()1486 @click.option(f"--{composed}")1487 @click.option(f"--{decomposed}")1488 def cmd(**kwargs):1489 click.echo(repr(sorted(kwargs)))14901491 assert [p.name for p in cmd.params] == [composed, decomposed]14921493 result = runner.invoke(cmd, [])1494 assert not result.exception1495 assert result.output == f"['{decomposed}', '{composed}']\n"149614971498def test_option_name_must_be_an_identifier():1499 """A short option is the one refused shape an argument cannot be written as."""1500 with pytest.raises(TypeError, match="Could not determine name"):1501 click.Option(["-0"])150215031504def test_option_prompt_still_guards_against_a_nameless_option():1505 """An unexposed option can still be named ``""``, which ``prompt=True`` refuses."""1506 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):1507 with pytest.raises(TypeError, match="'name' is required with 'prompt=True'"):1508 click.Option(["--0-file"], expose_value=False, prompt=True)150915101511def test_option_name_check_applies_when_not_exposed():1512 """An unexposed option is named ``""``, and says Click 9.0 will refuse it."""1513 with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):1514 assert click.Option(["--0foo"], expose_value=False).name == ""151515161517def test_option_explicit_name_carries_a_refused_declaration(runner):1518 """An explicit name reaches a declaration the transform cannot name."""1519 seen = []15201521 def record(ctx, param, value):1522 seen.append(value)15231524 @click.command()1525 @click.option("--0foo", "zero_foo", expose_value=False, callback=record)1526 def cmd(**kwargs):1527 click.echo(repr(kwargs))15281529 assert cmd.params[0].name == "zero_foo"15301531 result = runner.invoke(cmd, ["--0foo", "value"])1532 assert not result.exception1533 assert result.output == "{}\n"1534 assert seen == ["value"]153515361537def test_option_name_may_be_a_python_keyword(runner):1538 """``str.isidentifier()`` accepts a keyword, so the check lets one through."""1539 with pytest.warns(DeprecationWarning, match="is a Python keyword"):15401541 @click.command()1542 @click.option("--from")1543 def cmd(**kwargs):1544 click.echo(repr(kwargs))15451546 assert cmd.params[0].name == "from"15471548 result = runner.invoke(cmd, ["--from", "here"])1549 assert not result.exception1550 assert result.output == "{'from': 'here'}\n"155115521553def test_flag_duplicate_names(runner):1554 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):1555 click.Option(["--foo/--foo"], default=False)1556
2360 unmodified lines
modified:CHANGES.md+5 added
1## Version 8.6.023Unreleased45- A parameter name that is not a valid Python identifier, or that is a Python6 keyword, is deprecated and raises `TypeError` in Click 9.0. {pr}`3866`7- An {class}`Option` name written as a Python identifier is deprecated when it8 is not already lower-cased. {pr}`3866`910## Version 8.5.11112Unreleased13
1681 unmodified lines