Revert "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.
This reverts commit e2bddbc801dabc4efc3c3c1e32b53b3f938d3efc.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent e2bddbc · Browse files · 6 files·+8 added−804 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+8 added−804 removed
- tests:+4 added−731 removed
- other:+4 added−73 removed
Provenance
- Commit
d036881- Tree
6be3fac- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
e2bddbc
6 files changed+8 added−804 removed
modified:docs/upgrade-guides.md-2 removed
11 unmodified lines1213141516171617181915 unmodified lines11 unmodified lines
### Deprecations
For each deprecation, provide a brief explanation, and direct users to new function / class if available.- A parameter name that is not a valid Python identifier is deprecated and raises `TypeError` in 9.0 if it does not satisfy [`str.isidentifier()`](https://docs.python.org/3/library/stdtypes.html#str.isidentifier). To migrate, give an explicit name to an option (`click.option("--0-file", "zero_file")`), or rename an argument's declaration and pass `metavar` to keep its old display (`click.argument("zero_file", metavar="0-FILE")`). See [#3827](https://github.com/pallets/click/pull/3827).- An option name written as a Python identifier is deprecated when it is not already lower cased. See [#3827](https://github.com/pallets/click/pull/3827).- `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).
### Removals with prior deprecation
15 unmodified linesmodified:src/click/core.py+4 added-69 removed
16 unmodified lines17 from functools import update_wrapper18 from gettext import gettext as _19 from gettext import ngettext20 from itertools import repeat21-from types import FrameType21 from types import TracebackType22 23 from . import types24 from ._utils import FLAG_NEEDS_VALUE78 unmodified lines103 """Write the final abort message to standard error."""104 echo(_("Aborted!"), file=sys.stderr)105 106 108-def _outside_click_stacklevel() -> int:109- """Depth of the first stack frame outside Click.110-111- .. versionadded:: 8.5.1112- """113- frame: FrameType | None = sys._getframe(1)114- level = 1115-116- while frame is not None:117- module = frame.f_globals.get("__name__", "")118-119- if module != "click" and not module.startswith("click."):120- return level121-122- frame = frame.f_back123- level += 1124-125- return level126-127-107 def _format_deprecated_label(deprecated: bool | str) -> str:108 """Return the parenthesized deprecation label shown in help text."""109 label = _("deprecated").upper()110 if isinstance(deprecated, str):2345 unmodified lines2456 def _parse_decls(2457 self, decls: cabc.Sequence[str], expose_value: bool2458 ) -> tuple[str, list[str], list[str]]: ...2459 2481- def _check_name_is_identifier(self, name: str, decls: cabc.Sequence[str]) -> None:2482- """Warn about a name Click 9.0 will refuse.2483-2484- .. versionadded:: 8.5.12485- """2486- if name.isidentifier():2487- return2488-2489- import warnings2490-2491- 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- )2498-2460 @property2461 def human_readable_name(self) -> str:2462 """Returns the human readable name of this parameter. This is the2463 same as the name for options, but the metavar for arguments.808 unmodified lines3272 if self.show_envvar and self.envvar is not None:3273 result += f" (env var: '{self.envvar}')"3274 return result3275 3315- 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.3317-3318- .. versionadded:: 8.5.13319- """3320- normalized = name.lower()3321-3322- if normalized == name:3323- return3324-3325- import warnings3326-3327- 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- )3334-3276 def _parse_decls(3277 self, decls: cabc.Sequence[str], expose_value: bool3278 ) -> tuple[str, list[str], list[str]]:3279 opts = []3280 secondary_opts = []3281 name = None3341- explicit_name = None3282 possible_names = []3283 3284 for decl in decls:3285 if decl.isidentifier():3286 if name is not None:3287 raise TypeError(_("Name '{name}' defined twice").format(name=name))3348- name = explicit_name = decl3288+ name = decl3289 else:3290 split_char = ";" if decl[:1] == "/" else "/"3291 if split_char in decl:3292 first, second = decl.split(split_char, 1)17 unmodified lines3310 3311 if name is None and possible_names:3312 possible_names.sort(key=lambda x: -len(x[0])) # group long options first3313 name = possible_names[0][1].replace("-", "_").lower()3314+ if not name.isidentifier():3315+ name = None3316 3375- if name is None or not name.isidentifier():3317+ if name is None:3318 if not expose_value:3377- self._check_name_is_identifier(name or "", decls)3319 return "", opts, secondary_opts3379-3320 raise TypeError(3321 _(3322 "Could not determine name for option with declarations {decls!r}"3323 ).format(decls=decls)7 unmodified lines3331 " you mean to pass '--{name}'?"3332 ).format(name=name)3333 )3334 3395- if explicit_name is not None:3396- self._check_name_is_normalized(explicit_name, decls)3397-3335 return name, opts, secondary_opts3336 3337 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3338 if self.multiple:439 unmodified lines3778 self, decls: cabc.Sequence[str], expose_value: bool3779 ) -> tuple[str, list[str], list[str]]:3780 if not decls:3781 if not expose_value:3845- self._check_name_is_identifier("", decls)3782 return "", [], []3783 raise TypeError("Argument is marked as exposed, but does not have a name.")3784 if len(decls) == 1:3785 name = arg = decls[0]4 unmodified lines3790 "Arguments take exactly one parameter declaration, got"3791 " {length}: {decls}."3792 ).format(length=len(decls), decls=decls)3793 )3858- self._check_name_is_identifier(name, decls)3794 return name, [arg], []3795 3796 def get_usage_pieces(self, ctx: Context) -> list[str]:3797 return [self.make_metavar(ctx)]38 unmodified linesmodified:tests/test_arguments.py-372 removed
1-import itertools1 import sys3-import unicodedata4-import warnings2 from unittest import mock3 4 import pytest8-from test_options import ENV_NAMES_ARE_CASE_INSENSITIVE5 6 import click7 from click._utils import UNSET8 69 unmodified lines78 assert result.exit_code == 279 assert "Got unexpected extra argument (bar)" in result.output80 81 86-@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-)98-def test_argument_names(runner, decl, expect):99- @click.command()100- @click.argument(decl)101- def cmd(**kwargs):102- click.echo(kwargs[expect])103-104- assert cmd.params[0].name == expect105-106- result = runner.invoke(cmd, ["value"])107- assert not result.exception108- assert result.output == "value\n"109-110-111-def 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"114-115- with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):116- assert click.Option(["--x", "Foo_Bar"]).name == "Foo_Bar"117-118-119-PARAM_KINDS = [120- pytest.param(click.Argument, "{decl}", id="argument"),121- pytest.param(click.Option, "--{decl}", id="option"),122-]123-124-# Declarations whose lower casing is neither one-to-one nor length-preserving.125-UNICODE_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-]133-134-# Declarations covering every shape the naming transform accepts.135-NAME_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-]152-153-154-@pytest.mark.parametrize("count", [1, 2])155-@pytest.mark.parametrize("expose_value", [True, False])156-def test_parameter_name_is_an_identifier_or_deprecated(count, expose_value):157- built = 0158-159- 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")163-164- try:165- param = cls(list(decls), expose_value=expose_value)166- except (TypeError, ValueError):167- continue168-169- built += 1170-171- if param.name.isidentifier():172- continue173-174- 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- )178-179- assert built, "the sweep built no parameter, so it proves nothing"180-181-182-def 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([])186-187- with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):188- assert click.Argument([], expose_value=False).name == ""189-190-191-def 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"195-196-197-def test_argument_metavar_renders_what_a_declaration_may_not(runner):198- """``metavar`` carries a display the declaration is no longer allowed to.199-200- 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 = []205-206- def record(ctx, param, value):207- seen.append(value)208-209- @click.command()210- @click.argument("zero_foo", expose_value=False, callback=record, metavar="0FOO")211- def cmd(**kwargs):212- click.echo(repr(kwargs))213-214- assert cmd.params[0].name == "zero_foo"215-216- result = runner.invoke(cmd, ["value"])217- assert not result.exception218- assert result.output == "{}\n"219- assert seen == ["value"]220-221- result = runner.invoke(cmd, ["--help"])222- assert "0FOO" in result.output223-224-225-@pytest.mark.parametrize(("cls", "form"), PARAM_KINDS)226-@pytest.mark.parametrize(("decl", "expect"), UNICODE_CASE_DECLS)227-def 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 == expect230-231-232-@pytest.mark.parametrize(("decl", "expect"), UNICODE_CASE_DECLS)233-def 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- return238-239- with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):240- assert click.Option(["--x", decl]).name == decl241-242- assert decl.lower() == expect243-244-245-@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-)257-def 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 == expect261-262-263-@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-)284-def 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.286-287- An exposed option is the exception, since it already refuses them.288- """289- spec = form.format(decl=decl)290-291- if cls is click.Option:292- with pytest.raises(TypeError, match="Could not determine name"):293- cls([spec])294- return295-296- with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):297- param = cls([spec])298-299- assert not param.name.isidentifier()300-301-302-@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-)310-def 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)315-316- if name.isidentifier():317- assert cls([decl]).name == name318- return319-320- if cls is click.Option:321- with pytest.raises(TypeError, match="Could not determine name"):322- cls([decl])323- return324-325- with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):326- assert cls([decl]).name == name327-328-329-@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-)336-def test_parameter_name_is_not_nfkc_normalized(runner, decorator, decl, argv):337- """``str.isidentifier()`` is not the test for "can be a parameter name".338-339- 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- """343-344- @click.command()345- @decorator(decl)346- def cmd(**kwargs):347- click.echo(repr(kwargs))348-349- name = cmd.params[0].name350- assert name == "fi"351- assert name.isidentifier()352- assert unicodedata.normalize("NFKC", name) == "fi"353-354- result = runner.invoke(cmd, argv)355- assert not result.exception356- assert result.output == "{'fi': 'value'}\n"357-358-359-def test_argument_name_keeps_its_normalization_form(runner):360- """A composed and a decomposed declaration are two distinct arguments.361-362- 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)367-368- @click.command()369- @click.argument(composed)370- @click.argument(decomposed)371- def cmd(**kwargs):372- click.echo(repr(sorted(kwargs)))373-374- assert [p.name for p in cmd.params] == [composed, decomposed]375-376- result = runner.invoke(cmd, ["one", "two"])377- assert not result.exception378- assert result.output == f"['{decomposed}', '{composed}']\n"379-380-381-def test_argument_name_case_transform_can_collide(runner):382-383- @click.command()384- @click.argument("Foo-Bar")385- @click.argument("foo_bar")386- def cmd(**kwargs):387- click.echo(repr(kwargs))388-389- with pytest.warns(UserWarning, match="is used by an argument"):390- result = runner.invoke(cmd, ["one", "two"], catch_exceptions=False)391-392- assert result.output == "{'foo_bar': 'two'}\n"393-394-395-def test_argument_name_can_collide_with_an_option(runner):396-397- @click.command()398- @click.option("--foo-bar")399- @click.argument("Foo-Bar", required=False)400- def cmd(**kwargs):401- click.echo(repr(kwargs))402-403- assert [p.name for p in cmd.params] == ["foo_bar", "foo_bar"]404-405- 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- )409-410- assert result.output == "{'foo_bar': 'from-argument'}\n"411-412-413-def test_argument_has_no_auto_envvar(runner):414- """An argument reads only the envvars it names, never a derived one."""415-416- @click.command()417- @click.argument("Foo-Bar", required=False)418- def cmd(**kwargs):419- click.echo(repr(kwargs))420-421- 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"426-427-428-@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-)436-def test_argument_explicit_envvar_case_sensitivity(runner, env, expect):437- """An argument matches its named envvar exactly, like an option does.438-439- And loses the distinction on Windows, like an option does.440- """441-442- @click.command()443- @click.argument("arg", envvar="ArG", required=False)444- def cmd(arg):445- click.echo(repr(arg))446-447- 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"452-453-82 def test_bytes_args(runner, monkeypatch):83 @click.command()84 @click.argument("arg")85 def from_bytes(arg):655 unmodified linesmodified:tests/test_deprecations.py-97 removed
1 import importlib.metadata2-import warnings2 3 import pytest4 5 import click64 unmodified lines70 def test_isolated_filesystem_deprecated(runner):71 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):72 with runner.isolated_filesystem():73 pass75-76-77-@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-)102-def 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()106-107-108-@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-)120-def 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)] == []124-125-126-def 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"])130-131-132-@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-)141-def 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])145-146- assert param.name == decl147- assert decl.lower() == expect148-149-150-@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-)159-def 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)] == []163-164-165-def 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+4 added-262 removed
1 unmodified line2 import os3 import re4 import sys5 import tempfile6-import unicodedata7-import warnings6 from contextlib import nullcontext7 from typing import Literal8 9 if sys.version_info < (3, 11):10 enum.StrEnum = enum.Enum # type: ignore[assignment]11 14-import click12 import pytest13+14+import click15+from click import Option16-from click import UNPROCESSED, Option16+from click import UNPROCESSED17 from click._utils import UNSET18 from click.testing import CliRunner19 20 791 unmodified lines812 assert not result.exception813 assert result.output == "foo\n"814 815 816-# 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.822-ENV_NAMES_ARE_CASE_INSENSITIVE = sys.platform == "win32"823-824-825-def test_auto_envvar_uses_the_transformed_name(runner):826- """The auto envvar is built from the name, which the transform lower-cased."""827-828- @click.command()829- @click.option("--Foo-Bar")830- def cmd(foo_bar):831- click.echo(foo_bar)832-833- 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"838-839-840-def test_auto_envvar_ignores_decl_case(runner):841- """The case written in the declaration never reaches the auto envvar."""842-843- @click.command()844- @click.option("--Foo-Bar")845- def cmd(foo_bar):846- click.echo(repr(foo_bar))847-848- 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"854-855-856-def test_auto_envvar_prefix_is_upper_cased(runner):857- """A lower-case prefix reaches an upper-case variable, and only that one."""858-859- @click.command()860- @click.option("--flag/--no-flag")861- def cmd(flag):862- click.echo(repr(flag))863-864- result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"YO_FLAG": "1"})865- assert not result.exception866- assert result.output == "True\n"867-868- 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"871-872-873-def 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"):876-877- @click.command()878- @click.option("--foo-bar")879- @click.option("--other", "Foo_Bar")880- def cmd(**kwargs):881- click.echo(repr(sorted(kwargs.items())))882-883- assert [p.name for p in cmd.params if p.name] == ["foo_bar", "Foo_Bar"]884-885- 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"890-891-892-def test_auto_envvar_upper_can_change_length(runner):893- """Deriving the envvar is not the inverse of deriving the name."""894-895- @click.command()896- @click.option("--ẞ")897- def cmd(**kwargs):898- click.echo(repr(kwargs))899-900- result = runner.invoke(cmd, [], auto_envvar_prefix="TEST", env={"TEST_SS": "foo"})901- assert not result.exception902- assert result.output == "{'ß': 'foo'}\n"903-904-905-@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-)913-def test_explicit_envvar_case_sensitivity(runner, env, expect):914- """An explicitly named envvar keeps the case it was registered with."""915-916- @click.command()917- @click.option("--arg", envvar="ArG")918- def cmd(arg):919- click.echo(repr(arg))920-921- 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"926-927-928-@pytest.mark.parametrize("name", ("FlAg", "sUper"))929-def test_explicit_envvar_list_keeps_each_spelling(runner, name):930- """Every name of an envvar list is matched with its own case."""931-932- @click.command()933- @click.option("--flag/--no-flag", envvar=["FlAg", "sUper"])934- def cmd(flag):935- click.echo(repr(flag))936-937- result = runner.invoke(cmd, [], env={name: "1"})938- assert not result.exception939- assert result.output == "True\n"940-941-816 def test_nargs_envvar(runner):817 @click.command()818 @click.option("--arg", nargs=2)819 def cmd(arg):452 unmodified lines1272 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),1273 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),1274 (["--from", "-f", "_from"], "_from"),1275 (["--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"),1276 ],1277 )1278 def test_option_names(runner, option_args, expected):1279 @click.command()8 unmodified lines1288 result = runner.invoke(cmd, [form])1289 assert result.output == "True\n"1290 1291 1432-def test_option_name_case_transform_can_collide(runner):1433- """Two declarations that differ can transform to one name, with no warning."""1434-1435- @click.command()1436- @click.option("--\N{KELVIN SIGN}")1437- @click.option("--k")1438- def cmd(**kwargs):1439- click.echo(repr(kwargs))1440-1441- assert [p.name for p in cmd.params] == ["k", "k"]1442-1443- result = runner.invoke(cmd, ["--\N{KELVIN SIGN}", "kelvin", "--k", "ascii"])1444- assert not result.exception1445- assert result.output == "{'k': 'ascii'}\n"1446-1447-1448-def test_option_name_case_variants_share_one_parameter(runner):1449- """Case variants of one option collapse onto a single parameter."""1450-1451- @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))1457-1458- assert [p.name for p in cmd.params] == ["foo_bar"] * 31459-1460- with warnings.catch_warnings(record=True) as caught:1461- warnings.simplefilter("always")1462- result = runner.invoke(cmd, ["--help"], catch_exceptions=False)1463-1464- 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.output1467-1468- 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"1472-1473- # 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"1476-1477-1478-def 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)1482-1483- @click.command()1484- @click.option(f"--{composed}")1485- @click.option(f"--{decomposed}")1486- def cmd(**kwargs):1487- click.echo(repr(sorted(kwargs)))1488-1489- assert [p.name for p in cmd.params] == [composed, decomposed]1490-1491- result = runner.invoke(cmd, [])1492- assert not result.exception1493- assert result.output == f"['{decomposed}', '{composed}']\n"1494-1495-1496-def 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"])1500-1501-1502-def 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)1507-1508-1509-def 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 == ""1513-1514-1515-def test_option_explicit_name_carries_a_refused_declaration(runner):1516- """An explicit name reaches a declaration the transform cannot name."""1517- seen = []1518-1519- def record(ctx, param, value):1520- seen.append(value)1521-1522- @click.command()1523- @click.option("--0foo", "zero_foo", expose_value=False, callback=record)1524- def cmd(**kwargs):1525- click.echo(repr(kwargs))1526-1527- assert cmd.params[0].name == "zero_foo"1528-1529- result = runner.invoke(cmd, ["--0foo", "value"])1530- assert not result.exception1531- assert result.output == "{}\n"1532- assert seen == ["value"]1533-1534-1535-def test_option_name_may_be_a_python_keyword(runner):1536- """``str.isidentifier()`` accepts a keyword, so the check lets one through."""1537-1538- @click.command()1539- @click.option("--from")1540- def cmd(**kwargs):1541- click.echo(repr(kwargs))1542-1543- assert cmd.params[0].name == "from"1544-1545- result = runner.invoke(cmd, ["--from", "here"])1546- assert not result.exception1547- assert result.output == "{'from': 'here'}\n"1548-1549-1292 def test_flag_duplicate_names(runner):1293 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):1294 click.Option(["--foo/--foo"], default=False)1295 2360 unmodified linesmodified:CHANGES.md-2 removed
1 ## Version 8.5.12 3 Unreleased4 5-- A parameter name that is not a valid Python identifier is deprecated and6- raises `TypeError` in Click 9.0. {pr}`3827`5 - Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`6 - A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,7 or while it exits, no longer escapes as an unhandled traceback. The command still8 exits with the intended code; only the message may be lost. {issue}`3802`1669 unmodified lines