Skip to content
Myr

Ensure that 'type_cast_value' never gets 'UNSET'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

In order to ensure that user-defined `type_cast_value` hooks are never called with a value of `UNSET`, it is necessary to intercept `UNSET` values and, in the particular cases in which `UNSET` needs special handling, preempt any call to `type_cast_value()`. `process_value()` is updated to check before calling `type_cast_value` and to skip the call entirely if an `UNSET` value is detected. Passing a value of `None` would not have the same effect for `click.Option`, which previously had logic which is specific to the `value is UNSET` case, and which cannot be reliably detected if a `None` value is passed in. This means that `type_cast_value()` is no longer guaranteed to be called during argument processing, but when it is called, it's guaranteed not to see an `UNSET` value. New tests explore this only from the perspective of checking if `UNSET` is ever passed, not in terms of pinning down when/if the hook gets called. resolves #3069

authored by Stephen Rosen · committed by Stephen Rosen · parent 27aaed3 · Browse files · 4 files+102 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+102 added−9 removed

  • tests:+73 added−0 removed
  • other:+29 added−9 removed

4 files+102 added−9 removed

modified:src/click/core.py+27 added-9 removed
2336 unmodified lines
2337 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2338 """Convert and validate a value against the parameter's2339 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2340 """2341 if value in (None, UNSET):2341 if value is None:2342 if self.multiple or self.nargs == -1:2343 return ()2344 else:2345 return value
74 unmodified lines
2420 the :attr:`UNSET` sentinel.24212422 :meta private:2423 """2424 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the2425 # cases in which `UNSET` gets special treatment explicitly at this layer2426 #2427 # Refs:2428 # https://github.com/pallets/click/issues/30692429 if value is UNSET:2430 if self.multiple or self.nargs == -1:2431 value = ()2432 else:2424 value = self.type_cast_value(ctx, value)2433 value = self.type_cast_value(ctx, value)24342435 if self.required and self.value_is_missing(value):2436 raise MissingParameter(ctx=ctx, param=self)2437
826 unmodified lines
3264 source = ParameterSource.PROMPT32653266 return value, source32673259 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3260 if self.is_flag and not self.required:3261 if value is UNSET:3262 if self.is_bool_flag:3263 # If the flag is a boolean flag, we return False if it is not set.3264 value = False3265 return super().type_cast_value(ctx, value)3268 def process_value(self, ctx: Context, value: t.Any) -> t.Any:3269 # process_value has to be overridden on Options in order to capture3270 # `value == UNSET` cases before `type_cast_value()` gets called.3271 #3272 # Refs:3273 # https://github.com/pallets/click/issues/30693274 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET:3275 value = False32763277 if self.callback is not None:3278 value = self.callback(ctx, self, value)32793280 return value32813282 # in the normal case, rely on Parameter.process_value3283 return super().process_value(ctx, value)328432853286class Argument(Parameter):3287 """Arguments are positional parameters to a command. They generally3288 provide fewer features than options but can have infinite ``nargs``3289 and are required by default.
96 unmodified lines
modified:tests/test_arguments.py+37 added
577 unmodified lines
578 pass579580 with pytest.warns(UserWarning):581 runner.invoke(cli, [])582583584@pytest.mark.parametrize(585 ("argument_kwargs", "pass_argv"),586 (587 # there is a large potential parameter space to explore here588 # this is just a very small sample of it589 ({}, ["myvalue"]),590 ({"nargs": -1}, []),591 ({"nargs": -1}, ["myvalue"]),592 ({"default": None}, ["myvalue"]),593 ({"required": False}, []),594 ({"required": False}, ["myvalue"]),595 ),596)597def test_argument_custom_class_can_override_type_cast_value_and_never_sees_unset(598 runner, argument_kwargs, pass_argv599):600 """601 Test that overriding type_cast_value is supported602603 In particular, the argument is never passed an UNSET sentinel value.604 """605606 class CustomArgument(click.Argument):607 def type_cast_value(self, ctx, value):608 assert value is not UNSET609 return value610611 @click.command()612 @click.argument("myarg", **argument_kwargs, cls=CustomArgument)613 def cmd(myarg):614 click.echo("ok")615616 result = runner.invoke(cmd, pass_argv)617 assert not result.exception618 assert result.exit_code == 0
modified:tests/test_options.py+36 added
1010 unmodified lines
1011 assert "I am a help text" in result.output1012 assert "you wont see me" not in result.output101310141015@pytest.mark.parametrize(1016 ("param_decl", "option_kwargs", "pass_argv"),1017 (1018 # there is a large potential parameter space to explore here1019 # this is just a very small sample of it1020 ("--opt", {}, []),1021 ("--opt", {"multiple": True}, []),1022 ("--opt", {"is_flag": True}, []),1023 ("--opt/--no-opt", {"is_flag": True, "default": None}, []),1024 ("--req", {"is_flag": True, "required": True}, ["--req"]),1025 ),1026)1027def test_option_custom_class_can_override_type_cast_value_and_never_sees_unset(1028 runner, param_decl, option_kwargs, pass_argv1029):1030 """1031 Test that overriding type_cast_value is supported10321033 In particular, the option is never passed an UNSET sentinel value.1034 """10351036 class CustomOption(click.Option):1037 def type_cast_value(self, ctx, value):1038 assert value is not UNSET1039 return value10401041 @click.command()1042 @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)1043 def cmd(myparam):1044 click.echo("ok")10451046 result = runner.invoke(cmd, pass_argv)1047 assert not result.exception1048 assert result.exit_code == 0104910501051def test_option_custom_class_reusable(runner):1052 """Ensure we can reuse a custom class option. See Issue #926"""10531054 class CustomOption(click.Option):
1223 unmodified lines
modified:CHANGES.rst+2 added
9 unmodified lines
10- Replace ``Sentinel.UNSET`` default values by ``None`` as they're passed through11 the ``Context.invoke()`` method. :issue:`3066` :issue:`3065` :pr:`3068`12- Fix conversion of ``Sentinel.UNSET`` happening too early, which caused incorrect13 behavior for multiple parameters using the same name. :issue:`3071` :pr:`3079`14- When ``Sentinel.UNSET`` is found during parsing, it will skip calls to15 ``type_cast_value``. :issue:`3069`1617Version 8.3.018--------------19
1287 unmodified lines