Skip to content
Myr

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

10 files+271 added−129 removed

modified:src/click/core.py+78 added-36 removed
140 unmodified lines
141 source for a parameter by name.142143 .. versionchanged:: 8.0144 Use :class:`~enum.Enum` and drop the ``validate`` method.145146 .. versionchanged:: 8.0147 Added the ``PROMPT`` value.148 """149150 COMMANDLINE = enum.auto()151 """The value was provided by the command line args."""
2 unmodified lines
154 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."""160161162class Context:163 """The context is a special internal object that holds state relevant
117 unmodified lines
281 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 but
448 unmodified lines
737 value was actually taken from the default.738739 :param name: The name of the parameter.740 :rtype: ParameterSource741742 .. 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)747748749class BaseCommand:750 """The base command implements the minimal API contract of commands.
536 unmodified lines
1287 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 continue12981299 results.extend(
487 unmodified lines
1787 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.17901791 .. versionchanged:: 8.01792 For ``multiple=True, nargs>1``, the default must be a list of1793 tuples.17941795 .. 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 ``()``.17991800 .. 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 lines
1943 if value is None:1944 value = ctx.lookup_default(self.name)1945 source = ParameterSource.DEFAULT_MAP19461929 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.DEFAULT19501932 return value1951 return value, source19521953 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 None19601961 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 )19681969 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)19711972 return self.type(value, self, ctx)19731974 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 ())19771978 return tuple(_convert(x, level - 1) for x in value)19791980 return _convert(value, (self.nargs != 1) + bool(self.multiple))19811982 def process_value(self, ctx, value):1983 """Given a value and context this runs the logic to convert the
15 unmodified lines
19992000 def full_process_value(self, ctx, value):2001 value = self.process_value(ctx, value)20021978 if value is None and not ctx.resilient_parsing:1979 value = self.get_default(ctx)19801981 if value is not None:1982 ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)19832003 if self.required and self.value_is_missing(value):2004 raise MissingParameter(ctx=ctx, param=self)20052006 # 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 lines
20242025 def resolve_envvar_value(self, ctx):2026 if self.envvar is None:2027 return20282029 if isinstance(self.envvar, (tuple, list)):2030 for envvar in self.envvar:2031 rv = os.environ.get(envvar)2008 if rv is not None:20322033 if rv:2034 return rv2035 else:2036 rv = os.environ.get(self.envvar)20372013 if rv != "":2038 if rv:2039 return rv20402041 def value_from_envvar(self, ctx):2042 rv = self.resolve_envvar_value(ctx)20432044 if rv is not None and self.nargs != 1:2045 rv = self.type.split_envvar_value(rv)20462047 return rv20482049 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)20532054 try:2055 value = self.full_process_value(ctx, value)20562057 if self.callback is not None:2058 value = self.callback(ctx, self, value)2059 except Exception:2060 if not ctx.resilient_parsing:2061 raise20622063 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 raise20642065 if self.expose_value:2066 ctx.params[self.name] = value20672041 if value is not None:2042 ctx._seen_params.add(self)20432068 return value, args20692070 def get_help_record(self, ctx):2071 pass
355 unmodified lines
2427 rv = super().resolve_envvar_value(ctx)24282429 if rv is not None:2430 return rv24312432 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)24352436 if rv:2437 return rv24382439 def value_from_envvar(self, ctx):2440 rv = self.resolve_envvar_value(ctx)24412442 if rv is None:2443 return None24442445 value_depth = (self.nargs != 1) + bool(self.multiple)24462447 if value_depth > 0 and rv is not None:2448 rv = self.type.split_envvar_value(rv)24492450 if self.multiple and self.nargs != 1:2451 rv = batch(rv, self.nargs)24522453 return rv24542422 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)24572426 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.PROMPT24672468 return value, source246924702471class 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 lines
modified:src/click/shell_completion.py+19 added-18 removed
2 unmodified lines
34from .core import Argument5from .core import MultiCommand6from .core import Option7from .core import ParameterSource8from .parser import split_arg_string9from .utils import echo1011
383 unmodified lines
395 """396 return _available_shells.get(shell)397398398def _is_incomplete_argument(values, param):399def _is_incomplete_argument(ctx, param):400 """Determine if the given parameter is an argument that can still401 accept values.402402 :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 False409409 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 )420411 if value is None:412 return True421414 if param.nargs == -1:415 return True416417 if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:418 return True419420 return False421422422def _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 lines
521 # command will provide option name completions.522 if "--" not in args and _start_of_option(incomplete):523 return ctx.command, incomplete524525 params = ctx.command.get_params(ctx)526527 # 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, incomplete532533 # 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, incomplete538539 # There were no unparsed arguments, the command may be a group that540 # will provide command name completions.
1 unmodified line
modified:src/click/types.py+55 added-31 removed
179 unmodified lines
180 value = value.decode("utf-8", "replace")181 else:182 value = value.decode("utf-8", "replace")183 return value184 return value184 return str(value)185186 def __repr__(self):187 return "STRING"188
65 unmodified lines
254255 if normed_value in normed_choices:256 return normed_choices[normed_value]257258 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)261262 def __repr__(self):263 return f"Choice({list(self.choices)})"264
52 unmodified lines
317 except ValueError:318 return None319320 def convert(self, value, param, ctx):323 # Exact match321 if isinstance(value, datetime):322 return value323324 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)326327 if converted is not None:328 return converted329330 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 )335336 def __repr__(self):337 return "DateTime"
5 unmodified lines
343 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)348349350class _NumberRangeBase(_NumberParamTypeBase):351 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):
145 unmodified lines
497class BoolParamType(ParamType):498 name = "boolean"499500 def convert(self, value, param, ctx):498 if isinstance(value, bool):501 if value in {False, True}:502 return bool(value)503504 norm = value.strip().lower()505
2 unmodified lines
508509 if norm in {"0", "false", "f", "no", "n", "off"}:510 return False511509 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)513514 def __repr__(self):515 return "BOOL"516
3 unmodified lines
520521 def convert(self, value, param, ctx):522 import uuid523524 if isinstance(value, uuid.UUID):525 return value526527 value = value.strip()528529 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)533534 def __repr__(self):535 return "UUID"536
80 unmodified lines
617 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)622623 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 lines
821 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))822823824def 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 = False830831 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]837838 # 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)847848 guessed_type = True849850 if isinstance(ty, tuple):851 return Tuple(ty)852853 if isinstance(ty, ParamType):854 return ty855856 if ty is str or ty is None:857 return STRING858859 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 BOOL861862 if ty is float:863 return FLOAT864865 # 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 BOOL870871 if guessed_type:872 return STRING873851 # 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 pass883884 return FuncParamType(ty)885886887#: A dummy parameter type that just does nothing. From a user's
30 unmodified lines
modified:tests/test_arguments.py+15 added-12 removed
162 unmodified lines
163 assert result.output == "Foo bar baz\n"164165166@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)177def test_nargs_envvar(runner, nargs, value, code, output):177def 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)182183 @click.command()184 @param185 def cmd(arg):186 click.echo(f"len {len(arg)}")186 return arg187188 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)189190 if isinstance(expect, str):191 assert expect in str(result.exception)192 else:193 assert result.return_value == expect194195196def test_empty_nargs(runner):197 @click.command()198 @click.argument("arg", nargs=-1)199 def cmd(arg):
175 unmodified lines
modified:tests/test_basic.py+10 added-14 removed
145 unmodified lines
146 assert "FOO:[46]" in result.output147148 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.output151152153def test_uuid_option(runner):154 @click.command()
13 unmodified lines
168 assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output169170 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.output173174175def test_float_option(runner):176 @click.command()
11 unmodified lines
188 assert "FOO:[23.5]" in result.output189190 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.output193194195def test_boolean_option(runner):196 for default in True, False:
105 unmodified lines
302 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.output307308309def test_path_option(runner):310 @click.command()
53 unmodified lines
364365 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 )371372 result = runner.invoke(cli, ["--help"])373 assert "--method [foo|bar|baz]" in result.output
11 unmodified lines
385386 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 )392393 result = runner.invoke(cli, ["--help"])394 assert "{foo|bar|baz}" in result.output
15 unmodified lines
410411 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.output417418 result = runner.invoke(cli, ["--help"])419 assert (
111 unmodified lines
modified:tests/test_formatting.py+1 added-1 removed
193 unmodified lines
194 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 ]200201202def test_formatting_usage_error_nested(runner):
150 unmodified lines
modified:tests/test_options.py+30 added-14 removed
186 unmodified lines
187 assert "foo, bar" in result.output188 assert "1, 2" in result.output189190191def 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)191def 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)198199 assert all(isinstance(e[0], int) for e in arg2)200 assert all(isinstance(e[1], str) for e in arg2)199202 result = runner.invoke(203 cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()204 )205 assert not result.exception200def 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"),)208209210def 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)217218 # 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"222223224def test_dynamic_default_help_unset(runner):225 @click.command()226 @click.option(227 "--username",
38 unmodified lines
266 (click.IntRange(max=32), "x<=32"),267 ],268)269def 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 lines
modified:tests/test_shell_completion.py+17 added-2 removed
88 unmodified lines
89 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90 assert _get_words(cli, ["x", "b"], "d") == ["d"]919293def 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"]106107108def 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 lines
133 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"]140141142def test_option_custom():143 def custom(ctx, param, incomplete):
163 unmodified lines
modified:tests/test_types.py+24 added
52 unmodified lines
53 sneaky.clamp = True5455 with pytest.raises(RuntimeError):56 sneaky.convert("1.5", None, None)575859@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)71def 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)7677 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 == expect
modified:CHANGES.rst+22 added-1 removed
109 unmodified lines
110- 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`137138139Version 7.1.2140-------------
635 unmodified lines