Skip to content
Myr

test_deprecations.py

This file

Path

tests/test_deprecations.py

255 lines · 9.3 KiB · Python

Last changed by

landed by oscabriel2247b35

History of this file

Take it

1import importlib.metadata2import warnings34import pytest56import click7import click.core8import click.parser9import click.shell_completion10import click.utils111213@pytest.mark.parametrize(14    ("module", "name", "target"),15    [16        # Stream helpers, re-exported from both `click` and `click.utils`.17        (click, "get_binary_stream", click.utils._get_binary_stream),18        (click, "get_text_stream", click.utils._get_text_stream),19        (click.utils, "get_binary_stream", click.utils._get_binary_stream),20        (click.utils, "get_text_stream", click.utils._get_text_stream),21        # Command-class aliases, re-exported from `click` and `click.core`.22        (click, "BaseCommand", click.core._BaseCommand),23        (click, "MultiCommand", click.core._MultiCommand),24        (click.core, "BaseCommand", click.core._BaseCommand),25        (click.core, "MultiCommand", click.core._MultiCommand),26        # Old parser API (moved to `optparse`); `OptionParser` is also27        # re-exported from the top-level `click` namespace.28        (click, "OptionParser", click.parser._OptionParser),29        (click.parser, "OptionParser", click.parser._OptionParser),30        (click.parser, "Argument", click.parser._Argument),31        (click.parser, "Option", click.parser._Option),32        (click.parser, "split_opt", click.parser._split_opt),33        (click.parser, "normalize_opt", click.parser._normalize_opt),34        (click.parser, "ParsingState", click.parser._ParsingState),35        (click.parser, "split_arg_string", click.shell_completion.split_arg_string),36        # Deprecated `click.utils` utilities.37        (click.utils, "LazyFile", click.utils._LazyFile),38        (click.utils, "KeepOpenFile", click.utils._KeepOpenFile),39        (click.utils, "make_default_short_help", click.utils._make_default_short_help),40        (click.utils, "PacifyFlushWrapper", click.utils._PacifyFlushWrapper),41        (click.utils, "safecall", click.utils._safecall),42        # Version metadata attribute.43        (click, "__version__", importlib.metadata.version("click")),44    ],45    ids=lambda v: getattr(v, "__name__", v),46)47def test_attr_deprecated(module, name, target):48    with pytest.warns(DeprecationWarning, match=name):49        value = getattr(module, name)5051    assert value == target525354@pytest.mark.parametrize(55    "module",56    [click, click.core, click.parser, click.utils],57    ids=lambda m: m.__name__,58)59def test_unknown_attribute_raises(module):60    with pytest.raises(AttributeError, match="no_such_attribute"):61        _ = module.no_such_attribute626364def test_context_protected_args_deprecated():65    ctx = click.Context(click.Command("cli"))6667    with pytest.warns(DeprecationWarning, match="protected_args"):68        assert ctx.protected_args == []697071@pytest.mark.parametrize(72    ("param", "expected"),73    [74        (click.Option(["-t", "--times"]), "--times"),75        (click.Argument(["filename"]), "FILENAME"),76    ],77    ids=["option", "argument"],78)79def test_parameter_human_readable_name_deprecated(param, expected):80    with pytest.warns(DeprecationWarning, match="human_readable_name"):81        assert param.human_readable_name == expected8283    assert param.spec == expected848586@pytest.mark.parametrize("base", [click.Parameter, click.Option, click.Argument])87def test_parameter_human_readable_name_override_deprecated(base):88    """Click reads ``spec``, so an override of the old property has no effect."""89    with pytest.warns(DeprecationWarning, match="Override 'spec' instead"):9091        class Custom(base):  # type: ignore[misc, valid-type]92            @property93            def human_readable_name(self) -> str:94                return "custom"959697@pytest.mark.parametrize("base", [click.Parameter, click.Option, click.Argument])98def test_parameter_subclass_without_override_is_silent(base):99    """The warning names a subclass that overrides the property, and no other."""100    with warnings.catch_warnings():101        warnings.simplefilter("error", DeprecationWarning)102103        class Custom(base):  # type: ignore[misc, valid-type]104            pass105106107def test_isolated_filesystem_deprecated(runner):108    with pytest.warns(DeprecationWarning, match="isolated_filesystem"):109        with runner.isolated_filesystem():110            pass111112113@pytest.mark.parametrize(114    ("make_param", "match"),115    [116        pytest.param(117            lambda: click.Argument(["0foo"]),118            "not a valid Python identifier",119            id="argument-leading-digit",120        ),121        pytest.param(122            lambda: click.Argument(["foo.bar"]),123            "not a valid Python identifier",124            id="argument-dot",125        ),126        pytest.param(127            lambda: click.Argument(["foo bar"]),128            "not a valid Python identifier",129            id="argument-space",130        ),131        pytest.param(132            lambda: click.Argument([""]),133            "not a valid Python identifier",134            id="argument-empty-decl",135        ),136        pytest.param(137            lambda: click.Argument(["0foo"], expose_value=False),138            "not a valid Python identifier",139            id="argument-unexposed",140        ),141        pytest.param(142            lambda: click.Argument([], expose_value=False),143            "not a valid Python identifier",144            id="argument-no-decl",145        ),146        pytest.param(147            lambda: click.Option(["--0foo"], expose_value=False),148            "not a valid Python identifier",149            id="option-unexposed",150        ),151        pytest.param(152            lambda: click.Option([], expose_value=False),153            "not a valid Python identifier",154            id="option-no-decl",155        ),156        # A keyword is an identifier too, so this rule alone reports it.157        pytest.param(158            lambda: click.Option(["--from"]),159            "is a Python keyword",160            id="option-from",161        ),162        pytest.param(163            lambda: click.Option(["--import"]),164            "is a Python keyword",165            id="option-import",166        ),167        pytest.param(168            lambda: click.Argument(["class"]),169            "is a Python keyword",170            id="argument-class",171        ),172    ],173)174def test_unusable_name_deprecated(make_param, match):175    """A name Click 9.0 refuses reports which of its two rules it broke."""176    with pytest.warns(DeprecationWarning, match=match):177        make_param()178179180@pytest.mark.parametrize(181    "make_param",182    [183        pytest.param(lambda: click.Argument(["foo-bar"]), id="argument-hyphen"),184        pytest.param(lambda: click.Argument(["Foo_Bar"]), id="argument-case"),185        pytest.param(lambda: click.Option(["--foo-bar"]), id="option-hyphen"),186        pytest.param(187            lambda: click.Option(["--0foo", "zero_foo"]), id="option-explicit-name"188        ),189        # Soft keywords are contextual and name a parameter fine.190        pytest.param(lambda: click.Option(["--match"]), id="soft-keyword-match"),191        pytest.param(lambda: click.Argument(["type"]), id="soft-keyword-type"),192        # These lower case out of the keyword set.193        pytest.param(lambda: click.Option(["--True"]), id="true"),194        pytest.param(lambda: click.Option(["--None"]), id="none"),195    ],196)197def test_usable_name_not_deprecated(recwarn, make_param):198    """A name a callback can declare keeps working, and says nothing."""199    make_param()200    assert [w for w in recwarn if issubclass(w.category, DeprecationWarning)] == []201202203@pytest.mark.parametrize(204    "make_param",205    [206        pytest.param(lambda: click.Option(["--from"]), id="keyword"),207        pytest.param(lambda: click.Argument(["0foo"]), id="non-identifier"),208    ],209)210def test_unusable_name_names_the_release_that_refuses_it(make_param):211    """Both refusals name the release that turns the warning into an error."""212    match = r"will raise a TypeError in Click 9\.0"213    with pytest.warns(DeprecationWarning, match=match):214        make_param()215216217@pytest.mark.parametrize(218    ("decl", "expect"),219    [220        pytest.param("Foo_Bar", "foo_bar", id="mixed-case"),221        pytest.param("X_Y", "x_y", id="upper-case"),222        pytest.param("ΟΔΟΣ", "οδος", id="final-sigma"),223        pytest.param("\N{KELVIN SIGN}", "k", id="kelvin-sign"),224    ],225)226def test_unnormalized_explicit_name_deprecated(decl, expect):227    """Click 9.0 lower cases an explicit name like any other declaration."""228    with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):229        param = click.Option(["--x", decl])230231    assert param.name == decl232    assert decl.lower() == expect233234235@pytest.mark.parametrize(236    "decls",237    [238        pytest.param(["--x", "foo_bar"], id="already-lower"),239        pytest.param(["--x", "_from"], id="leading-underscore"),240        pytest.param(["--Foo-Bar"], id="derived-not-explicit"),241        pytest.param(["--x", "café"], id="lower-case-non-ascii"),242    ],243)244def test_normalized_explicit_name_not_deprecated(recwarn, decls):245    """A name already spelled the way 9.0 spells it says nothing."""246    click.Option(decls)247    assert [w for w in recwarn if issubclass(w.category, DeprecationWarning)] == []248249250def test_unnormalized_name_on_a_refused_option_is_silent():251    """An option that cannot be built at all warns about nothing."""252    with pytest.raises(TypeError, match="No options defined"):253        with warnings.catch_warnings():254            warnings.simplefilter("error", DeprecationWarning)255            click.Option(["Foo_Bar"])