Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Closes pallets#2952 Fixes pallets#2788
authored by Kevin Deldycke · committed by GitHub · parents 5c1239b, 9caedb9 · Browse files · 8 files·+421 added−89 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+421 added−89 removed
- tests:+264 added−51 removed
- other:+157 added−38 removed
Provenance
- Commit
565f36d- Tree
ad02162- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
5c1239b- Parent 2
9caedb9
8 files changed+421 added−89 removed
modified:docs/options.md+25 added
366 unmodified lines367 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})368 369 ```370 371+Variable names are:372+ - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).373+ - Not stripped of whitespaces and should match the exact name provided to the `envvar` argument.374+375+For flag options, there is two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.376+377+The environment variable need to be interpreted, because values read from them are always strings. We need to transform these strings into boolean values that will determine if the flag is activated or not.378+379+Here are the rules used to parse environment variable values for flag options:380+ - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag381+ - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag382+ - The presence of the environment variable without value is interpreted as deactivating the flag383+ - Empty strings are interpreted as deactivating the flag384+ - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all activating the flag385+ - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag386+ - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above387+ - Any other value is interpreted as deactivating the flag388+389+.. caution::390+ For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.391+392+ So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.393+394+Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.395+396 ## Multiple Options from Environment Values397 398 As options can accept multiple values, pulling in such values from399 environment variables (which are strings) is a bit more complex. The way77 unmodified linesmodified:src/click/core.py+66 added-25 removed
2552 unmodified lines2553 ) -> None:2554 if help:2555 help = inspect.cleandoc(help)2556 2557- default_is_missing = "default" not in attrs2557 super().__init__(2558 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2559 )2560 25 unmodified lines2586 # used as a flag to indicate using prompt or flag_value.2587 self._flag_needs_value = self.prompt is not None and not self.prompt_required2588 2589 if is_flag is None:2590+ # Implicitly a flag because flag_value was set.2591 if flag_value is not None:2592- # Implicitly a flag because flag_value was set.2592 is_flag = True2593+ # Not a flag, but when used as a flag it shows a prompt.2594 elif self._flag_needs_value:2595- # Not a flag, but when used as a flag it shows a prompt.2595 is_flag = False2597- else:2598- # Implicitly a flag because flag options were given.2599- is_flag = bool(self.secondary_opts)2596+ # Implicitly a flag because flag options were given.2597+ elif self.secondary_opts:2598+ is_flag = True2599 elif is_flag is False and not self._flag_needs_value:2600 # Not a flag, and prompt is not enabled, can be used as a2601 # flag if flag_value is set.2602 self._flag_needs_value = flag_value is not None2603 2604 self.default: t.Any | t.Callable[[], t.Any]2605 2606+ if is_flag:2607+ # Set missing default for flags if not explicitly required or prompted.2607- if is_flag and default_is_missing and not self.required:2608- if multiple:2609- self.default = ()2610- else:2611- self.default = False2608+ if self.default is None and not self.required and not self.prompt:2609+ if multiple:2610+ self.default = ()2611+ else:2612+ self.default = False2613 2613- if is_flag and flag_value is None:2614- flag_value = not self.default2614+ if flag_value is None:2615+ # A boolean flag presence in the command line is enough to set2616+ # the value: to the default if it is not blank, or to True2617+ # otherwise.2618+ flag_value = self.default if self.default else True2619 2620 self.type: types.ParamType2621 if is_flag and type is None:2622 # Re-guess the type from the flag value instead of the2623 # default.2624 self.type = types.convert_type(None, flag_value)2625 2622- self.is_flag: bool = is_flag2623- self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2626+ self.is_flag: bool = bool(is_flag)2627+ self.is_bool_flag: bool = bool(2628+ is_flag and isinstance(self.type, types.BoolParamType)2629+ )2630 self.flag_value: t.Any = flag_value2631 2632 # Counting2633 self.count = count2634 if count:2635 if type is None:2636 self.type = types.IntRange(min=0)2631- if default_is_missing:2637+ if self.default is None:2638 self.default = 02639 2640 self.allow_from_autoenv = allow_from_autoenv2641 self.help = help281 unmodified lines2923 # if we're the default one in which case we return the flag2924 # value as default.2925 if self.is_flag and not self.is_bool_flag:2926 for param in ctx.command.params:2921- if param.name == self.name and param.default:2922- return t.cast(Option, param).flag_value2927+ if param.name == self.name and param.default is not None:2928+ return t.cast(Option, param).default2929 2930 return None2931 2932 return super().get_default(ctx, call=call)31 unmodified lines2964 **prompt_kwargs,2965 )2966 2967 def resolve_envvar_value(self, ctx: Context) -> str | None:2968+ """Find which environment variable to read for this option and return2969+ its value.2970+2971+ Returns the value of the environment variable if it exists, or ``None``2972+ if it does not.2973+2974+ .. caution::2975+2976+ The raw value extracted from the environment is not normalized and2977+ is returned as-is. Any normalization or reconciation with the2978+ option's type should happen later.2979+ """2980 rv = super().resolve_envvar_value(ctx)2981 2982 if rv is not None:2965- if self.is_flag and self.flag_value:2966- return str(self.flag_value)2983 return rv2984 2985 if (2986 self.allow_from_autoenv8 unmodified lines2995 2996 return None2997 2998 def value_from_envvar(self, ctx: Context) -> t.Any | None:2999+ """Normalize the value from the environment variable, if it exists."""2983- rv: t.Any | None = self.resolve_envvar_value(ctx)3000+ rv: str | None = self.resolve_envvar_value(ctx)3001 3002 if rv is None:3003 return None3004 2988- value_depth = (self.nargs != 1) + bool(self.multiple)3005+ # Non-boolean flags are more liberal in what they accept. But a flag being a3006+ # flag, its envvar value still needs to analyzed to determine if the flag is3007+ # activated or not.3008+ if self.is_flag and not self.is_bool_flag:3009+ # If the flag_value is set and match the envvar value, return it3010+ # directly.3011+ if self.flag_value is not None and rv == self.flag_value:3012+ return self.flag_value3013+ # Analyze the envvar value as a boolean to know if the flag is3014+ # activated or not.3015+ return types.BoolParamType.str_to_bool(rv)3016 3017+ # Split the envvar value if it is allowed to be repeated.3018+ value_depth = (self.nargs != 1) + bool(self.multiple)3019 if value_depth > 0:2991- rv = self.type.split_envvar_value(rv)2992-3020+ multi_rv = self.type.split_envvar_value(rv)3021 if self.multiple and self.nargs != 1:2994- rv = batch(rv, self.nargs)3022+ multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]3023 3024+ return multi_rv3025+3026 return rv3027 3028 def consume_value(3029 self, ctx: Context, opts: cabc.Mapping[str, Parameter]10 unmodified lines3040 else:3041 value = self.flag_value3042 source = ParameterSource.COMMANDLINE3043 3044+ # A flag which is activated and has a flag_value set, should returns3045+ # the latter, unless the value comes from the explicitly sets default.3046 elif (3047+ self.is_flag3048+ and value is True3049+ and not self.is_bool_flag3050+ and self.flag_value is not None3051+ and source is not ParameterSource.DEFAULT3052+ ):3053+ value = self.flag_value3054+3055+ elif (3056 self.multiple3057 and value is not None3058 and any(v is _flag_needs_value for v in value)3059 ):117 unmodified linesmodified:src/click/types.py+57 added-13 removed
659 unmodified lines660 661 class BoolParamType(ParamType):662 name = "boolean"663 664- def convert(665- self, value: t.Any, param: Parameter | None, ctx: Context | None666- ) -> t.Any:667- if value in {False, True}:668- return bool(value)664+ bool_states: dict[str, bool] = {665+ "1": True,666+ "0": False,667+ "yes": True,668+ "no": False,669+ "true": True,670+ "false": False,671+ "on": True,672+ "off": False,673+ "t": True,674+ "f": False,675+ "y": True,676+ "n": False,677+ # Absence of value is considered False.678+ "": False,679+ }680+ """A mapping of string values to boolean states.681 670- norm = value.strip().lower()682+ Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683+ and extends it.684 672- if norm in {"1", "true", "t", "yes", "y", "on"}:673- return True685+ .. caution::686+ String values are lower-cased, as the ``str_to_bool`` comparison function687+ below is case-insensitive.688 675- if norm in {"0", "false", "f", "no", "n", "off"}:676- return False689+ .. warning::690+ The mapping is not exhaustive, and does not cover all possible boolean strings691+ representations. It will remains as it is to avoid endless bikeshedding.692 678- self.fail(679- _("{value!r} is not a valid boolean.").format(value=value), param, ctx680- )693+ Future work my be considered to make this mapping user-configurable from public694+ API.695+ """696 697+ @staticmethod698+ def str_to_bool(value: str | bool) -> bool | None:699+ """Convert a string to a boolean value.700+701+ If the value is already a boolean, it is returned as-is. If the value is a702+ string, it is stripped of whitespaces and lower-cased, then checked against703+ the known boolean states pre-defined in the `BoolParamType.bool_states` mapping704+ above.705+706+ Returns `None` if the value does not match any known boolean state.707+ """708+ if isinstance(value, bool):709+ return value710+ return BoolParamType.bool_states.get(value.strip().lower())711+712+ def convert(713+ self, value: t.Any, param: Parameter | None, ctx: Context | None714+ ) -> bool:715+ normalized = self.str_to_bool(value)716+ if normalized is None:717+ self.fail(718+ _(719+ "{value!r} is not a valid boolean. Recognized values: {states}"720+ ).format(value=value, states=", ".join(sorted(self.bool_states))),721+ param,722+ ctx,723+ )724+ return normalized725+726 def __repr__(self) -> str:727 return "BOOL"728 729 480 unmodified linesmodified:tests/test_arguments.py-13 removed
196 unmodified lines197 else:198 assert result.return_value == expect199 200 201-def test_envvar_flag_value(runner):202- @click.command()203- # is_flag is implicitly true204- @click.option("--upper", flag_value="upper", envvar="UPPER")205- def cmd(upper):206- click.echo(upper)207- return upper208-209- # For whatever value of the `env` variable, if it exists, the flag should be `upper`210- result = runner.invoke(cmd, env={"UPPER": "whatever"})211- assert result.output.strip() == "upper"212-213-201 def test_nargs_envvar_only_if_values_empty(runner):202 @click.command()203 @click.argument("arg", envvar="X", nargs=-1)204 def cli(arg):257 unmodified linesmodified:tests/test_basic.py+9 added-5 removed
220 unmodified lines221 result = runner.invoke(cli, args, standalone_mode=False)222 assert result.return_value is expect223 224 225-@pytest.mark.parametrize("default", [True, False])226-@pytest.mark.parametrize(("args", "expect"), [(["--f"], True), ([], False)])225+@pytest.mark.parametrize(226+ ("default", "args", "expect"),227+ (228+ (True, ["--f"], True),229+ (True, [], True),230+ (False, ["--f"], True),231+ (False, [], False),232+ ),233+)234 def test_boolean_flag(runner, default, args, expect):235 @click.command()236 @click.option("--f", is_flag=True, default=default)237 def cli(f):238 return f239 233- if default:234- expect = not expect235-240 result = runner.invoke(cli, args, standalone_mode=False)241 assert result.return_value is expect242 243 415 unmodified linesmodified:tests/test_imports.py+16 added-15 removed
25 unmodified lines26 """27 28 ALLOWED_IMPORTS = {29 "__future__",30- "weakref",31- "os",32- "struct",30+ "codecs",31 "collections",32 "collections.abc",35- "sys",33+ "configparser",34 "contextlib",35+ "datetime",36+ "enum",37+ "errno",38+ "fcntl",39 "functools",38- "stat",39- "re",40- "codecs",40+ "gettext",41 "inspect",42- "itertools",42 "io",43+ "itertools",44+ "os",45+ "re",46+ "shutil",47+ "stat",48+ "struct",49+ "sys",50 "threading",45- "errno",46- "fcntl",47- "datetime",48- "enum",49- "typing",51 "types",51- "gettext",52- "shutil",52+ "typing",53+ "weakref",54 }55 56 if WIN:57 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])14 unmodified linesmodified:tests/test_options.py+239 added-18 removed
245 unmodified lines246 assert not result.exception247 assert result.output == "foo|bar\n"248 249 250-def test_trailing_blanks_boolean_envvar(runner):250+@pytest.mark.parametrize(251+ ("name", "value", "expected"),252+ (253+ # Lower-cased variations of value.254+ ("SHOUT", "true", True),255+ ("SHOUT", "false", False),256+ # Title-cased variations of value.257+ ("SHOUT", "True", True),258+ ("SHOUT", "False", False),259+ # Upper-cased variations of value.260+ ("SHOUT", "TRUE", True),261+ ("SHOUT", "FALSE", False),262+ # Random-cased variations of value.263+ ("SHOUT", "TruE", True),264+ ("SHOUT", "truE", True),265+ ("SHOUT", "FaLsE", False),266+ ("SHOUT", "falsE", False),267+ # Extra spaces around the value.268+ ("SHOUT", "true ", True),269+ ("SHOUT", " true", True),270+ ("SHOUT", " true ", True),271+ ("SHOUT", "false ", False),272+ ("SHOUT", " false", False),273+ ("SHOUT", " false ", False),274+ # Integer variations.275+ ("SHOUT", "1", True),276+ ("SHOUT", "0", False),277+ # Alternative states.278+ ("SHOUT", "t", True),279+ ("SHOUT", "f", False),280+ ("SHOUT", "y", True),281+ ("SHOUT", "n", False),282+ ("SHOUT", "yes", True),283+ ("SHOUT", "no", False),284+ ("SHOUT", "on", True),285+ ("SHOUT", "off", False),286+ # Blank value variations.287+ ("SHOUT", None, False),288+ ("SHOUT", "", False),289+ ("SHOUT", " ", False),290+ ("SHOUT", " ", False),291+ # Variable names are not stripped of spaces and so don't match the292+ # flag, which then naturraly takes its default value.293+ ("SHOUT ", "True", False),294+ ("SHOUT ", "False", False),295+ (" SHOUT ", "True", False),296+ (" SHOUT ", "False", False),297+ # Same for random and reverse environment variable names: they are not298+ # recognized by the option.299+ ("RANDOM", "True", False),300+ ("NO_SHOUT", "True", False),301+ ("NO_SHOUT", "False", False),302+ ),303+)304+def test_boolean_envvar_normalization(runner, name, value, expected):305 @click.command()306 @click.option("--shout/--no-shout", envvar="SHOUT")307 def cli(shout):308 click.echo(f"shout: {shout!r}")309 256- result = runner.invoke(cli, [], env={"SHOUT": " true "})310+ result = runner.invoke(cli, [], env={name: value})311 assert result.exit_code == 0258- assert result.output == "shout: True\n"312+ assert result.output == f"shout: {expected}\n"313 314 315+@pytest.mark.parametrize(316+ ("name", "value"),317+ (318+ ("SHOUT", "tr ue"),319+ ("SHOUT", "10"),320+ ("SHOUT", "01"),321+ ("SHOUT", "00"),322+ ("SHOUT", "11"),323+ ("SHOUT", "randomstring"),324+ ("SHOUT", "None"),325+ ),326+)327+def test_boolean_envvar_bad_values(runner, name, value):328+ @click.command()329+ @click.option("--shout/--no-shout", envvar="SHOUT")330+ def cli(shout):331+ click.echo(f"shout: {shout!r}")332+333+ result = runner.invoke(cli, [], env={name: value})334+ assert result.exit_code == 2335+ assert (336+ f"Invalid value for '--shout': {value!r} is not a valid boolean."337+ in result.output338+ )339+340+341 def test_multiple_default_help(runner):342 @click.command()343 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)344 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)742 unmodified lines1087 assert param.type is click.INT1088 1089 1090 @pytest.mark.parametrize(1011- ("opts", "pass_flag", "expected"),1091+ ("opt_params", "pass_flag", "expected"),1092 [1013- pytest.param({"type": bool}, False, "False"),1014- pytest.param({"type": bool}, True, "True"),1015- pytest.param({"type": bool, "default": True}, False, "True"),1016- pytest.param({"type": bool, "default": True}, True, "False"),1017- pytest.param({"type": click.BOOL}, False, "False"),1018- pytest.param({"type": click.BOOL}, True, "True"),1019- pytest.param({"type": click.BOOL, "default": True}, False, "True"),1020- pytest.param({"type": click.BOOL, "default": True}, True, "False"),1021- pytest.param({"type": str}, False, ""),1022- pytest.param({"type": str}, True, "True"),1093+ # Effect of the presence/absence of flag depending on type1094+ ({"type": bool}, False, False),1095+ ({"type": bool}, True, True),1096+ ({"type": click.BOOL}, False, False),1097+ ({"type": click.BOOL}, True, True),1098+ ({"type": str}, False, "False"),1099+ ({"type": str}, True, "True"),1100+ # Effects of default value1101+ ({"type": bool, "default": True}, False, True),1102+ ({"type": bool, "default": True}, True, True),1103+ ({"type": bool, "default": False}, False, False),1104+ ({"type": bool, "default": False}, True, True),1105+ ({"type": bool, "default": None}, False, False),1106+ ({"type": bool, "default": None}, True, True),1107+ ({"type": click.BOOL, "default": True}, False, True),1108+ ({"type": click.BOOL, "default": True}, True, True),1109+ ({"type": click.BOOL, "default": False}, False, False),1110+ ({"type": click.BOOL, "default": False}, True, True),1111+ ({"type": click.BOOL, "default": None}, False, False),1112+ ({"type": click.BOOL, "default": None}, True, True),1113+ ({"type": str, "default": True}, False, "True"),1114+ ({"type": str, "default": True}, True, "True"),1115+ ({"type": str, "default": False}, False, "False"),1116+ ({"type": str, "default": False}, True, "True"),1117+ ({"type": str, "default": "foo"}, False, "foo"),1118+ ({"type": str, "default": "foo"}, True, "foo"),1119+ ({"type": str, "default": None}, False, "False"),1120+ ({"type": str, "default": None}, True, "True"),1121+ # Effects of flag_value1122+ ({"type": bool, "flag_value": True}, False, False),1123+ ({"type": bool, "flag_value": True}, True, True),1124+ ({"type": bool, "flag_value": False}, False, False),1125+ ({"type": bool, "flag_value": False}, True, False),1126+ ({"type": bool, "flag_value": None}, False, False),1127+ ({"type": bool, "flag_value": None}, True, True),1128+ ({"type": click.BOOL, "flag_value": True}, False, False),1129+ ({"type": click.BOOL, "flag_value": True}, True, True),1130+ ({"type": click.BOOL, "flag_value": False}, False, False),1131+ ({"type": click.BOOL, "flag_value": False}, True, False),1132+ ({"type": click.BOOL, "flag_value": None}, False, False),1133+ ({"type": click.BOOL, "flag_value": None}, True, True),1134+ ({"type": str, "flag_value": True}, False, "False"),1135+ ({"type": str, "flag_value": True}, True, "True"),1136+ ({"type": str, "flag_value": False}, False, "False"),1137+ ({"type": str, "flag_value": False}, True, "False"),1138+ ({"type": str, "flag_value": "foo"}, False, "False"),1139+ ({"type": str, "flag_value": "foo"}, True, "foo"),1140+ ({"type": str, "flag_value": None}, False, "False"),1141+ ({"type": str, "flag_value": None}, True, "True"),1142+ # Not passing --foo returns the default value as-is1143+ ({"type": bool, "default": True, "flag_value": True}, False, True),1144+ ({"type": bool, "default": True, "flag_value": False}, False, True),1145+ ({"type": bool, "default": False, "flag_value": True}, False, False),1146+ ({"type": bool, "default": False, "flag_value": False}, False, False),1147+ ({"type": bool, "default": None, "flag_value": True}, False, False),1148+ ({"type": bool, "default": None, "flag_value": False}, False, False),1149+ ({"type": str, "default": True, "flag_value": True}, False, "True"),1150+ ({"type": str, "default": True, "flag_value": False}, False, "True"),1151+ ({"type": str, "default": False, "flag_value": True}, False, "False"),1152+ ({"type": str, "default": False, "flag_value": False}, False, "False"),1153+ ({"type": str, "default": "foo", "flag_value": True}, False, "foo"),1154+ ({"type": str, "default": "foo", "flag_value": False}, False, "foo"),1155+ ({"type": str, "default": "foo", "flag_value": "bar"}, False, "foo"),1156+ ({"type": str, "default": "foo", "flag_value": None}, False, "foo"),1157+ ({"type": str, "default": None, "flag_value": True}, False, "False"),1158+ ({"type": str, "default": None, "flag_value": False}, False, "False"),1159+ # Passing --foo returns the explicitly set flag_value1160+ ({"type": bool, "default": True, "flag_value": True}, True, True),1161+ ({"type": bool, "default": True, "flag_value": False}, True, False),1162+ ({"type": bool, "default": False, "flag_value": True}, True, True),1163+ ({"type": bool, "default": False, "flag_value": False}, True, False),1164+ ({"type": bool, "default": None, "flag_value": True}, True, True),1165+ ({"type": bool, "default": None, "flag_value": False}, True, False),1166+ ({"type": str, "default": True, "flag_value": True}, True, "True"),1167+ ({"type": str, "default": True, "flag_value": False}, True, "False"),1168+ ({"type": str, "default": False, "flag_value": True}, True, "True"),1169+ ({"type": str, "default": False, "flag_value": False}, True, "False"),1170+ ({"type": str, "default": "foo", "flag_value": True}, True, "True"),1171+ ({"type": str, "default": "foo", "flag_value": False}, True, "False"),1172+ ({"type": str, "default": "foo", "flag_value": "bar"}, True, "bar"),1173+ ({"type": str, "default": "foo", "flag_value": None}, True, "foo"),1174+ ({"type": str, "default": None, "flag_value": True}, True, "True"),1175+ ({"type": str, "default": None, "flag_value": False}, True, "False"),1176 ],1177 )1025-def test_flag_value_is_correctly_set(runner, opts, pass_flag, expected):1178+def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1179 @click.command()1180+ @click.option("--foo", is_flag=True, **opt_params)1181+ def cmd(foo):1182+ click.echo(repr(foo))1183+1184+ result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1185+ assert result.output == f"{expected!r}\n"1186+1187+1188+@pytest.mark.parametrize(1189+ "opts",1190+ [1191+ {"type": bool, "default": "foo"},1192+ {"type": bool, "flag_value": "foo"},1193+ {"type": click.BOOL, "default": "foo"},1194+ {"type": click.BOOL, "flag_value": "foo"},1195+ ],1196+)1197+def test_invalid_flag_definition(runner, opts):1198+ @click.command()1199 @click.option("--foo", is_flag=True, **opts)1200 def cmd(foo):1201 click.echo(foo)1202 1031- result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1032- assert result.output == f"{expected}\n"1203+ result = runner.invoke(cmd, ["--foo"])1204+ assert (1205+ "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1206+ in result.output1207+ )1208 1209 1210 @pytest.mark.parametrize(1211+ ("flag_value", "envvar_value", "expected"),1212+ [1213+ # Envvar is set to false, so the flag default value is returned.1214+ ("bar", "False", "False"),1215+ # Same as above with alternative states and blank values.1216+ ("bar", "0", "False"),1217+ ("bar", "f", "False"),1218+ ("bar", "", "False"),1219+ # Envvar is set to true, so the flag_value is returned.1220+ ("bar", "True", "bar"),1221+ ("bar", "1", "bar"),1222+ ("bar", "t", "bar"),1223+ # So far we have the same cases as the test_flag_value_and_default1224+ # test case. Now instead of passing a boolean-like value, let's use1225+ # the flag_value as the envvar value.1226+ ("bar", "bar", "bar"),1227+ # flag_value is expected to be the exact same in the envvar for the flag to be1228+ # activated.1229+ ("bar", " bar ", "False"),1230+ ("bar", "BAR", "False"),1231+ ("bar", "random", "False"),1232+ ("bar", "bar random", "False"),1233+ ("bar", "random bar", "False"),1234+ ("BAR", "BAR", "BAR"),1235+ ("BAR", "bar", "False"),1236+ (" bar ", " bar ", " bar "),1237+ (" bar ", "bar", "False"),1238+ (" bar ", "BAR", "False"),1239+ ],1240+)1241+def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1242+ """Ensure that flag_value is recognized by the envvar."""1243+1244+ @click.command()1245+ @click.option(1246+ "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1247+ )1248+ def cmd(upper):1249+ click.echo(repr(upper))1250+1251+ result = runner.invoke(cmd, env={"UPPER": envvar_value})1252+ assert result.exit_code == 01253+ assert result.output == f"{expected!r}\n"1254+1255+1256+@pytest.mark.parametrize(1257 ("option", "expected"),1258 [1259 # Not boolean flags1260 pytest.param(Option(["-a"], type=int), False, id="int option"),6 unmodified lines1267 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1268 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1269 ],1270 )1050-def test_is_bool_flag_is_correctly_set(option, expected):1271+def test_bool_flag_auto_detection(option, expected):1272 assert option.is_bool_flag is expected1273 1274 1275 @pytest.mark.parametrize(87 unmodified linesmodified:CHANGES.rst+9 added
1 .. currentmodule:: click2 3+Version 8.2.24+-------------5+6+Unreleased7+8+- Fix reconciliation of `default`, `flag_value` and `type` parameters for9+ flag options, as well as parsing and normalization of environment variables.10+ :issue:`2952` :pr:`2956`11+12 Version 8.2.113 -------------14 15 Released 2025-05-201241 unmodified lines