test_defaults.py
This file
Path
tests/test_defaults.py
567 lines · 19.1 KiB · Python
Last changed by
Stable (#3851)Rowlando13before adoption6aabf09
History of this fileTake 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 # Falsy containers are returned as-is too.186 ({"key": set()}, "key", set()),187 ({"key": frozenset()}, "key", frozenset()),188 ({"key": {}}, "key", {}),189 ],190)191def test_lookup_default_returns_hides_sentinel(default_map, key, expected):192 """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.193194 Regression test for https://github.com/pallets/click/issues/3145.195 """196 cmd = click.Command("test")197 ctx = click.Context(cmd)198 if default_map is not None:199 ctx.default_map = default_map200 assert ctx.lookup_default(key) == expected201202203def test_lookup_default_callable_in_default_map(runner):204 """A callable in ``default_map`` is invoked with ``call=True``205 (the default) and returned as-is with ``call=False``.206207 Click uses both paths internally:208 - ``get_default()`` passes ``call=False``,209 - ``resolve_ctx()`` passes ``call=True``.210 """211 factory = lambda: "lazy-value" # noqa: E731212213 # Unit-level: call=True invokes, call=False returns as-is.214 cmd = click.Command("test")215 ctx = click.Context(cmd)216 ctx.default_map = {"name": factory}217 assert ctx.lookup_default("name", call=True) == "lazy-value"218 assert ctx.lookup_default("name", call=False) is factory219220 # Integration: the callable is invoked during value resolution.221 @click.command()222 @click.option("--name", default="original", show_default=True)223 @click.pass_context224 def cli(ctx, name):225 click.echo(f"name={name!r}")226227 result = runner.invoke(cli, [], default_map={"name": factory})228 assert not result.exception229 assert "name='lazy-value'" in result.output230231 # Help rendering gets the callable via call=False, so it232 # shows "(dynamic)" rather than invoking it.233 result = runner.invoke(cli, ["--help"], default_map={"name": factory})234 assert not result.exception235 assert "(dynamic)" in result.output236237238@pytest.mark.parametrize(239 ("args", "default_map", "expected_value", "expected_source"),240 [241 # CLI arg wins over everything.242 (["--name", "cli"], {"name": "mapped"}, "cli", "COMMANDLINE"),243 # default_map overrides parameter default.244 ([], {"name": "mapped"}, "mapped", "DEFAULT_MAP"),245 # Explicit None in default_map still counts as DEFAULT_MAP.246 ([], {"name": None}, None, "DEFAULT_MAP"),247 # Falsy values in default_map are not confused with missing keys.248 ([], {"name": ""}, "", "DEFAULT_MAP"),249 ([], {"name": 0}, "0", "DEFAULT_MAP"),250 # No default_map falls back to parameter default.251 ([], None, "original", "DEFAULT"),252 ],253)254def test_default_map_source(runner, args, default_map, expected_value, expected_source):255 """``get_parameter_source()`` reports the correct origin for a parameter256 value across the resolution chain: CLI > default_map > parameter default.257 """258259 @click.command()260 @click.option("--name", default="original")261 @click.pass_context262 def cli(ctx, name):263 source = ctx.get_parameter_source("name")264 click.echo(f"name={name!r} source={source.name}")265266 kwargs = {}267 if default_map is not None:268 kwargs["default_map"] = default_map269 result = runner.invoke(cli, args, **kwargs)270 assert not result.exception271 assert f"name={expected_value!r}" in result.output272 assert f"source={expected_source}" in result.output273274275def test_parameter_source_during_paramtype_convert(runner):276 """``get_parameter_source()`` is available during ``ParamType.convert``.277278 Uses the reproducer from https://github.com/pallets/click/issues/3458.279 """280281 class Source(click.ParamType):282 name = "source"283284 def convert(self, value, param, ctx):285 return {286 "value": value,287 "source": ctx.get_parameter_source(param.name),288 }289290 @click.command()291 @click.option("--default", type=Source(), default="/tmp/file")292 @click.option("--nodefault", type=Source())293 def cli(default, nodefault):294 click.echo(f"default: {default}")295 click.echo(f"nodefault: {nodefault}")296297 result = runner.invoke(cli, [])298 assert not result.exception299 assert "default: {'value': '/tmp/file', 'source': " in result.output300 assert "'source': None}" not in result.output.split("default:")[1].split("\n")[0]301 assert (302 result.output == "default: {'value': '/tmp/file', 'source': "303 f"{ParameterSource.DEFAULT!r}}}\nnodefault: None\n"304 )305306 result = runner.invoke(cli, ["--default", "cli", "--nodefault", "also"])307 assert not result.exception308 assert (309 "default: {'value': 'cli', 'source': "310 f"{ParameterSource.COMMANDLINE!r}}}" in result.output311 )312 assert (313 "nodefault: {'value': 'also', 'source': "314 f"{ParameterSource.COMMANDLINE!r}}}" in result.output315 )316317318def test_parameter_source_during_eager_callback(runner):319 """``get_parameter_source()`` is available during eager callbacks.320321 Regression test for https://github.com/pallets/click/issues/3458.322 """323324 def eager_cb(ctx, param, value):325 source = ctx.get_parameter_source(param.name)326 click.echo(f"callback source={source.name if source else None}")327328 @click.command()329 @click.option(330 "--flag/--no-flag",331 default=False,332 is_eager=True,333 callback=eager_cb,334 expose_value=False,335 )336 def cli():337 source = click.get_current_context().get_parameter_source("flag")338 click.echo(f"final source={source.name}")339340 result = runner.invoke(cli, [])341 assert not result.exception342 assert "callback source=DEFAULT" in result.output343 assert "final source=DEFAULT" in result.output344345 result = runner.invoke(cli, ["--flag"])346 assert not result.exception347 assert "callback source=COMMANDLINE" in result.output348 assert "final source=COMMANDLINE" in result.output349350351def test_flask_debug_env_not_stomped_by_default_flag(runner, monkeypatch):352 """Eager callback must not overwrite env when the flag used its default.353354 Covers the Flask ``_set_debug`` pattern (pallets/flask#6025). Regression test355 for https://github.com/pallets/click/issues/3458.356 """357358 monkeypatch.delenv("APP_DEBUG", raising=False)359360 def set_debug(ctx, param, value):361 source = ctx.get_parameter_source(param.name)362 if source is not None and source in (363 ParameterSource.DEFAULT,364 ParameterSource.DEFAULT_MAP,365 ):366 return None367 os.environ["APP_DEBUG"] = "1" if value else "0"368 return value369370 @click.command()371 @click.option(372 "--debug/--no-debug",373 default=False,374 is_eager=True,375 expose_value=False,376 callback=set_debug,377 )378 def cli():379 click.echo(f"APP_DEBUG={os.environ.get('APP_DEBUG', '')}")380381 monkeypatch.setenv("APP_DEBUG", "1")382 result = runner.invoke(cli, [])383 assert result.exit_code == 0384 assert result.output.strip() == "APP_DEBUG=1"385386 result = runner.invoke(cli, ["--debug"])387 assert result.exit_code == 0388 assert result.output.strip() == "APP_DEBUG=1"389390 result = runner.invoke(cli, ["--no-debug"])391 assert result.exit_code == 0392 assert result.output.strip() == "APP_DEBUG=0"393394395def test_parameter_source_on_parse_result_bypass(runner):396 """A losing option keeps its provisional source when ``ctx.params[name]``397 is populated by code that bypassed ``handle_parse_result``.398399 This replicate the pattern documented in the "Parameter Modifications" section400 of ``docs/advanced.md``. This test highlight the current behavior of401 ``get_parameter_source()`` but is not intended as a contract enforcement.402 """403404 def hijack(ctx, param, value):405 ctx.params["target"] = "hijacked"406 return value407408 @click.command()409 @click.option("--hijacker", is_eager=True, callback=hijack, expose_value=False)410 @click.option("--target", default="default_value")411 @click.pass_context412 def cli(ctx, target):413 source = ctx.get_parameter_source("target")414 click.echo(f"value={target} source={source.name if source else 'None'}")415416 result = runner.invoke(cli, ["--hijacker", "anything"])417 assert result.exit_code == 0, result.output418 assert "value=hijacked" in result.output419 assert "source=DEFAULT" in result.output420421422def test_lookup_default_override_respected(runner):423 """A subclass override of ``lookup_default()`` should be called by Click424 internals, not bypassed by a private method.425426 Reproduce exactly https://github.com/pallets/click/issues/3145 in which a427 subclass that falls back to prefix-based lookup when the parent returns428 ``None``.429430 Previous attempts in https://github.com/pallets/click/pr/3199 were entirely431 bypassing the user's overridden method.432 """433434 class CustomContext(click.Context):435 def lookup_default(self, name, call=True):436 default = super().lookup_default(name, call=call)437438 if default is not None:439 return default440441 # Prefix-based fallback: look up "app" sub-dict for "app_email".442 prefix = name.split("_", 1)[0]443 group = getattr(self, "default_map", None) or {}444 sub = group.get(prefix)445 if isinstance(sub, dict):446 return sub.get(name)447 return default448449 @click.command("get-views")450 @click.option("--app-email", default="original", show_default=True)451 @click.pass_context452 def cli(ctx, app_email):453 click.echo(f"app_email={app_email!r}")454455 cli.context_class = CustomContext456 default_map = {"app": {"app_email": "prefix@example.com"}}457458 # resolve_ctx path: the override provides the runtime value.459 result = runner.invoke(cli, [], default_map=default_map)460 assert not result.exception461 assert "app_email='prefix@example.com'" in result.output462463 # get_default path: the override is also used when464 # rendering --help with show_default=True.465 result = runner.invoke(cli, ["--help"], default_map=default_map)466 assert not result.exception467 assert "prefix@example.com" in result.output468469470class _Marker:471 """Dummy callable used as a flag_value in default tests."""472473 pass474475476@pytest.mark.parametrize(477 ("default_map", "args", "expected"),478 [479 # No default_map: auto-aligned default returns the class, not an instance.480 (None, [], _Marker),481 # CLI flag always returns the class.482 (None, ["--opt"], _Marker),483 # Static value in default_map overrides the auto-aligned flag_value.484 ({"value": "from-map"}, [], "from-map"),485 # Callable in default_map is still invoked (not suppressed by the fix).486 ({"value": lambda: "lazy-map"}, [], "lazy-map"),487 # None in default_map overrides the flag_value.488 ({"value": None}, [], None),489 # CLI arg wins over default_map.490 ({"value": "from-map"}, ["--opt"], _Marker),491 ],492)493def test_default_map_with_callable_flag_value(runner, default_map, args, expected):494 """``default_map`` entries should override the auto-aligned callable ``flag_value``,495 and callable entries in ``default_map`` should still be invoked.496497 Verifies the fix for https://github.com/pallets/click/issues/3121 does not498 break ``default_map`` precedence.499 """500501 @click.command()502 @click.option("--opt", "value", flag_value=_Marker, type=UNPROCESSED, default=True)503 def cli(value):504 click.echo(repr(value), nl=False)505506 kwargs = {}507 if default_map is not None:508 kwargs["default_map"] = default_map509 result = runner.invoke(cli, args, **kwargs)510 assert result.exit_code == 0511 assert result.output == repr(expected)512513514@pytest.mark.parametrize(515 ("default_map", "option_kwargs", "cli_args", "expected"),516 [517 # String is split for nargs=2 option.518 ({"point": "3 4"}, {"nargs": 2, "type": int}, [], (3, 4)),519 # String is split for explicit Tuple type.520 ({"point": "hello world"}, {"type": (str, str)}, [], ("hello", "world")),521 # Already-structured tuple passes through unchanged.522 ({"point": ("a", "b")}, {"nargs": 2}, [], ("a", "b")),523 # Already-structured list passes through unchanged.524 ({"point": [5, 6]}, {"nargs": 2, "type": int}, [], (5, 6)),525 # CLI args override default_map for nargs > 1.526 (527 {"point": "3 4"},528 {"nargs": 2, "type": int},529 ["--point", "10", "20"],530 (10, 20),531 ),532 ],533)534def test_default_map_nargs(runner, default_map, option_kwargs, cli_args, expected):535 """A string in ``default_map`` for an option with ``nargs > 1`` should be536 split the same way an environment variable string is split.537538 Regression test for https://github.com/pallets/click/issues/2745.539 """540541 @click.command()542 @click.option("--point", **option_kwargs)543 def cli(point):544 click.echo(repr(point))545546 result = runner.invoke(cli, cli_args, default_map=default_map)547 assert result.exit_code == 0548 assert result.output.strip() == repr(expected)549550551def test_unset_in_default_map(runner):552 """An ``UNSET`` value in ``default_map`` should be treated as if553 the key is absent, and so fallback to the parameter's own default.554555 Refs: https://github.com/pallets/click/pull/3224#issuecomment-3968643305556 """557558 @click.command(559 context_settings={"default_map": {"port": UNSET}},560 )561 @click.option("--port", default=8000)562 def cli(port):563 click.echo(f"port={port}")564565 result = runner.invoke(cli, [])566 assert result.exit_code == 0567 assert result.output.strip() == "port=8000"