| 1 |
import pytest |
| 2 |
|
| 3 |
import click |
| 4 |
from click import UNPROCESSED |
| 5 |
from click._utils import UNSET |
| 6 |
|
| 7 |
|
| 8 |
@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 |
) |
| 19 |
def test_basic_defaults(runner, default, type, expected_output, expected_type): |
| 20 |
"""Smoke test: a single option's default is type-coerced. |
| 21 |
|
| 22 |
This covers basic single-option default type coercion. |
| 23 |
""" |
| 24 |
|
| 25 |
@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}]") |
| 30 |
|
| 31 |
result = runner.invoke(cli, []) |
| 32 |
assert not result.exception |
| 33 |
assert f"FOO:[{expected_output}]" in result.output |
| 34 |
|
| 35 |
|
| 36 |
def test_multiple_defaults(runner): |
| 37 |
"""Smoke test: each element in a multiple-option default is type-coerced. |
| 38 |
|
| 39 |
.. hint:: |
| 40 |
``test_options.py::test_good_defaults_for_multiple`` |
| 41 |
covers the structural default processing (``list`` to |
| 42 |
``tuple``, various ``nargs``) exhaustively. |
| 43 |
|
| 44 |
This test fills the gap of explicit |
| 45 |
``type=click.FLOAT`` coercion on the elements. |
| 46 |
""" |
| 47 |
|
| 48 |
@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) |
| 54 |
|
| 55 |
result = runner.invoke(cli, []) |
| 56 |
assert not result.exception |
| 57 |
assert result.output.splitlines() == ["23.0", "42.0"] |
| 58 |
|
| 59 |
|
| 60 |
def test_nargs_plus_multiple(runner): |
| 61 |
"""Smoke test: option with ``nargs=2`` + ``multiple=True`` and a |
| 62 |
tuple-of-tuples default. |
| 63 |
|
| 64 |
.. hint:: |
| 65 |
``test_options.py::test_good_defaults_for_multiple`` |
| 66 |
expands this with many more edge cases with various |
| 67 |
``nargs``/``multiple``/``default`` combinations. |
| 68 |
|
| 69 |
An argument-specific equivalent is in |
| 70 |
``test_arguments.py::test_good_defaults_for_nargs``. |
| 71 |
""" |
| 72 |
|
| 73 |
@click.command() |
| 74 |
@click.option( |
| 75 |
"--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT |
| 76 |
) |
| 77 |
def cli(arg): |
| 78 |
for a, b in arg: |
| 79 |
click.echo(f"<{a:d}|{b:d}>") |
| 80 |
|
| 81 |
result = runner.invoke(cli, []) |
| 82 |
assert not result.exception |
| 83 |
assert result.output.splitlines() == ["<1|2>", "<3|4>"] |
| 84 |
|
| 85 |
|
| 86 |
def test_multiple_flag_default(runner): |
| 87 |
"""Default default for flags when multiple=True should be empty tuple.""" |
| 88 |
|
| 89 |
@click.command |
| 90 |
# flag due to secondary token |
| 91 |
@click.option("-y/-n", multiple=True) |
| 92 |
# flag due to is_flag |
| 93 |
@click.option("-f", is_flag=True, multiple=True) |
| 94 |
# flag due to flag_value |
| 95 |
@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, v |
| 99 |
|
| 100 |
result = runner.invoke(cli, standalone_mode=False) |
| 101 |
assert result.return_value == ((), (), ()) |
| 102 |
|
| 103 |
result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False) |
| 104 |
assert result.return_value == ((True, False), (True,), (1, -1)) |
| 105 |
|
| 106 |
|
| 107 |
def test_flag_default_map(runner): |
| 108 |
"""test flag with default map""" |
| 109 |
|
| 110 |
@click.group() |
| 111 |
def cli(): |
| 112 |
pass |
| 113 |
|
| 114 |
@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) |
| 118 |
|
| 119 |
result = runner.invoke(cli, ["foo"]) |
| 120 |
assert "False" in result.output |
| 121 |
|
| 122 |
result = runner.invoke(cli, ["foo", "--help"]) |
| 123 |
assert "default: no-name" in result.output |
| 124 |
|
| 125 |
result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}}) |
| 126 |
assert "True" in result.output |
| 127 |
|
| 128 |
result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}}) |
| 129 |
assert "default: name" in result.output |
| 130 |
|
| 131 |
|
| 132 |
def test_shared_param_prefers_first_default(runner): |
| 133 |
"""The first ``default=True`` wins when multiple ``flag_value`` options share |
| 134 |
a parameter name, regardless of which positional option carries it. |
| 135 |
|
| 136 |
.. hint:: |
| 137 |
``test_basic.py::test_flag_value_dual_options`` and |
| 138 |
``test_options.py::test_default_dual_option_callback`` are wider |
| 139 |
parametrized sibling tests covering many more default-value types (``None``, |
| 140 |
``UNSET``, strings, numbers) but always place the default on the first |
| 141 |
option. This test complements them by exercising both placements. |
| 142 |
""" |
| 143 |
|
| 144 |
@click.command |
| 145 |
@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) |
| 149 |
|
| 150 |
@click.command |
| 151 |
@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) |
| 155 |
|
| 156 |
result = runner.invoke(prefers_green, []) |
| 157 |
assert "green" in result.output |
| 158 |
result = runner.invoke(prefers_green, ["--red"]) |
| 159 |
assert "red" in result.output |
| 160 |
|
| 161 |
result = runner.invoke(prefers_red, []) |
| 162 |
assert "red" in result.output |
| 163 |
result = runner.invoke(prefers_red, ["--green"]) |
| 164 |
assert "green" in result.output |
| 165 |
|
| 166 |
|
| 167 |
@pytest.mark.parametrize( |
| 168 |
("default_map", "key", "expected"), |
| 169 |
[ |
| 170 |
# Key present in default_map. |
| 171 |
({"email": "[email protected]"}, "email", "[email protected]"), |
| 172 |
# Key missing from default_map. |
| 173 |
({"email": "[email protected]"}, "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 |
) |
| 184 |
def test_lookup_default_returns_hides_sentinel(default_map, key, expected): |
| 185 |
"""``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`. |
| 186 |
|
| 187 |
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_map |
| 193 |
assert ctx.lookup_default(key) == expected |
| 194 |
|
| 195 |
|
| 196 |
def 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``. |
| 199 |
|
| 200 |
Click uses both paths internally: |
| 201 |
- ``get_default()`` passes ``call=False``, |
| 202 |
- ``resolve_ctx()`` passes ``call=True``. |
| 203 |
""" |
| 204 |
factory = lambda: "lazy-value" # noqa: E731 |
| 205 |
|
| 206 |
# 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 factory |
| 212 |
|
| 213 |
# Integration: the callable is invoked during value resolution. |
| 214 |
@click.command() |
| 215 |
@click.option("--name", default="original", show_default=True) |
| 216 |
@click.pass_context |
| 217 |
def cli(ctx, name): |
| 218 |
click.echo(f"name={name!r}") |
| 219 |
|
| 220 |
result = runner.invoke(cli, [], default_map={"name": factory}) |
| 221 |
assert not result.exception |
| 222 |
assert "name='lazy-value'" in result.output |
| 223 |
|
| 224 |
# Help rendering gets the callable via call=False, so it |
| 225 |
# shows "(dynamic)" rather than invoking it. |
| 226 |
result = runner.invoke(cli, ["--help"], default_map={"name": factory}) |
| 227 |
assert not result.exception |
| 228 |
assert "(dynamic)" in result.output |
| 229 |
|
| 230 |
|
| 231 |
@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 |
) |
| 247 |
def test_default_map_source(runner, args, default_map, expected_value, expected_source): |
| 248 |
"""``get_parameter_source()`` reports the correct origin for a parameter |
| 249 |
value across the resolution chain: CLI > default_map > parameter default. |
| 250 |
""" |
| 251 |
|
| 252 |
@click.command() |
| 253 |
@click.option("--name", default="original") |
| 254 |
@click.pass_context |
| 255 |
def cli(ctx, name): |
| 256 |
source = ctx.get_parameter_source("name") |
| 257 |
click.echo(f"name={name!r} source={source.name}") |
| 258 |
|
| 259 |
kwargs = {} |
| 260 |
if default_map is not None: |
| 261 |
kwargs["default_map"] = default_map |
| 262 |
result = runner.invoke(cli, args, **kwargs) |
| 263 |
assert not result.exception |
| 264 |
assert f"name={expected_value!r}" in result.output |
| 265 |
assert f"source={expected_source}" in result.output |
| 266 |
|
| 267 |
|
| 268 |
def test_lookup_default_override_respected(runner): |
| 269 |
"""A subclass override of ``lookup_default()`` should be called by Click |
| 270 |
internals, not bypassed by a private method. |
| 271 |
|
| 272 |
Reproduce exactly https://github.com/pallets/click/issues/3145 in which a |
| 273 |
subclass that falls back to prefix-based lookup when the parent returns |
| 274 |
``None``. |
| 275 |
|
| 276 |
Previous attempts in https://github.com/pallets/click/pr/3199 were entirely |
| 277 |
bypassing the user's overridded method. |
| 278 |
""" |
| 279 |
|
| 280 |
class CustomContext(click.Context): |
| 281 |
def lookup_default(self, name, call=True): |
| 282 |
default = super().lookup_default(name, call=call) |
| 283 |
|
| 284 |
if default is not None: |
| 285 |
return default |
| 286 |
|
| 287 |
# 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 default |
| 294 |
|
| 295 |
@click.command("get-views") |
| 296 |
@click.option("--app-email", default="original", show_default=True) |
| 297 |
@click.pass_context |
| 298 |
def cli(ctx, app_email): |
| 299 |
click.echo(f"app_email={app_email!r}") |
| 300 |
|
| 301 |
cli.context_class = CustomContext |
| 302 |
default_map = {"app": {"app_email": "[email protected]"}} |
| 303 |
|
| 304 |
# resolve_ctx path: the override provides the runtime value. |
| 305 |
result = runner.invoke(cli, [], default_map=default_map) |
| 306 |
assert not result.exception |
| 307 |
assert "app_email='[email protected]'" in result.output |
| 308 |
|
| 309 |
# get_default path: the override is also used when |
| 310 |
# rendering --help with show_default=True. |
| 311 |
result = runner.invoke(cli, ["--help"], default_map=default_map) |
| 312 |
assert not result.exception |
| 313 |
assert "[email protected]" in result.output |
| 314 |
|
| 315 |
|
| 316 |
class _Marker: |
| 317 |
"""Dummy callable used as a flag_value in default tests.""" |
| 318 |
|
| 319 |
pass |
| 320 |
|
| 321 |
|
| 322 |
@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 |
) |
| 339 |
def 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. |
| 342 |
|
| 343 |
Verifies the fix for https://github.com/pallets/click/issues/3121 does not |
| 344 |
break ``default_map`` precedence. |
| 345 |
""" |
| 346 |
|
| 347 |
@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) |
| 351 |
|
| 352 |
kwargs = {} |
| 353 |
if default_map is not None: |
| 354 |
kwargs["default_map"] = default_map |
| 355 |
result = runner.invoke(cli, args, **kwargs) |
| 356 |
assert result.exit_code == 0 |
| 357 |
assert result.output == repr(expected) |
| 358 |
|
| 359 |
|
| 360 |
def test_unset_in_default_map(runner): |
| 361 |
"""An ``UNSET`` value in ``default_map`` should be treated as if |
| 362 |
the key is absent, and so fallback to the parameter's own default. |
| 363 |
|
| 364 |
Refs: https://github.com/pallets/click/pull/3224#issuecomment-3968643305 |
| 365 |
""" |
| 366 |
|
| 367 |
@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}") |
| 373 |
|
| 374 |
result = runner.invoke(cli, []) |
| 375 |
assert result.exit_code == 0 |
| 376 |
assert result.output.strip() == "port=8000" |