Merge pull request #1687 from pallets/multiple-tuple
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents b631e5a, ffe7a3b · Browse files · 10 files·+271 added−129 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+271 added−129 removed
- tests:+97 added−43 removed
- other:+174 added−86 removed
Provenance
- Commit
c067af7- Tree
6736bbf- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
b631e5a- Parent 2
ffe7a3b
10 files changed+271 added−129 removed
modified:src/click/core.py+78 added-36 removed
140 unmodified lines141 source for a parameter by name.142 143 .. versionchanged:: 8.0144 Use :class:`~enum.Enum` and drop the ``validate`` method.145+146+ .. versionchanged:: 8.0147+ Added the ``PROMPT`` value.148 """149 150 COMMANDLINE = enum.auto()151 """The value was provided by the command line args."""2 unmodified lines154 DEFAULT = enum.auto()155 """Used the default specified by the parameter."""156 DEFAULT_MAP = enum.auto()157 """Used a default provided by :attr:`Context.default_map`."""158+ PROMPT = enum.auto()159+ """Used a prompt to confirm a default or provide a value."""160 161 162 class Context:163 """The context is a special internal object that holds state relevant117 unmodified lines281 self.info_name = info_name282 #: Map of parameter names to their parsed values. Parameters283 #: with ``expose_value=False`` are not stored.284 self.params = {}280- # This tracks the actual param objects that were parsed, even if281- # they didn't expose a value. Used by completion system to know282- # what parameters to exclude.283- self._seen_params = set()285 #: the leftover arguments.286 self.args = []287 #: protected arguments. These are arguments that are prepended288 #: to `args` when certain parsing scenarios are encountered but448 unmodified lines737 value was actually taken from the default.738 739 :param name: The name of the parameter.740 :rtype: ParameterSource741+742+ .. versionchanged:: 8.0743+ Returns ``None`` if the parameter was not provided from any744+ source.745 """741- return self._parameter_source[name]746+ return self._parameter_source.get(name)747 748 749 class BaseCommand:750 """The base command implements the minimal API contract of commands.536 unmodified lines1287 for param in self.get_params(ctx):1288 if (1289 not isinstance(param, Option)1290 or param.hidden1286- or (not param.multiple and param in ctx._seen_params)1291+ or (1292+ not param.multiple1293+ and ctx.get_parameter_source(param.name)1294+ is ParameterSource.COMMANDLINE1295+ )1296 ):1297 continue1298 1299 results.extend(487 unmodified lines1787 semantics described above. The old name is deprecated and will1788 be removed in 8.1, until then it will be wrapped to match the1789 new requirements.1790 1791+ .. versionchanged:: 8.01792+ For ``multiple=True, nargs>1``, the default must be a list of1793+ tuples.1794+1795+ .. versionchanged:: 8.01796+ Setting a default is no longer required for ``nargs>1``, it will1797+ default to ``None``. ``multiple=True`` or ``nargs=-1`` will1798+ default to ``()``.1799+1800 .. versionchanged:: 7.11801 Empty environment variables are ignored rather than taking the1802 empty string value. This makes it possible for scripts to clear1803 variables if they can't unset them.139 unmodified lines1943 if value is None:1944 value = ctx.lookup_default(self.name)1945 source = ParameterSource.DEFAULT_MAP1946 1929- if value is not None:1930- ctx.set_parameter_source(self.name, source)1947+ if value is None:1948+ value = self.get_default(ctx)1949+ source = ParameterSource.DEFAULT1950 1932- return value1951+ return value, source1952 1953 def type_cast_value(self, ctx, value):1954 """Given a value this runs it properly through the type system.1955 This automatically handles things like `nargs` and `multiple` as1956 well as composite types.1957 """1958+ if value is None:1959+ return () if self.multiple or self.nargs == -1 else None1960+1961 if self.type.is_composite:1962 if self.nargs <= 1:1963 raise TypeError(1964 "Attempted to invoke composite type but nargs has"1965 f" been set to {self.nargs}. This is not supported;"1966 " nargs needs to be set to a fixed value > 1."1967 )1968+1969 if self.multiple:1947- return tuple(self.type(x or (), self, ctx) for x in value or ())1948- return self.type(value or (), self, ctx)1970+ return tuple(self.type(x, self, ctx) for x in value)1971 1972+ return self.type(value, self, ctx)1973+1974 def _convert(value, level):1975 if level == 0:1976 return self.type(value, self, ctx)1953- return tuple(_convert(x, level - 1) for x in value or ())1977 1978+ return tuple(_convert(x, level - 1) for x in value)1979+1980 return _convert(value, (self.nargs != 1) + bool(self.multiple))1981 1982 def process_value(self, ctx, value):1983 """Given a value and context this runs the logic to convert the15 unmodified lines1999 2000 def full_process_value(self, ctx, value):2001 value = self.process_value(ctx, value)2002 1978- if value is None and not ctx.resilient_parsing:1979- value = self.get_default(ctx)1980-1981- if value is not None:1982- ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)1983-2003 if self.required and self.value_is_missing(value):2004 raise MissingParameter(ctx=ctx, param=self)2005 2006 # For bounded nargs (!= -1), validate the number of values.2007 if (2008 not ctx.resilient_parsing2009 and self.nargs > 11991- and self.nargs != len(value)2010 and isinstance(value, (tuple, list))2011+ and (2012+ any(len(v) != self.nargs for v in value)2013+ if self.multiple2014+ else len(value) != self.nargs2015+ )2016 ):2017 were = "was" if len(value) == 1 else "were"2018 ctx.fail(2019 f"Argument {self.name!r} takes {self.nargs} values but"4 unmodified lines2024 2025 def resolve_envvar_value(self, ctx):2026 if self.envvar is None:2027 return2028+2029 if isinstance(self.envvar, (tuple, list)):2030 for envvar in self.envvar:2031 rv = os.environ.get(envvar)2008- if rv is not None:2032+2033+ if rv:2034 return rv2035 else:2036 rv = os.environ.get(self.envvar)2037 2013- if rv != "":2038+ if rv:2039 return rv2040 2041 def value_from_envvar(self, ctx):2042 rv = self.resolve_envvar_value(ctx)2043+2044 if rv is not None and self.nargs != 1:2045 rv = self.type.split_envvar_value(rv)2046+2047 return rv2048 2049 def handle_parse_result(self, ctx, opts, args):2050 with augment_usage_errors(ctx, param=self):2024- value = self.consume_value(ctx, opts)2051+ value, source = self.consume_value(ctx, opts)2052+ ctx.set_parameter_source(self.name, source)2053+2054 try:2055 value = self.full_process_value(ctx, value)2056+2057+ if self.callback is not None:2058+ value = self.callback(ctx, self, value)2059 except Exception:2060 if not ctx.resilient_parsing:2061 raise2062+2063 value = None2031- if self.callback is not None:2032- try:2033- value = self.callback(ctx, self, value)2034- except Exception:2035- if not ctx.resilient_parsing:2036- raise2064 2065 if self.expose_value:2066 ctx.params[self.name] = value2067 2041- if value is not None:2042- ctx._seen_params.add(self)2043-2068 return value, args2069 2070 def get_help_record(self, ctx):2071 pass355 unmodified lines2427 rv = super().resolve_envvar_value(ctx)2428 2429 if rv is not None:2430 return rv2431+2432 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:2433 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"2409- return os.environ.get(envvar)2434+ rv = os.environ.get(envvar)2435 2436+ if rv:2437+ return rv2438+2439 def value_from_envvar(self, ctx):2440 rv = self.resolve_envvar_value(ctx)2441+2442 if rv is None:2443 return None2444+2445 value_depth = (self.nargs != 1) + bool(self.multiple)2446+2447 if value_depth > 0 and rv is not None:2448 rv = self.type.split_envvar_value(rv)2449+2450 if self.multiple and self.nargs != 1:2451 rv = batch(rv, self.nargs)2452+2453 return rv2454 2422- def full_process_value(self, ctx, value):2423- if value is None and self.prompt is not None and not ctx.resilient_parsing:2424- return self.prompt_for_value(ctx)2455+ def consume_value(self, ctx, opts):2456+ value, source = super().consume_value(ctx, opts)2457 2426- return super().full_process_value(ctx, value)2458+ # The value wasn't set, or used the param's default, prompt if2459+ # prompting is enabled.2460+ if (2461+ source in {None, ParameterSource.DEFAULT}2462+ and self.prompt is not None2463+ and not ctx.resilient_parsing2464+ ):2465+ value = self.prompt_for_value(ctx)2466+ source = ParameterSource.PROMPT2467 2468+ return value, source2469 2470+2471 class Argument(Parameter):2472 """Arguments are positional parameters to a command. They generally2473 provide fewer features than options but can have infinite ``nargs``2474 and are required by default.61 unmodified linesmodified:src/click/shell_completion.py+19 added-18 removed
2 unmodified lines3 4 from .core import Argument5 from .core import MultiCommand6 from .core import Option7+from .core import ParameterSource8 from .parser import split_arg_string9 from .utils import echo10 11 383 unmodified lines395 """396 return _available_shells.get(shell)397 398 398-def _is_incomplete_argument(values, param):399+def _is_incomplete_argument(ctx, param):400 """Determine if the given parameter is an argument that can still401 accept values.402 402- :param values: Dict of param names and values parsed from the403- command line args.403+ :param ctx: Invocation context for the command represented by the404+ parsed complete args.405 :param param: Argument object being checked.406 """407 if not isinstance(param, Argument):408 return False409 409- value = values[param.name]410+ value = ctx.params[param.name]411+ return (412+ param.nargs == -1413+ or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE414+ or (415+ param.nargs > 1416+ and isinstance(value, (tuple, list))417+ and len(value) < param.nargs418+ )419+ )420 411- if value is None:412- return True421 414- if param.nargs == -1:415- return True416-417- if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:418- return True419-420- return False421-422-422 def _start_of_option(value):423 """Check if the value looks like the start of an option."""424 return value and not value[0].isalnum()425 95 unmodified lines521 # command will provide option name completions.522 if "--" not in args and _start_of_option(incomplete):523 return ctx.command, incomplete524 525+ params = ctx.command.get_params(ctx)526+527 # If the last complete arg is an option name with an incomplete528 # value, the option will provide value completions.528- for param in ctx.command.get_params(ctx):529+ for param in params:530 if _is_incomplete_option(args, param):531 return param, incomplete532 533 # It's not an option name or value. The first argument without a534 # parsed value will provide value completions.534- for param in ctx.command.get_params(ctx):535- if _is_incomplete_argument(ctx.params, param):535+ for param in params:536+ if _is_incomplete_argument(ctx, param):537 return param, incomplete538 539 # There were no unparsed arguments, the command may be a group that540 # will provide command name completions.1 unmodified linemodified:src/click/types.py+55 added-31 removed
179 unmodified lines180 value = value.decode("utf-8", "replace")181 else:182 value = value.decode("utf-8", "replace")183 return value184- return value184+ return str(value)185 186 def __repr__(self):187 return "STRING"188 65 unmodified lines254 255 if normed_value in normed_choices:256 return normed_choices[normed_value]257 258- self.fail(259- f"invalid choice: {value}. (choose from {', '.join(self.choices)})",260- param,261- ctx,262- )258+ one_of = "one of " if len(self.choices) > 1 else ""259+ choices_str = ", ".join(repr(c) for c in self.choices)260+ self.fail(f"{value!r} is not {one_of}{choices_str}.", param, ctx)261 262 def __repr__(self):263 return f"Choice({list(self.choices)})"264 52 unmodified lines317 except ValueError:318 return None319 320 def convert(self, value, param, ctx):323- # Exact match321+ if isinstance(value, datetime):322+ return value323+324 for format in self.formats:325- dtime = self._try_to_convert_date(value, format)326- if dtime:327- return dtime325+ converted = self._try_to_convert_date(value, format)326 327+ if converted is not None:328+ return converted329+330+ plural = "s" if len(self.formats) > 1 else ""331+ formats_str = ", ".join(repr(f) for f in self.formats)332 self.fail(330- f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})"333+ f"{value!r} does not match the format{plural} {formats_str}.", param, ctx334 )335 336 def __repr__(self):337 return "DateTime"5 unmodified lines343 def convert(self, value, param, ctx):344 try:345 return self._number_class(value)346 except ValueError:344- self.fail(f"{value} is not a valid {self.name}", param, ctx)347+ self.fail(f"{value!r} is not a valid {self.name}.", param, ctx)348 349 350 class _NumberRangeBase(_NumberParamTypeBase):351 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):145 unmodified lines497 class BoolParamType(ParamType):498 name = "boolean"499 500 def convert(self, value, param, ctx):498- if isinstance(value, bool):501+ if value in {False, True}:502 return bool(value)503 504 norm = value.strip().lower()505 2 unmodified lines508 509 if norm in {"0", "false", "f", "no", "n", "off"}:510 return False511 509- self.fail(f"{value!r} is not a valid boolean value.", param, ctx)512+ self.fail(f"{value!r} is not a valid boolean.", param, ctx)513 514 def __repr__(self):515 return "BOOL"516 3 unmodified lines520 521 def convert(self, value, param, ctx):522 import uuid523 524+ if isinstance(value, uuid.UUID):525+ return value526+527+ value = value.strip()528+529 try:530 return uuid.UUID(value)531 except ValueError:524- self.fail(f"{value} is not a valid UUID value", param, ctx)532+ self.fail(f"{value!r} is not a valid UUID.", param, ctx)533 534 def __repr__(self):535 return "UUID"536 80 unmodified lines617 else:618 ctx.call_on_close(safecall(f.flush))619 return f620 except OSError as e: # noqa: B014613- self.fail(614- f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}",615- param,616- ctx,617- )621+ self.fail(f"{filename_to_ui(value)!r}: {get_strerror(e)}", param, ctx)622 623 def shell_complete(self, ctx, param, incomplete):624 """Return a special completion marker that tells the completion625 system to use the shell to provide file path completions.195 unmodified lines821 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))822 823 824 def convert_type(ty, default=None):821- """Converts a callable or python type into the most appropriate822- param type.825+ """Find the most appropriate :class:`ParamType` for the given Python826+ type. If the type isn't provided, it can be inferred from a default827+ value.828 """829 guessed_type = False830+831 if ty is None and default is not None:826- if isinstance(default, tuple):827- ty = tuple(map(type, default))832+ if isinstance(default, (tuple, list)):833+ # If the default is empty, ty will remain None and will834+ # return STRING.835+ if default:836+ item = default[0]837+838+ # A tuple of tuples needs to detect the inner types.839+ # Can't call convert recursively because that would840+ # incorrectly unwind the tuple to a single type.841+ if isinstance(item, (tuple, list)):842+ ty = tuple(map(type, item))843+ else:844+ ty = type(item)845 else:846 ty = type(default)847+848 guessed_type = True849 850 if isinstance(ty, tuple):851 return Tuple(ty)852+853 if isinstance(ty, ParamType):854 return ty855+856 if ty is str or ty is None:857 return STRING858+859 if ty is int:860 return INT840- # Booleans are only okay if not guessed. This is done because for841- # flags the default value is actually a bit of a lie in that it842- # indicates which of the flags is the one we want. See get_default()843- # for more information.844- if ty is bool and not guessed_type:845- return BOOL861+862 if ty is float:863 return FLOAT864+865+ # Booleans are only okay if not guessed. For is_flag options with866+ # flag_value, default=True indicates which flag_value is the867+ # default.868+ if ty is bool and not guessed_type:869+ return BOOL870+871 if guessed_type:872 return STRING873 851- # Catch a common mistake874 if __debug__:875 try:876 if issubclass(ty, ParamType):877 raise AssertionError(878 f"Attempted to use an uninstantiated parameter type ({ty})."879 )880 except TypeError:881+ # ty is an instance (correct), so issubclass fails.882 pass883+884 return FuncParamType(ty)885 886 887 #: A dummy parameter type that just does nothing. From a user's30 unmodified linesmodified:tests/test_arguments.py+15 added-12 removed
162 unmodified lines163 assert result.output == "Foo bar baz\n"164 165 166 @pytest.mark.parametrize(167- ("nargs", "value", "code", "output"),167+ ("nargs", "value", "expect"),168 [169- (2, "", 2, "Argument 'arg' takes 2 values but 0 were given."),170- (2, "a", 2, "Argument 'arg' takes 2 values but 1 was given."),171- (2, "a b", 0, "len 2"),172- (2, "a b c", 2, "Argument 'arg' takes 2 values but 3 were given."),173- (-1, "a b c", 0, "len 3"),174- (-1, "", 0, "len 0"),169+ (2, "", None),170+ (2, "a", "Argument 'arg' takes 2 values but 1 was given."),171+ (2, "a b", ("a", "b")),172+ (2, "a b c", "Argument 'arg' takes 2 values but 3 were given."),173+ (-1, "a b c", ("a", "b", "c")),174+ (-1, "", ()),175 ],176 )177-def test_nargs_envvar(runner, nargs, value, code, output):177+def test_nargs_envvar(runner, nargs, value, expect):178 if nargs == -1:179 param = click.argument("arg", envvar="X", nargs=nargs)180 else:181 param = click.option("--arg", envvar="X", nargs=nargs)182 183 @click.command()184 @param185 def cmd(arg):186- click.echo(f"len {len(arg)}")186+ return arg187 188- result = runner.invoke(cmd, env={"X": value})189- assert result.exit_code == code190- assert output in result.output188+ result = runner.invoke(cmd, env={"X": value}, standalone_mode=False)189 190+ if isinstance(expect, str):191+ assert expect in str(result.exception)192+ else:193+ assert result.return_value == expect194 195+196 def test_empty_nargs(runner):197 @click.command()198 @click.argument("arg", nargs=-1)199 def cmd(arg):175 unmodified linesmodified:tests/test_basic.py+10 added-14 removed
145 unmodified lines146 assert "FOO:[46]" in result.output147 148 result = runner.invoke(cli, ["--foo=bar"])149 assert result.exception150- assert "Invalid value for '--foo': bar is not a valid integer" in result.output150+ assert "Invalid value for '--foo': 'bar' is not a valid integer." in result.output151 152 153 def test_uuid_option(runner):154 @click.command()13 unmodified lines168 assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output169 170 result = runner.invoke(cli, ["--u=bar"])171 assert result.exception172- assert "Invalid value for '--u': bar is not a valid UUID value" in result.output172+ assert "Invalid value for '--u': 'bar' is not a valid UUID." in result.output173 174 175 def test_float_option(runner):176 @click.command()11 unmodified lines188 assert "FOO:[23.5]" in result.output189 190 result = runner.invoke(cli, ["--foo=bar"])191 assert result.exception192- assert "Invalid value for '--foo': bar is not a valid float" in result.output192+ assert "Invalid value for '--foo': 'bar' is not a valid float." in result.output193 194 195 def test_boolean_option(runner):196 for default in True, False:105 unmodified lines302 with runner.isolated_filesystem():303 os.mkdir("example.txt")304 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])305 assert result_in.exit_code == 2306- assert (307- "Invalid value for '--file': Could not open file: example.txt"308- in result_in.output309- )306+ assert "Invalid value for '--file': 'example.txt'" in result_in.output307 308 309 def test_path_option(runner):310 @click.command()53 unmodified lines364 365 result = runner.invoke(cli, ["--method=meh"])366 assert result.exit_code == 2367 assert (371- "Invalid value for '--method': invalid choice: meh."372- " (choose from foo, bar, baz)" in result.output368+ "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."369+ in result.output370 )371 372 result = runner.invoke(cli, ["--help"])373 assert "--method [foo|bar|baz]" in result.output11 unmodified lines385 386 result = runner.invoke(cli, ["meh"])387 assert result.exit_code == 2388 assert (392- "Invalid value for '{foo|bar|baz}': invalid choice: meh. "393- "(choose from foo, bar, baz)" in result.output389+ "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"390+ " 'bar', 'baz'." in result.output391 )392 393 result = runner.invoke(cli, ["--help"])394 assert "{foo|bar|baz}" in result.output15 unmodified lines410 411 result = runner.invoke(cli, ["--start_date=2015-09"])412 assert result.exit_code == 2413 assert (417- "Invalid value for '--start_date':"418- " invalid datetime format: 2015-09."419- " (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"414+ "Invalid value for '--start_date': '2015-09' does not match the formats"415+ " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."416 ) in result.output417 418 result = runner.invoke(cli, ["--help"])419 assert (111 unmodified linesmodified:tests/test_formatting.py+1 added-1 removed
193 unmodified lines194 assert result.output.splitlines() == [195 "Usage: cmd [OPTIONS] metavar",196 "Try 'cmd --help' for help.",197 "",198- "Error: Invalid value for 'metavar': 3.14 is not a valid integer",198+ "Error: Invalid value for 'metavar': '3.14' is not a valid integer.",199 ]200 201 202 def test_formatting_usage_error_nested(runner):150 unmodified linesmodified:tests/test_options.py+30 added-14 removed
186 unmodified lines187 assert "foo, bar" in result.output188 assert "1, 2" in result.output189 190 191-def test_multiple_default_type(runner):192- @click.command()193- @click.option("--arg1", multiple=True, default=("foo", "bar"))194- @click.option("--arg2", multiple=True, default=(1, "a"))195- def cmd(arg1, arg2):196- assert all(isinstance(e[0], str) for e in arg1)197- assert all(isinstance(e[1], str) for e in arg1)191+def test_multiple_default_type():192+ opt = click.Option(["-a"], multiple=True, default=(1, 2))193+ assert opt.nargs == 1194+ assert opt.multiple195+ assert opt.type is click.INT196+ ctx = click.Context(click.Command("test"))197+ assert opt.get_default(ctx) == (1, 2)198 199- assert all(isinstance(e[0], int) for e in arg2)200- assert all(isinstance(e[1], str) for e in arg2)199 202- result = runner.invoke(203- cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()204- )205- assert not result.exception200+def test_multiple_default_composite_type():201+ opt = click.Option(["-a"], multiple=True, default=[(1, "a")])202+ assert opt.nargs == 2203+ assert opt.multiple204+ assert isinstance(opt.type, click.Tuple)205+ assert opt.type.types == [click.INT, click.STRING]206+ ctx = click.Context(click.Command("test"))207+ assert opt.get_default(ctx) == ((1, "a"),)208 209 210+def test_parse_multiple_default_composite_type(runner):211+ @click.command()212+ @click.option("-a", multiple=True, default=("a", "b"))213+ @click.option("-b", multiple=True, default=[(1, "a")])214+ def cmd(a, b):215+ click.echo(a)216+ click.echo(b)217+218+ # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())219+ # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"220+ result = runner.invoke(cmd)221+ assert result.output == "('a', 'b')\n((1, 'a'),)\n"222+223+224 def test_dynamic_default_help_unset(runner):225 @click.command()226 @click.option(227 "--username",38 unmodified lines266 (click.IntRange(max=32), "x<=32"),267 ],268 )269 def test_intrange_default_help_text(runner, type, expect):254- option = click.Option(["--count"], type=type, show_default=True, default=1)270+ option = click.Option(["--count"], type=type, show_default=True, default=2)271 context = click.Context(click.Command("test"))272 result = option.get_help_record(context)[1]273 assert expect in result274 374 unmodified linesmodified:tests/test_shell_completion.py+17 added-2 removed
88 unmodified lines89 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90 assert _get_words(cli, ["x", "b"], "d") == ["d"]91 92 93+def test_argument_default():94+ cli = Command(95+ "cli",96+ add_help_option=False,97+ params=[98+ Argument(["a"], type=Choice(["a"]), default="a"),99+ Argument(["b"], type=Choice(["b"]), default="b"),100+ ],101+ )102+ assert _get_words(cli, [], "") == ["a"]103+ assert _get_words(cli, ["a"], "b") == ["b"]104+ # ignore type validation105+ assert _get_words(cli, ["x"], "b") == ["b"]106+107+108 def test_type_choice():109 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])110 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]111 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]21 unmodified lines133 Option(["--on/--off"]),134 Argument(["a"], type=Choice(["a1", "a2", "b"])),135 ],136 )122- assert _get_words(cli, ["type"], "--") == ["--on", "--off"]137+ assert _get_words(cli, [], "--") == ["--on", "--off"]138 # flag option doesn't take value, use choice argument124- assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]139+ assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]140 141 142 def test_option_custom():143 def custom(ctx, param, incomplete):163 unmodified linesmodified:tests/test_types.py+24 added
52 unmodified lines53 sneaky.clamp = True54 55 with pytest.raises(RuntimeError):56 sneaky.convert("1.5", None, None)57+58+59+@pytest.mark.parametrize(60+ ("nargs", "multiple", "default", "expect"),61+ [62+ (2, False, None, None),63+ (2, False, (None, None), (None, None)),64+ (None, True, None, ()),65+ (None, True, (None, None), (None, None)),66+ (2, True, None, ()),67+ (2, True, [(None, None)], ((None, None),)),68+ (-1, None, None, ()),69+ ],70+)71+def test_cast_multi_default(runner, nargs, multiple, default, expect):72+ if nargs == -1:73+ param = click.Argument(["a"], nargs=nargs, default=default)74+ else:75+ param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)76+77+ cli = click.Command("cli", params=[param], callback=lambda a: a)78+ result = runner.invoke(cli, standalone_mode=False)79+ assert result.exception is None80+ assert result.return_value == expectmodified:CHANGES.rst+22 added-1 removed
109 unmodified lines110 - Extra context settings (``obj=...``, etc.) are passed on to the111 completion system. :issue:`942`112 - Include ``--help`` option in completion. :pr:`1504`113 - ``ParameterSource`` is an ``enum.Enum`` subclass. :issue:`1530`114-- Boolean type strips surrounding space before converting.114+- Boolean and UUID types strip surrounding space before converting.115 :issue:`1605`116+- Adjusted error message from parameter type validation to be more117+ consistent. Quotes are used to distinguish the invalid value.118+ :issue:`1605`119+- The default value for a parameter with ``nargs`` > 1 and120+ ``multiple=True`` must be a list of tuples. :issue:`1649`121+- When getting the value for a parameter, the default is tried in the122+ same section as other sources to ensure consistent processing.123+ :issue:`1649`124+- All parameter types accept a value that is already the correct type.125+ :issue:`1649`126+- For shell completion, an argument is considered incomplete if its127+ value did not come from the command line args. :issue:`1649`128+- Added ``ParameterSource.PROMPT`` to track parameter values that were129+ prompted for. :issue:`1649`130+- Options with ``nargs`` > 1 no longer raise an error if a default is131+ not given. Parameters with ``nargs`` > 1 default to ``None``, and132+ parameters with ``multiple=True`` or ``nargs=-1`` default to an133+ empty tuple. :issue:`472`134+- Handle empty env vars as though the option were not passed. This135+ extends the change introduced in 7.1 to be consistent in more cases.136+ :issue:`1285`137 138 139 Version 7.1.2140 -------------635 unmodified lines