test_defaults.py
This file
Path
tests/test_defaults.py
376 lines · 12.7 KiB · Python
Last changed by
Reduce blast-radius of `UNSET` in `default_map` (#3240)Rowlando13before adoption4a35225
History of this fileTake it
1import pytest23import click4from click import UNPROCESSED5from click._utils import UNSET678@pytest.mark.parametrize(9 ("default", "type", "expected_output", "expected_type"),10 [11 (42, click.FLOAT, "42.0", float),12 ("42", click.INT, "42", int),13 (1.5, click.STRING, "1.5", str),14 ("1.5", click.FLOAT, "1.5", float),15 ("true", click.BOOL, "True", bool),16 ("0", click.BOOL, "False", bool),17 ],18)19def test_basic_defaults(runner, default, type, expected_output, expected_type):20 """Smoke test: a single option's default is type-coerced.2122 This covers basic single-option default type coercion.23 """2425 @click.command()26 @click.option("--foo", default=default, type=type)27 def cli(foo):28 assert isinstance(foo, expected_type)29 click.echo(f"FOO:[{foo}]")3031 result = runner.invoke(cli, [])32 assert not result.exception33 assert f"FOO:[{expected_output}]" in result.output343536def test_multiple_defaults(runner):37 """Smoke test: each element in a multiple-option default is type-coerced.3839 .. hint::40 ``test_options.py::test_good_defaults_for_multiple``41 covers the structural default processing (``list`` to42 ``tuple``, various ``nargs``) exhaustively.4344 This test fills the gap of explicit45 ``type=click.FLOAT`` coercion on the elements.46 """4748 @click.command()49 @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True)50 def cli(foo):51 for item in foo:52 assert isinstance(item, float)53 click.echo(item)5455 result = runner.invoke(cli, [])56 assert not result.exception57 assert result.output.splitlines() == ["23.0", "42.0"]585960def test_nargs_plus_multiple(runner):61 """Smoke test: option with ``nargs=2`` + ``multiple=True`` and a62 tuple-of-tuples default.6364 .. hint::65 ``test_options.py::test_good_defaults_for_multiple``66 expands this with many more edge cases with various67 ``nargs``/``multiple``/``default`` combinations.6869 An argument-specific equivalent is in70 ``test_arguments.py::test_good_defaults_for_nargs``.71 """7273 @click.command()74 @click.option(75 "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT76 )77 def cli(arg):78 for a, b in arg:79 click.echo(f"<{a:d}|{b:d}>")8081 result = runner.invoke(cli, [])82 assert not result.exception83 assert result.output.splitlines() == ["<1|2>", "<3|4>"]848586def test_multiple_flag_default(runner):87 """Default default for flags when multiple=True should be empty tuple."""8889 @click.command90 # flag due to secondary token91 @click.option("-y/-n", multiple=True)92 # flag due to is_flag93 @click.option("-f", is_flag=True, multiple=True)94 # flag due to flag_value95 @click.option("-v", "v", flag_value=1, multiple=True)96 @click.option("-q", "v", flag_value=-1, multiple=True)97 def cli(y, f, v):98 return y, f, v99100 result = runner.invoke(cli, standalone_mode=False)101 assert result.return_value == ((), (), ())102103 result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False)104 assert result.return_value == ((True, False), (True,), (1, -1))105106107def test_flag_default_map(runner):108 """test flag with default map"""109110 @click.group()111 def cli():112 pass113114 @cli.command()115 @click.option("--name/--no-name", is_flag=True, show_default=True, help="name flag")116 def foo(name):117 click.echo(name)118119 result = runner.invoke(cli, ["foo"])120 assert "False" in result.output121122 result = runner.invoke(cli, ["foo", "--help"])123 assert "default: no-name" in result.output124125 result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}})126 assert "True" in result.output127128 result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})129 assert "default: name" in result.output130131132def test_shared_param_prefers_first_default(runner):133 """The first ``default=True`` wins when multiple ``flag_value`` options share134 a parameter name, regardless of which positional option carries it.135136 .. hint::137 ``test_basic.py::test_flag_value_dual_options`` and138 ``test_options.py::test_default_dual_option_callback`` are wider139 parametrized sibling tests covering many more default-value types (``None``,140 ``UNSET``, strings, numbers) but always place the default on the first141 option. This test complements them by exercising both placements.142 """143144 @click.command145 @click.option("--red", "color", flag_value="red")146 @click.option("--green", "color", flag_value="green", default=True)147 def prefers_green(color):148 click.echo(color)149150 @click.command151 @click.option("--red", "color", flag_value="red", default=True)152 @click.option("--green", "color", flag_value="green")153 def prefers_red(color):154 click.echo(color)155156 result = runner.invoke(prefers_green, [])157 assert "green" in result.output158 result = runner.invoke(prefers_green, ["--red"])159 assert "red" in result.output160161 result = runner.invoke(prefers_red, [])162 assert "red" in result.output163 result = runner.invoke(prefers_red, ["--green"])164 assert "green" in result.output165166167@pytest.mark.parametrize(168 ("default_map", "key", "expected"),169 [170 # Key present in default_map.171 ({"email": "a@b.com"}, "email", "a@b.com"),172 # Key missing from default_map.173 ({"email": "a@b.com"}, "nonexistent", None),174 # No default_map at all / empty default_map.175 (None, "anything", None),176 ({}, "anything", None),177 # Falsy values are returned as-is.178 ({"key": None}, "key", None),179 ({"key": 0}, "key", 0),180 ({"key": ""}, "key", ""),181 ({"key": False}, "key", False),182 ],183)184def test_lookup_default_returns_hides_sentinel(default_map, key, expected):185 """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.186187 Regression test for https://github.com/pallets/click/issues/3145.188 """189 cmd = click.Command("test")190 ctx = click.Context(cmd)191 if default_map is not None:192 ctx.default_map = default_map193 assert ctx.lookup_default(key) == expected194195196def test_lookup_default_callable_in_default_map(runner):197 """A callable in ``default_map`` is invoked with ``call=True``198 (the default) and returned as-is with ``call=False``.199200 Click uses both paths internally:201 - ``get_default()`` passes ``call=False``,202 - ``resolve_ctx()`` passes ``call=True``.203 """204 factory = lambda: "lazy-value" # noqa: E731205206 # Unit-level: call=True invokes, call=False returns as-is.207 cmd = click.Command("test")208 ctx = click.Context(cmd)209 ctx.default_map = {"name": factory}210 assert ctx.lookup_default("name", call=True) == "lazy-value"211 assert ctx.lookup_default("name", call=False) is factory212213 # Integration: the callable is invoked during value resolution.214 @click.command()215 @click.option("--name", default="original", show_default=True)216 @click.pass_context217 def cli(ctx, name):218 click.echo(f"name={name!r}")219220 result = runner.invoke(cli, [], default_map={"name": factory})221 assert not result.exception222 assert "name='lazy-value'" in result.output223224 # Help rendering gets the callable via call=False, so it225 # shows "(dynamic)" rather than invoking it.226 result = runner.invoke(cli, ["--help"], default_map={"name": factory})227 assert not result.exception228 assert "(dynamic)" in result.output229230231@pytest.mark.parametrize(232 ("args", "default_map", "expected_value", "expected_source"),233 [234 # CLI arg wins over everything.235 (["--name", "cli"], {"name": "mapped"}, "cli", "COMMANDLINE"),236 # default_map overrides parameter default.237 ([], {"name": "mapped"}, "mapped", "DEFAULT_MAP"),238 # Explicit None in default_map still counts as DEFAULT_MAP.239 ([], {"name": None}, None, "DEFAULT_MAP"),240 # Falsy values in default_map are not confused with missing keys.241 ([], {"name": ""}, "", "DEFAULT_MAP"),242 ([], {"name": 0}, "0", "DEFAULT_MAP"),243 # No default_map falls back to parameter default.244 ([], None, "original", "DEFAULT"),245 ],246)247def test_default_map_source(runner, args, default_map, expected_value, expected_source):248 """``get_parameter_source()`` reports the correct origin for a parameter249 value across the resolution chain: CLI > default_map > parameter default.250 """251252 @click.command()253 @click.option("--name", default="original")254 @click.pass_context255 def cli(ctx, name):256 source = ctx.get_parameter_source("name")257 click.echo(f"name={name!r} source={source.name}")258259 kwargs = {}260 if default_map is not None:261 kwargs["default_map"] = default_map262 result = runner.invoke(cli, args, **kwargs)263 assert not result.exception264 assert f"name={expected_value!r}" in result.output265 assert f"source={expected_source}" in result.output266267268def test_lookup_default_override_respected(runner):269 """A subclass override of ``lookup_default()`` should be called by Click270 internals, not bypassed by a private method.271272 Reproduce exactly https://github.com/pallets/click/issues/3145 in which a273 subclass that falls back to prefix-based lookup when the parent returns274 ``None``.275276 Previous attempts in https://github.com/pallets/click/pr/3199 were entirely277 bypassing the user's overridded method.278 """279280 class CustomContext(click.Context):281 def lookup_default(self, name, call=True):282 default = super().lookup_default(name, call=call)283284 if default is not None:285 return default286287 # Prefix-based fallback: look up "app" sub-dict for "app_email".288 prefix = name.split("_", 1)[0]289 group = getattr(self, "default_map", None) or {}290 sub = group.get(prefix)291 if isinstance(sub, dict):292 return sub.get(name)293 return default294295 @click.command("get-views")296 @click.option("--app-email", default="original", show_default=True)297 @click.pass_context298 def cli(ctx, app_email):299 click.echo(f"app_email={app_email!r}")300301 cli.context_class = CustomContext302 default_map = {"app": {"app_email": "prefix@example.com"}}303304 # resolve_ctx path: the override provides the runtime value.305 result = runner.invoke(cli, [], default_map=default_map)306 assert not result.exception307 assert "app_email='prefix@example.com'" in result.output308309 # get_default path: the override is also used when310 # rendering --help with show_default=True.311 result = runner.invoke(cli, ["--help"], default_map=default_map)312 assert not result.exception313 assert "prefix@example.com" in result.output314315316class _Marker:317 """Dummy callable used as a flag_value in default tests."""318319 pass320321322@pytest.mark.parametrize(323 ("default_map", "args", "expected"),324 [325 # No default_map: auto-aligned default returns the class, not an instance.326 (None, [], _Marker),327 # CLI flag always returns the class.328 (None, ["--opt"], _Marker),329 # Static value in default_map overrides the auto-aligned flag_value.330 ({"value": "from-map"}, [], "from-map"),331 # Callable in default_map is still invoked (not suppressed by the fix).332 ({"value": lambda: "lazy-map"}, [], "lazy-map"),333 # None in default_map overrides the flag_value.334 ({"value": None}, [], None),335 # CLI arg wins over default_map.336 ({"value": "from-map"}, ["--opt"], _Marker),337 ],338)339def test_default_map_with_callable_flag_value(runner, default_map, args, expected):340 """``default_map`` entries should override the auto-aligned callable ``flag_value``,341 and callable entries in ``default_map`` should still be invoked.342343 Verifies the fix for https://github.com/pallets/click/issues/3121 does not344 break ``default_map`` precedence.345 """346347 @click.command()348 @click.option("--opt", "value", flag_value=_Marker, type=UNPROCESSED, default=True)349 def cli(value):350 click.echo(repr(value), nl=False)351352 kwargs = {}353 if default_map is not None:354 kwargs["default_map"] = default_map355 result = runner.invoke(cli, args, **kwargs)356 assert result.exit_code == 0357 assert result.output == repr(expected)358359360def test_unset_in_default_map(runner):361 """An ``UNSET`` value in ``default_map`` should be treated as if362 the key is absent, and so fallback to the parameter's own default.363364 Refs: https://github.com/pallets/click/pull/3224#issuecomment-3968643305365 """366367 @click.command(368 context_settings={"default_map": {"port": UNSET}},369 )370 @click.option("--port", default=8000)371 def cli(port):372 click.echo(f"port={port}")373374 result = runner.invoke(cli, [])375 assert result.exit_code == 0376 assert result.output.strip() == "port=8000"