from __future__ import annotations import enum import os import pytest import click from click._utils import UNSET def test_basic_functionality(runner): @click.command() def cli(): """Hello World!""" click.echo("I EXECUTED") result = runner.invoke(cli, ["--help"]) assert not result.exception assert "Hello World!" in result.output assert "Show this message and exit." in result.output assert result.exit_code == 0 assert "I EXECUTED" not in result.output result = runner.invoke(cli, []) assert not result.exception assert "I EXECUTED" in result.output assert result.exit_code == 0 @pytest.mark.parametrize( ("help_names", "params", "args", "expected_output"), [ (["--help"], [], [], "\n"), (["--help"], [click.Argument(["help"])], ["value"], "value\n"), ( ["--help"], [click.Option(["--assist", "help"])], ["--assist", "value"], "value\n", ), (["--man"], [click.Option(["--foo", "man"])], ["--foo", "value"], "value\n"), ], ids=["no-collision", "argument", "option", "custom-flags"], ) def test_param_named_help(runner, help_names, params, args, expected_output): """User parameters never clash with the automatic help option, which stores its value under the reserved ``_click_default_help`` name. https://github.com/pallets/click/issues/2819 """ cli = click.Command( "cli", context_settings={"help_option_names": help_names}, params=params, callback=lambda **kwargs: click.echo(next(iter(kwargs.values()), None)), ) ctx = click.Context(cli, help_option_names=help_names) help_option = cli.get_help_option(ctx) assert help_option is not None assert help_option.name == "_click_default_help" result = runner.invoke(cli, args) assert result.output == expected_output assert result.exit_code == 0 result = runner.invoke(cli, [help_names[0]]) assert "Show this message and exit." in result.output assert result.exit_code == 0 def test_param_squatting_help_option_name(runner): """Claiming the reserved storage name of the automatic help option triggers a warning. """ @click.command() @click.argument("_click_default_help") def cli(_click_default_help): click.echo(_click_default_help) with pytest.warns(UserWarning, match="reserved for the automatic help option"): result = runner.invoke(cli, ["value"]) # The collision still breaks parsing, but no longer silently. assert result.exit_code == 2 def test_option_reusing_help_flag(runner): """An option reusing the ``--help`` flag replaces the automatic help option entirely. https://github.com/pallets/click/issues/2819 """ @click.command() @click.option("--help", default="default value") def cli(help): click.echo(help) assert cli.get_help_option(click.Context(cli)) is None result = runner.invoke(cli, []) assert result.output == "default value\n" assert result.exit_code == 0 result = runner.invoke(cli, ["--help", "custom"]) assert result.output == "custom\n" assert result.exit_code == 0 def test_repr(): @click.command() def command(): pass @click.group() def group(): pass @group.command() def subcommand(): pass assert repr(command) == "" assert repr(group) == "" assert repr(subcommand) == "" def test_return_values(): @click.command() def cli(): return 42 with cli.make_context("foo", []) as ctx: rv = cli.invoke(ctx) assert rv == 42 def test_basic_group(runner): @click.group() def cli(): """This is the root.""" click.echo("ROOT EXECUTED") @cli.command() def subcommand(): """This is a subcommand.""" click.echo("SUBCOMMAND EXECUTED") result = runner.invoke(cli, ["--help"]) assert not result.exception assert "COMMAND [ARGS]..." in result.output assert "This is the root" in result.output assert "This is a subcommand." in result.output assert result.exit_code == 0 assert "ROOT EXECUTED" not in result.output result = runner.invoke(cli, ["subcommand"]) assert not result.exception assert result.exit_code == 0 assert "ROOT EXECUTED" in result.output assert "SUBCOMMAND EXECUTED" in result.output def test_group_commands_dict(runner): """A Group can be built with a dict of commands.""" @click.command() def sub(): click.echo("sub", nl=False) cli = click.Group(commands={"other": sub}) result = runner.invoke(cli, ["other"]) assert result.output == "sub" def test_group_from_list(runner): """A Group can be built with a list of commands.""" @click.command() def sub(): click.echo("sub", nl=False) cli = click.Group(commands=[sub]) result = runner.invoke(cli, ["sub"]) assert result.output == "sub" @pytest.mark.parametrize( ("args", "expect"), [ ([], "S:[no value]"), (["--s=42"], "S:[42]"), (["--s"], "Error: Option '--s' requires an argument."), (["--s="], "S:[]"), (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"), ], ) def test_string_option(runner, args, expect): @click.command() @click.option("--s", default="no value") def cli(s): click.echo(f"S:[{s}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "expect"), [ ([], "I:[84]"), (["--i=23"], "I:[46]"), (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."), ], ) def test_int_option(runner, args, expect): @click.command() @click.option("--i", default=42) def cli(i): click.echo(f"I:[{i * 2}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "expect"), [ ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"), ( ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"], "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]", ), (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."), ], ) def test_uuid_option(runner, args, expect): @click.command() @click.option( "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID ) def cli(u): click.echo(f"U:[{u}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "expect"), [ ([], "F:[42.0]"), ("--f=23.5", "F:[23.5]"), ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."), ], ) def test_float_option(runner, args, expect): @click.command() @click.option("--f", default=42.0) def cli(f): click.echo(f"F:[{f}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "default", "expect"), [ (["--on"], True, True), (["--on"], False, True), (["--on"], None, True), (["--on"], UNSET, True), (["--off"], True, False), (["--off"], False, False), (["--off"], None, False), (["--off"], UNSET, False), ([], True, True), ([], False, False), ([], None, None), ([], UNSET, False), ], ) def test_boolean_switch(runner, args, default, expect): @click.command() @click.option("--on/--off", default=default) def cli(on): return on result = runner.invoke(cli, args, standalone_mode=False) assert result.return_value is expect @pytest.mark.parametrize( ("default", "args", "expect"), ( (True, ["--f"], True), (True, [], True), (False, ["--f"], True), (False, [], False), # Boolean flags have a 3-states logic. # See: https://github.com/pallets/click/issues/3024#issue-3285556668 (None, ["--f"], True), (None, [], None), ), ) def test_boolean_flag(runner, default, args, expect): @click.command() @click.option("--f", is_flag=True, default=default) def cli(f): return f result = runner.invoke(cli, args, standalone_mode=False) assert result.return_value is expect @pytest.mark.parametrize( ("value", "expect"), [ *((x, "True") for x in ("1", "true", "t", "yes", "y", "on")), *((x, "False") for x in ("0", "false", "f", "no", "n", "off")), ], ) def test_boolean_conversion(runner, value, expect): @click.command() @click.option("--flag", type=bool) def cli(flag): click.echo(flag, nl=False) result = runner.invoke(cli, ["--flag", value]) assert result.output == expect result = runner.invoke(cli, ["--flag", value.title()]) assert result.output == expect @pytest.mark.parametrize( ("default", "args", "expected"), # These test cases are similar to the ones in # tests/test_options.py::test_default_dual_option_callback, so keep them in sync. ( # Each option is returning its own flag_value, whatever the default is. (True, ["--upper"], "upper"), (True, ["--lower"], "lower"), (False, ["--upper"], "upper"), (False, ["--lower"], "lower"), (None, ["--upper"], "upper"), (None, ["--lower"], "lower"), (UNSET, ["--upper"], "upper"), (UNSET, ["--lower"], "lower"), # Check that the last option wins when both are specified. (True, ["--upper", "--lower"], "lower"), (True, ["--lower", "--upper"], "upper"), # Check that the default is returned as-is when no option is specified. ("upper", [], "upper"), ("lower", [], "lower"), ("uPPer", [], "uPPer"), ("lOwEr", [], "lOwEr"), (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "), (None, [], None), # Default is normalized to None if it is UNSET. (UNSET, [], None), # Special case: if default=True and flag_value is set, the value returned is the # flag_value, not the True Python value itself. (True, [], "upper"), # Non-string defaults are process as strings by the default Parameter's type. (False, [], "False"), (42, [], "42"), (12.3, [], "12.3"), ), ) def test_flag_value_dual_options(runner, default, args, expected): """Check how default is processed when options compete for the same variable name. Covers the regression reported in https://github.com/pallets/click/issues/3024#issuecomment-3146199461 .. hint:: Similar to ``test_options.py::test_default_dual_option_callback``. ``test_defaults.py::test_shared_param_prefers_first_default`` is a smoke-test complement that exercises both default placements. """ @click.command() @click.option("--upper", "case", flag_value="upper", default=default) @click.option("--lower", "case", flag_value="lower") def cli(case): click.echo(repr(case), nl=False) result = runner.invoke(cli, args) assert result.output == repr(expected) def test_file_option(runner, tmp_path): @click.command() @click.option("--file", type=click.File("w")) def input(file): file.write("Hello World!\n") @click.command() @click.option("--file", type=click.File("r")) def output(file): click.echo(file.read()) example = tmp_path / "example.txt" result_in = runner.invoke(input, [f"--file={example}"]) result_out = runner.invoke(output, [f"--file={example}"]) assert not result_in.exception assert result_in.output == "" assert not result_out.exception assert result_out.output == "Hello World!\n\n" def test_file_lazy_mode(runner, tmp_path): do_io = False @click.command() @click.option("--file", type=click.File("w")) def input(file): if do_io: file.write("Hello World!\n") @click.command() @click.option("--file", type=click.File("r")) def output(file): pass example = tmp_path / "example.txt" example.mkdir() do_io = True result_in = runner.invoke(input, [f"--file={example}"]) assert result_in.exit_code == 1 do_io = False result_in = runner.invoke(input, [f"--file={example}"]) assert result_in.exit_code == 0 result_out = runner.invoke(output, [f"--file={example}"]) assert result_out.exception @click.command() @click.option("--file", type=click.File("w", lazy=False)) def input_non_lazy(file): file.write("Hello World!\n") non_lazy = tmp_path / "non_lazy.txt" non_lazy.mkdir() result_in = runner.invoke(input_non_lazy, [f"--file={non_lazy}"]) assert result_in.exit_code == 2 assert f"Invalid value for '--file': '{non_lazy}'" in result_in.output def test_path_option(runner, tmp_path): @click.command() @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True)) def write_to_dir(o): with open(os.path.join(o, "foo.txt"), "wb") as f: f.write(b"meh\n") test_dir = tmp_path / "test" test_dir.mkdir() result = runner.invoke(write_to_dir, ["-O", str(test_dir)]) assert not result.exception with open(test_dir / "foo.txt", "rb") as f: assert f.read() == b"meh\n" result = runner.invoke(write_to_dir, ["-O", str(test_dir / "foo.txt")]) assert "is a file" in result.output @click.command() @click.option("-f", type=click.Path(exists=True)) def showtype(f): click.echo(f"is_file={os.path.isfile(f)}") click.echo(f"is_dir={os.path.isdir(f)}") result = runner.invoke(showtype, ["-f", str(tmp_path / "xxx")]) assert "does not exist" in result.output result = runner.invoke(showtype, ["-f", str(tmp_path)]) assert "is_file=False" in result.output assert "is_dir=True" in result.output @click.command() @click.option("-f", type=click.Path()) def exists(f): click.echo(f"exists={os.path.exists(f)}") result = runner.invoke(exists, ["-f", str(tmp_path / "xxx")]) assert "exists=False" in result.output result = runner.invoke(exists, ["-f", str(tmp_path)]) assert "exists=True" in result.output def test_choice_option(runner): @click.command() @click.option("--method", type=click.Choice(["foo", "bar", "baz"])) def cli(method): click.echo(method) result = runner.invoke(cli, ["--method=foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(cli, ["--method=meh"]) assert result.exit_code == 2 assert ( "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "--method [foo|bar|baz]" in result.output def test_choice_argument(runner): @click.command() @click.argument("method", type=click.Choice(["foo", "bar", "baz"])) def cli(method): click.echo(method) result = runner.invoke(cli, ["foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output def test_choice_argument_enum(runner): class MyEnum(str, enum.Enum): FOO = "foo-value" BAR = "bar-value" BAZ = "baz-value" @click.command() @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False)) def cli(method: MyEnum): assert isinstance(method, MyEnum) click.echo(method) result = runner.invoke(cli, ["foo"]) assert result.output == "foo-value\n" assert not result.exception result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output def test_choice_argument_custom_type(runner): class MyClass: def __init__(self, value: str) -> None: self.value = value def __str__(self) -> str: return self.value @click.command() @click.argument( "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")]) ) def cli(method: MyClass): assert isinstance(method, MyClass) click.echo(method) result = runner.invoke(cli, ["foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output def test_choice_argument_none(runner): @click.command() @click.argument( "method", type=click.Choice(["not-none", None], case_sensitive=False) ) def cli(method: str | None): assert isinstance(method, str) or method is None click.echo(repr(method), nl=False) result = runner.invoke(cli, ["not-none"]) assert not result.exception assert result.output == repr("not-none") result = runner.invoke(cli, ["none"]) assert not result.exception assert result.output == repr(None) result = runner.invoke(cli, []) assert result.exception assert ( "Error: Missing argument '{not-none|none}'. " "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr ) result = runner.invoke(cli, ["--help"]) assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n") def test_choice_argument_optional_metavar(runner): """Optional Choice arguments reuse the type's brackets instead of doubling. Without this the usage line for a ``Choice`` argument with ``nargs=-1`` or ``required=False`` rendered as ``[[a|b|c]]``: one pair from ``Choice`` to enumerate values, a second pair from ``Argument`` to mark it optional. """ @click.command() @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), nargs=-1) def cli_variadic(method): pass @click.command() @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), required=False) def cli_optional(method): pass variadic = runner.invoke(cli_variadic, ["--help"]).output assert "Usage: cli-variadic [OPTIONS] [foo|bar|baz]...\n" in variadic assert "[[foo|bar|baz]]" not in variadic optional = runner.invoke(cli_optional, ["--help"]).output assert "Usage: cli-optional [OPTIONS] [foo|bar|baz]\n" in optional assert "[[foo|bar|baz]]" not in optional def test_datetime_argument_optional_metavar(runner): """``DateTime`` arguments behave the same way as ``Choice``.""" @click.command() @click.argument("when", type=click.DateTime(formats=["%Y-%m-%d"]), required=False) def cli(when): pass result = runner.invoke(cli, ["--help"]) assert "Usage: cli [OPTIONS] [%Y-%m-%d]\n" in result.output assert "[[%Y-%m-%d]]" not in result.output def test_datetime_option_default(runner): @click.command() @click.option("--start_date", type=click.DateTime()) def cli(start_date): click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S")) result = runner.invoke(cli, ["--start_date=2015-09-29"]) assert not result.exception assert result.output == "2015-09-29T00:00:00\n" result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"]) assert not result.exception assert result.output == "2015-09-29T09:11:22\n" result = runner.invoke(cli, ["--start_date=2015-09"]) assert result.exit_code == 2 assert ( "Invalid value for '--start_date': '2015-09' does not match the formats" " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'." ) in result.output result = runner.invoke(cli, ["--help"]) assert ( "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output ) def test_datetime_option_custom(runner): @click.command() @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"])) def cli(start_date): click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S")) result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"]) assert not result.exception assert result.output == "2010-06-05T00:00:00\n" def test_required_option(runner): @click.command() @click.option("--foo", required=True) def cli(foo): click.echo(foo) result = runner.invoke(cli, []) assert result.exit_code == 2 assert "Missing option '--foo'" in result.output def test_evaluation_order(runner): called = [] def memo(ctx, param, value): called.append(value) return value @click.command() @click.option("--missing", default="missing", is_eager=False, callback=memo) @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo) @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo) @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo) @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo) @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo) @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo) def cli(**x): pass result = runner.invoke( cli, [ "--eager-flag2", "--eager-flag1", "--normal-flag2", "--eager-flag3", "--normal-flag3", "--normal-flag3", "--normal-flag1", "--normal-flag1", ], ) assert not result.exception assert called == [ "eager2", "eager1", "eager3", "normal2", "normal3", "normal1", "missing", ] def test_hidden_option(runner): @click.command() @click.option("--nope", hidden=True) def cli(nope): click.echo(nope) result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "--nope" not in result.output def test_hidden_command(runner): @click.group() def cli(): pass @cli.command(hidden=True) def nope(): pass result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "nope" not in result.output def test_hidden_group(runner): @click.group() def cli(): pass @cli.group(hidden=True) def subgroup(): pass @subgroup.command() def nope(): pass result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "subgroup" not in result.output assert "nope" not in result.output def test_summary_line(runner): @click.group() def cli(): pass @cli.command() def cmd(): """ Summary line without period Here is a sentence. And here too. """ pass result = runner.invoke(cli, ["--help"]) assert "Summary line without period" in result.output assert "Here is a sentence." not in result.output def test_help_invalid_default(runner): cli = click.Command( "cli", params=[ click.Option( ["-a"], type=click.Path(exists=True), default="not found", show_default=True, ), ], ) result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "default: not found" in result.output def test_version_option_resolves_import_name_to_distribution(runner, monkeypatch): """When ``package_name`` (detected or passed) is an import name that differs from its installed distribution name (``PIL`` vs ``Pillow``), ``version_option`` resolves it via ``packages_distributions()`` instead of raising ``RuntimeError``. """ import importlib.metadata def fake_version(name): if name == "pillow": return "10.4.0" raise importlib.metadata.PackageNotFoundError(name) monkeypatch.setattr(importlib.metadata, "version", fake_version) monkeypatch.setattr( importlib.metadata, "packages_distributions", lambda: {"PIL": ["pillow"]}, ) @click.command() @click.version_option(package_name="PIL") def cli(): pass result = runner.invoke(cli, ["--version"], prog_name="imageapp") assert result.exit_code == 0 assert "10.4.0" in result.output def test_version_option_ambiguous_import_name_errors(runner, monkeypatch): """When an import name maps to multiple installed distributions, the user must disambiguate. The error names the candidates. """ import importlib.metadata def fake_version(name): raise importlib.metadata.PackageNotFoundError(name) monkeypatch.setattr(importlib.metadata, "version", fake_version) monkeypatch.setattr( importlib.metadata, "packages_distributions", lambda: {"plug": ["foo-plug", "bar-plug"]}, ) @click.command() @click.version_option(package_name="plug") def cli(): pass result = runner.invoke(cli, ["--version"]) assert result.exit_code != 0 msg = str(result.exception) assert "multiple installed distributions" in msg assert "foo-plug" in msg assert "bar-plug" in msg def test_version_option_unknown_package_errors(runner, monkeypatch): """When the name resolves to no distribution, keep the existing error.""" import importlib.metadata def fake_version(name): raise importlib.metadata.PackageNotFoundError(name) monkeypatch.setattr(importlib.metadata, "version", fake_version) monkeypatch.setattr(importlib.metadata, "packages_distributions", lambda: {}) @click.command() @click.version_option(package_name="nonexistent") def cli(): pass result = runner.invoke(cli, ["--version"]) assert result.exit_code != 0 assert "not installed" in str(result.exception) @pytest.mark.parametrize("args", [["--version"], ["-V"]]) def test_custom_version_option(runner, args): @click.command() @click.custom_version_option(lambda ctx: "custom 9.9.9", "-V", "--version") def cli(): pass result = runner.invoke(cli, args) assert result.exit_code == 0 assert result.output == "custom 9.9.9\n" def test_custom_version_option_receives_context(runner): @click.command() @click.custom_version_option(lambda ctx: f"{ctx.info_name} 1.0") def cli(): pass result = runner.invoke(cli, ["--version"], prog_name="mytool") assert result.exit_code == 0 assert result.output == "mytool 1.0\n" @pytest.mark.parametrize( ("nargs", "multiple", "default", "expect"), [ (2, False, None, None), (2, False, (None, None), (None, None)), (None, True, None, ()), (None, True, (None, None), (None, None)), (2, True, None, ()), (2, True, [(None, None)], ((None, None),)), (-1, None, None, ()), ], ) def test_cast_multi_default(runner, nargs, multiple, default, expect): if nargs == -1: param = click.Argument(["a"], nargs=nargs, default=default) else: param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default) cli = click.Command("cli", params=[param], callback=lambda a: a) result = runner.invoke(cli, standalone_mode=False) assert result.exception is None assert result.return_value == expect