Skip to content
Myr

test_defaults.py

This file

Path

tests/test_defaults.py

563 lines · 19.0 KiB · Python

Last changed by

Merge branch 'stable'David Lordbefore adoptionbc36cd1

History of this file

Take it

1import os23import pytest45import click6from click import UNPROCESSED7from click._utils import UNSET8from click.core import ParameterSource91011@pytest.mark.parametrize(12    ("default", "type", "expected_output", "expected_type"),13    [14        (42, click.FLOAT, "42.0", float),15        ("42", click.INT, "42", int),16        (1.5, click.STRING, "1.5", str),17        ("1.5", click.FLOAT, "1.5", float),18        ("true", click.BOOL, "True", bool),19        ("0", click.BOOL, "False", bool),20    ],21)22def test_basic_defaults(runner, default, type, expected_output, expected_type):23    """Smoke test: a single option's default is type-coerced.2425    This covers basic single-option default type coercion.26    """2728    @click.command()29    @click.option("--foo", default=default, type=type)30    def cli(foo):31        assert isinstance(foo, expected_type)32        click.echo(f"FOO:[{foo}]")3334    result = runner.invoke(cli, [])35    assert not result.exception36    assert f"FOO:[{expected_output}]" in result.output373839def test_multiple_defaults(runner):40    """Smoke test: each element in a multiple-option default is type-coerced.4142    .. hint::43        ``test_options.py::test_good_defaults_for_multiple``44        covers the structural default processing (``list`` to45        ``tuple``, various ``nargs``) exhaustively.4647        This test fills the gap of explicit48        ``type=click.FLOAT`` coercion on the elements.49    """5051    @click.command()52    @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True)53    def cli(foo):54        for item in foo:55            assert isinstance(item, float)56            click.echo(item)5758    result = runner.invoke(cli, [])59    assert not result.exception60    assert result.output.splitlines() == ["23.0", "42.0"]616263def test_nargs_plus_multiple(runner):64    """Smoke test: option with ``nargs=2`` + ``multiple=True`` and a65    tuple-of-tuples default.6667    .. hint::68        ``test_options.py::test_good_defaults_for_multiple``69        expands this with many more edge cases with various70        ``nargs``/``multiple``/``default`` combinations.7172        An argument-specific equivalent is in73        ``test_arguments.py::test_good_defaults_for_nargs``.74    """7576    @click.command()77    @click.option(78        "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT79    )80    def cli(arg):81        for a, b in arg:82            click.echo(f"<{a:d}|{b:d}>")8384    result = runner.invoke(cli, [])85    assert not result.exception86    assert result.output.splitlines() == ["<1|2>", "<3|4>"]878889def test_multiple_flag_default(runner):90    """Default for flags when multiple=True should be empty tuple."""9192    @click.command93    # flag due to secondary token94    @click.option("-y/-n", multiple=True)95    # flag due to is_flag96    @click.option("-f", is_flag=True, multiple=True)97    # flag due to flag_value98    @click.option("-v", "v", flag_value=1, multiple=True)99    @click.option("-q", "v", flag_value=-1, multiple=True)100    def cli(y, f, v):101        return y, f, v102103    result = runner.invoke(cli, standalone_mode=False)104    assert result.return_value == ((), (), ())105106    result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False)107    assert result.return_value == ((True, False), (True,), (1, -1))108109110def test_flag_default_map(runner):111    """test flag with default map"""112113    @click.group()114    def cli():115        pass116117    @cli.command()118    @click.option("--name/--no-name", is_flag=True, show_default=True, help="name flag")119    def foo(name):120        click.echo(name)121122    result = runner.invoke(cli, ["foo"])123    assert "False" in result.output124125    result = runner.invoke(cli, ["foo", "--help"])126    assert "default: no-name" in result.output127128    result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}})129    assert "True" in result.output130131    result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})132    assert "default: name" in result.output133134135def test_shared_param_prefers_first_default(runner):136    """The first ``default=True`` wins when multiple ``flag_value`` options share137    a parameter name, regardless of which positional option carries it.138139    .. hint::140        ``test_basic.py::test_flag_value_dual_options`` and141        ``test_options.py::test_default_dual_option_callback`` are wider142        parametrized sibling tests covering many more default-value types (``None``,143        ``UNSET``, strings, numbers) but always place the default on the first144        option. This test complements them by exercising both placements.145    """146147    @click.command148    @click.option("--red", "color", flag_value="red")149    @click.option("--green", "color", flag_value="green", default=True)150    def prefers_green(color):151        click.echo(color)152153    @click.command154    @click.option("--red", "color", flag_value="red", default=True)155    @click.option("--green", "color", flag_value="green")156    def prefers_red(color):157        click.echo(color)158159    result = runner.invoke(prefers_green, [])160    assert "green" in result.output161    result = runner.invoke(prefers_green, ["--red"])162    assert "red" in result.output163164    result = runner.invoke(prefers_red, [])165    assert "red" in result.output166    result = runner.invoke(prefers_red, ["--green"])167    assert "green" in result.output168169170@pytest.mark.parametrize(171    ("default_map", "key", "expected"),172    [173        # Key present in default_map.174        ({"email": "a@b.com"}, "email", "a@b.com"),175        # Key missing from default_map.176        ({"email": "a@b.com"}, "nonexistent", None),177        # No default_map at all / empty default_map.178        (None, "anything", None),179        ({}, "anything", None),180        # Falsy values are returned as-is.181        ({"key": None}, "key", None),182        ({"key": 0}, "key", 0),183        ({"key": ""}, "key", ""),184        ({"key": False}, "key", False),185    ],186)187def test_lookup_default_returns_hides_sentinel(default_map, key, expected):188    """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.189190    Regression test for https://github.com/pallets/click/issues/3145.191    """192    cmd = click.Command("test")193    ctx = click.Context(cmd)194    if default_map is not None:195        ctx.default_map = default_map196    assert ctx.lookup_default(key) == expected197198199def test_lookup_default_callable_in_default_map(runner):200    """A callable in ``default_map`` is invoked with ``call=True``201    (the default) and returned as-is with ``call=False``.202203    Click uses both paths internally:204    - ``get_default()`` passes ``call=False``,205    - ``resolve_ctx()`` passes ``call=True``.206    """207    factory = lambda: "lazy-value"  # noqa: E731208209    # Unit-level: call=True invokes, call=False returns as-is.210    cmd = click.Command("test")211    ctx = click.Context(cmd)212    ctx.default_map = {"name": factory}213    assert ctx.lookup_default("name", call=True) == "lazy-value"214    assert ctx.lookup_default("name", call=False) is factory215216    # Integration: the callable is invoked during value resolution.217    @click.command()218    @click.option("--name", default="original", show_default=True)219    @click.pass_context220    def cli(ctx, name):221        click.echo(f"name={name!r}")222223    result = runner.invoke(cli, [], default_map={"name": factory})224    assert not result.exception225    assert "name='lazy-value'" in result.output226227    # Help rendering gets the callable via call=False, so it228    # shows "(dynamic)" rather than invoking it.229    result = runner.invoke(cli, ["--help"], default_map={"name": factory})230    assert not result.exception231    assert "(dynamic)" in result.output232233234@pytest.mark.parametrize(235    ("args", "default_map", "expected_value", "expected_source"),236    [237        # CLI arg wins over everything.238        (["--name", "cli"], {"name": "mapped"}, "cli", "COMMANDLINE"),239        # default_map overrides parameter default.240        ([], {"name": "mapped"}, "mapped", "DEFAULT_MAP"),241        # Explicit None in default_map still counts as DEFAULT_MAP.242        ([], {"name": None}, None, "DEFAULT_MAP"),243        # Falsy values in default_map are not confused with missing keys.244        ([], {"name": ""}, "", "DEFAULT_MAP"),245        ([], {"name": 0}, "0", "DEFAULT_MAP"),246        # No default_map falls back to parameter default.247        ([], None, "original", "DEFAULT"),248    ],249)250def test_default_map_source(runner, args, default_map, expected_value, expected_source):251    """``get_parameter_source()`` reports the correct origin for a parameter252    value across the resolution chain: CLI > default_map > parameter default.253    """254255    @click.command()256    @click.option("--name", default="original")257    @click.pass_context258    def cli(ctx, name):259        source = ctx.get_parameter_source("name")260        click.echo(f"name={name!r} source={source.name}")261262    kwargs = {}263    if default_map is not None:264        kwargs["default_map"] = default_map265    result = runner.invoke(cli, args, **kwargs)266    assert not result.exception267    assert f"name={expected_value!r}" in result.output268    assert f"source={expected_source}" in result.output269270271def test_parameter_source_during_paramtype_convert(runner):272    """``get_parameter_source()`` is available during ``ParamType.convert``.273274    Uses the reproducer from https://github.com/pallets/click/issues/3458.275    """276277    class Source(click.ParamType):278        name = "source"279280        def convert(self, value, param, ctx):281            return {282                "value": value,283                "source": ctx.get_parameter_source(param.name),284            }285286    @click.command()287    @click.option("--default", type=Source(), default="/tmp/file")288    @click.option("--nodefault", type=Source())289    def cli(default, nodefault):290        click.echo(f"default: {default}")291        click.echo(f"nodefault: {nodefault}")292293    result = runner.invoke(cli, [])294    assert not result.exception295    assert "default: {'value': '/tmp/file', 'source': " in result.output296    assert "'source': None}" not in result.output.split("default:")[1].split("\n")[0]297    assert (298        result.output == "default: {'value': '/tmp/file', 'source': "299        f"{ParameterSource.DEFAULT!r}}}\nnodefault: None\n"300    )301302    result = runner.invoke(cli, ["--default", "cli", "--nodefault", "also"])303    assert not result.exception304    assert (305        "default: {'value': 'cli', 'source': "306        f"{ParameterSource.COMMANDLINE!r}}}" in result.output307    )308    assert (309        "nodefault: {'value': 'also', 'source': "310        f"{ParameterSource.COMMANDLINE!r}}}" in result.output311    )312313314def test_parameter_source_during_eager_callback(runner):315    """``get_parameter_source()`` is available during eager callbacks.316317    Regression test for https://github.com/pallets/click/issues/3458.318    """319320    def eager_cb(ctx, param, value):321        source = ctx.get_parameter_source(param.name)322        click.echo(f"callback source={source.name if source else None}")323324    @click.command()325    @click.option(326        "--flag/--no-flag",327        default=False,328        is_eager=True,329        callback=eager_cb,330        expose_value=False,331    )332    def cli():333        source = click.get_current_context().get_parameter_source("flag")334        click.echo(f"final source={source.name}")335336    result = runner.invoke(cli, [])337    assert not result.exception338    assert "callback source=DEFAULT" in result.output339    assert "final source=DEFAULT" in result.output340341    result = runner.invoke(cli, ["--flag"])342    assert not result.exception343    assert "callback source=COMMANDLINE" in result.output344    assert "final source=COMMANDLINE" in result.output345346347def test_flask_debug_env_not_stomped_by_default_flag(runner, monkeypatch):348    """Eager callback must not overwrite env when the flag used its default.349350    Covers the Flask ``_set_debug`` pattern (pallets/flask#6025). Regression test351    for https://github.com/pallets/click/issues/3458.352    """353354    monkeypatch.delenv("APP_DEBUG", raising=False)355356    def set_debug(ctx, param, value):357        source = ctx.get_parameter_source(param.name)358        if source is not None and source in (359            ParameterSource.DEFAULT,360            ParameterSource.DEFAULT_MAP,361        ):362            return None363        os.environ["APP_DEBUG"] = "1" if value else "0"364        return value365366    @click.command()367    @click.option(368        "--debug/--no-debug",369        default=False,370        is_eager=True,371        expose_value=False,372        callback=set_debug,373    )374    def cli():375        click.echo(f"APP_DEBUG={os.environ.get('APP_DEBUG', '')}")376377    monkeypatch.setenv("APP_DEBUG", "1")378    result = runner.invoke(cli, [])379    assert result.exit_code == 0380    assert result.output.strip() == "APP_DEBUG=1"381382    result = runner.invoke(cli, ["--debug"])383    assert result.exit_code == 0384    assert result.output.strip() == "APP_DEBUG=1"385386    result = runner.invoke(cli, ["--no-debug"])387    assert result.exit_code == 0388    assert result.output.strip() == "APP_DEBUG=0"389390391def test_parameter_source_on_parse_result_bypass(runner):392    """A losing option keeps its provisional source when ``ctx.params[name]``393    is populated by code that bypassed ``handle_parse_result``.394395    This replicate the pattern documented in the "Parameter Modifications" section396    of ``docs/advanced.md``. This test highlight the current behavior of397    ``get_parameter_source()`` but is not intended as a contract enforcement.398    """399400    def hijack(ctx, param, value):401        ctx.params["target"] = "hijacked"402        return value403404    @click.command()405    @click.option("--hijacker", is_eager=True, callback=hijack, expose_value=False)406    @click.option("--target", default="default_value")407    @click.pass_context408    def cli(ctx, target):409        source = ctx.get_parameter_source("target")410        click.echo(f"value={target} source={source.name if source else 'None'}")411412    result = runner.invoke(cli, ["--hijacker", "anything"])413    assert result.exit_code == 0, result.output414    assert "value=hijacked" in result.output415    assert "source=DEFAULT" in result.output416417418def test_lookup_default_override_respected(runner):419    """A subclass override of ``lookup_default()`` should be called by Click420    internals, not bypassed by a private method.421422    Reproduce exactly https://github.com/pallets/click/issues/3145 in which a423    subclass that falls back to prefix-based lookup when the parent returns424    ``None``.425426    Previous attempts in https://github.com/pallets/click/pr/3199 were entirely427    bypassing the user's overridden method.428    """429430    class CustomContext(click.Context):431        def lookup_default(self, name, call=True):432            default = super().lookup_default(name, call=call)433434            if default is not None:435                return default436437            # Prefix-based fallback: look up "app" sub-dict for "app_email".438            prefix = name.split("_", 1)[0]439            group = getattr(self, "default_map", None) or {}440            sub = group.get(prefix)441            if isinstance(sub, dict):442                return sub.get(name)443            return default444445    @click.command("get-views")446    @click.option("--app-email", default="original", show_default=True)447    @click.pass_context448    def cli(ctx, app_email):449        click.echo(f"app_email={app_email!r}")450451    cli.context_class = CustomContext452    default_map = {"app": {"app_email": "prefix@example.com"}}453454    # resolve_ctx path: the override provides the runtime value.455    result = runner.invoke(cli, [], default_map=default_map)456    assert not result.exception457    assert "app_email='prefix@example.com'" in result.output458459    # get_default path: the override is also used when460    # rendering --help with show_default=True.461    result = runner.invoke(cli, ["--help"], default_map=default_map)462    assert not result.exception463    assert "prefix@example.com" in result.output464465466class _Marker:467    """Dummy callable used as a flag_value in default tests."""468469    pass470471472@pytest.mark.parametrize(473    ("default_map", "args", "expected"),474    [475        # No default_map: auto-aligned default returns the class, not an instance.476        (None, [], _Marker),477        # CLI flag always returns the class.478        (None, ["--opt"], _Marker),479        # Static value in default_map overrides the auto-aligned flag_value.480        ({"value": "from-map"}, [], "from-map"),481        # Callable in default_map is still invoked (not suppressed by the fix).482        ({"value": lambda: "lazy-map"}, [], "lazy-map"),483        # None in default_map overrides the flag_value.484        ({"value": None}, [], None),485        # CLI arg wins over default_map.486        ({"value": "from-map"}, ["--opt"], _Marker),487    ],488)489def test_default_map_with_callable_flag_value(runner, default_map, args, expected):490    """``default_map`` entries should override the auto-aligned callable ``flag_value``,491    and callable entries in ``default_map`` should still be invoked.492493    Verifies the fix for https://github.com/pallets/click/issues/3121 does not494    break ``default_map`` precedence.495    """496497    @click.command()498    @click.option("--opt", "value", flag_value=_Marker, type=UNPROCESSED, default=True)499    def cli(value):500        click.echo(repr(value), nl=False)501502    kwargs = {}503    if default_map is not None:504        kwargs["default_map"] = default_map505    result = runner.invoke(cli, args, **kwargs)506    assert result.exit_code == 0507    assert result.output == repr(expected)508509510@pytest.mark.parametrize(511    ("default_map", "option_kwargs", "cli_args", "expected"),512    [513        # String is split for nargs=2 option.514        ({"point": "3 4"}, {"nargs": 2, "type": int}, [], (3, 4)),515        # String is split for explicit Tuple type.516        ({"point": "hello world"}, {"type": (str, str)}, [], ("hello", "world")),517        # Already-structured tuple passes through unchanged.518        ({"point": ("a", "b")}, {"nargs": 2}, [], ("a", "b")),519        # Already-structured list passes through unchanged.520        ({"point": [5, 6]}, {"nargs": 2, "type": int}, [], (5, 6)),521        # CLI args override default_map for nargs > 1.522        (523            {"point": "3 4"},524            {"nargs": 2, "type": int},525            ["--point", "10", "20"],526            (10, 20),527        ),528    ],529)530def test_default_map_nargs(runner, default_map, option_kwargs, cli_args, expected):531    """A string in ``default_map`` for an option with ``nargs > 1`` should be532    split the same way an environment variable string is split.533534    Regression test for https://github.com/pallets/click/issues/2745.535    """536537    @click.command()538    @click.option("--point", **option_kwargs)539    def cli(point):540        click.echo(repr(point))541542    result = runner.invoke(cli, cli_args, default_map=default_map)543    assert result.exit_code == 0544    assert result.output.strip() == repr(expected)545546547def test_unset_in_default_map(runner):548    """An ``UNSET`` value in ``default_map`` should be treated as if549    the key is absent, and so fallback to the parameter's own default.550551    Refs: https://github.com/pallets/click/pull/3224#issuecomment-3968643305552    """553554    @click.command(555        context_settings={"default_map": {"port": UNSET}},556    )557    @click.option("--port", default=8000)558    def cli(port):559        click.echo(f"port={port}")560561    result = runner.invoke(cli, [])562    assert result.exit_code == 0563    assert result.output.strip() == "port=8000"