Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

691 lines · 20.6 KiB · Python

Last changed by

Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348

History of this file

Take it

1import os2import re34import pytest56import click789def test_prefixes(runner):10    @click.command()11    @click.option("++foo", is_flag=True, help="das foo")12    @click.option("--bar", is_flag=True, help="das bar")13    def cli(foo, bar):14        click.echo(f"foo={foo} bar={bar}")1516    result = runner.invoke(cli, ["++foo", "--bar"])17    assert not result.exception18    assert result.output == "foo=True bar=True\n"1920    result = runner.invoke(cli, ["--help"])21    assert re.search(r"\+\+foo\s+das foo", result.output) is not None22    assert re.search(r"--bar\s+das bar", result.output) is not None232425def test_invalid_option(runner):26    with pytest.raises(TypeError, match="name was passed") as exc_info:27        click.Option(["foo"])2829    message = str(exc_info.value)30    assert "name was passed (foo)" in message31    assert "declare an argument" in message32    assert "'--foo'" in message333435def test_invalid_nargs(runner):36    with pytest.raises(TypeError, match="nargs < 0"):3738        @click.command()39        @click.option("--foo", nargs=-1)40        def cli(foo):41            pass424344def test_nargs_tup_composite_mult(runner):45    @click.command()46    @click.option("--item", type=(str, int), multiple=True)47    def copy(item):48        for name, id in item:49            click.echo(f"name={name} id={id:d}")5051    result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])52    assert not result.exception53    assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]545556def test_counting(runner):57    @click.command()58    @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))59    def cli(v):60        click.echo(f"verbosity={v:d}")6162    result = runner.invoke(cli, ["-vvv"])63    assert not result.exception64    assert result.output == "verbosity=3\n"6566    result = runner.invoke(cli, ["-vvvv"])67    assert result.exception68    assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output6970    result = runner.invoke(cli, [])71    assert not result.exception72    assert result.output == "verbosity=0\n"7374    result = runner.invoke(cli, ["--help"])75    assert re.search(r"-v\s+Verbosity", result.output) is not None767778@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])79def test_unknown_options(runner, unknown_flag):80    @click.command()81    def cli():82        pass8384    result = runner.invoke(cli, [unknown_flag])85    assert result.exception86    assert f"no such option: {unknown_flag}" in result.output878889@pytest.mark.parametrize(90    ("value", "expect"),91    [92        ("--cat", "Did you mean --count?"),93        ("--bounds", "(Possible options: --bound, --count)"),94        ("--bount", "(Possible options: --bound, --count)"),95    ],96)97def test_suggest_possible_options(runner, value, expect):98    cli = click.Command(99        "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]100    )101    result = runner.invoke(cli, [value])102    assert expect in result.output103104105def test_multiple_required(runner):106    @click.command()107    @click.option("-m", "--message", multiple=True, required=True)108    def cli(message):109        click.echo("\n".join(message))110111    result = runner.invoke(cli, ["-m", "foo", "-mbar"])112    assert not result.exception113    assert result.output == "foo\nbar\n"114115    result = runner.invoke(cli, [])116    assert result.exception117    assert "Error: Missing option '-m' / '--message'." in result.output118119120def test_empty_envvar(runner):121    @click.command()122    @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")123    def cli(mypath):124        click.echo(f"mypath: {mypath}")125126    result = runner.invoke(cli, [], env={"MYPATH": ""})127    assert result.exit_code == 0128    assert result.output == "mypath: None\n"129130131def test_multiple_envvar(runner):132    @click.command()133    @click.option("--arg", multiple=True)134    def cmd(arg):135        click.echo("|".join(arg))136137    result = runner.invoke(138        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}139    )140    assert not result.exception141    assert result.output == "foo|bar|baz\n"142143    @click.command()144    @click.option("--arg", multiple=True, envvar="X")145    def cmd(arg):146        click.echo("|".join(arg))147148    result = runner.invoke(cmd, [], env={"X": "foo bar baz"})149    assert not result.exception150    assert result.output == "foo|bar|baz\n"151152    @click.command()153    @click.option("--arg", multiple=True, type=click.Path())154    def cmd(arg):155        click.echo("|".join(arg))156157    result = runner.invoke(158        cmd,159        [],160        auto_envvar_prefix="TEST",161        env={"TEST_ARG": f"foo{os.path.pathsep}bar"},162    )163    assert not result.exception164    assert result.output == "foo|bar\n"165166167def test_trailing_blanks_boolean_envvar(runner):168    @click.command()169    @click.option("--shout/--no-shout", envvar="SHOUT")170    def cli(shout):171        click.echo(f"shout: {shout!r}")172173    result = runner.invoke(cli, [], env={"SHOUT": " true "})174    assert result.exit_code == 0175    assert result.output == "shout: True\n"176177178def test_multiple_default_help(runner):179    @click.command()180    @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)181    @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)182    def cmd(arg, arg2):183        pass184185    result = runner.invoke(cmd, ["--help"])186    assert not result.exception187    assert "foo, bar" in result.output188    assert "1, 2" in result.output189190191def test_show_default_default_map(runner):192    @click.command()193    @click.option("--arg", default="a", show_default=True)194    def cmd(arg):195        click.echo(arg)196197    result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})198199    assert not result.exception200    assert "[default: b]" in result.output201202203def test_multiple_default_type():204    opt = click.Option(["-a"], multiple=True, default=(1, 2))205    assert opt.nargs == 1206    assert opt.multiple207    assert opt.type is click.INT208    ctx = click.Context(click.Command("test"))209    assert opt.get_default(ctx) == (1, 2)210211212def test_multiple_default_composite_type():213    opt = click.Option(["-a"], multiple=True, default=[(1, "a")])214    assert opt.nargs == 2215    assert opt.multiple216    assert isinstance(opt.type, click.Tuple)217    assert opt.type.types == [click.INT, click.STRING]218    ctx = click.Context(click.Command("test"))219    assert opt.get_default(ctx) == ((1, "a"),)220221222def test_parse_multiple_default_composite_type(runner):223    @click.command()224    @click.option("-a", multiple=True, default=("a", "b"))225    @click.option("-b", multiple=True, default=[(1, "a")])226    def cmd(a, b):227        click.echo(a)228        click.echo(b)229230    # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())231    # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"232    result = runner.invoke(cmd)233    assert result.output == "('a', 'b')\n((1, 'a'),)\n"234235236def test_dynamic_default_help_unset(runner):237    @click.command()238    @click.option(239        "--username",240        prompt=True,241        default=lambda: os.environ.get("USER", ""),242        show_default=True,243    )244    def cmd(username):245        print("Hello,", username)246247    result = runner.invoke(cmd, ["--help"])248    assert result.exit_code == 0249    assert "--username" in result.output250    assert "lambda" not in result.output251    assert "(dynamic)" in result.output252253254def test_dynamic_default_help_text(runner):255    @click.command()256    @click.option(257        "--username",258        prompt=True,259        default=lambda: os.environ.get("USER", ""),260        show_default="current user",261    )262    def cmd(username):263        print("Hello,", username)264265    result = runner.invoke(cmd, ["--help"])266    assert result.exit_code == 0267    assert "--username" in result.output268    assert "lambda" not in result.output269    assert "(current user)" in result.output270271272@pytest.mark.parametrize(273    ("type", "expect"),274    [275        (click.IntRange(1, 32), "1<=x<=32"),276        (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),277        (click.IntRange(1), "x>=1"),278        (click.IntRange(max=32), "x<=32"),279    ],280)281def test_intrange_default_help_text(runner, type, expect):282    option = click.Option(["--count"], type=type, show_default=True, default=2)283    context = click.Context(click.Command("test"))284    result = option.get_help_record(context)[1]285    assert expect in result286287288def test_toupper_envvar_prefix(runner):289    @click.command()290    @click.option("--arg")291    def cmd(arg):292        click.echo(arg)293294    result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})295    assert not result.exception296    assert result.output == "foo\n"297298299def test_nargs_envvar(runner):300    @click.command()301    @click.option("--arg", nargs=2)302    def cmd(arg):303        click.echo("|".join(arg))304305    result = runner.invoke(306        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}307    )308    assert not result.exception309    assert result.output == "foo|bar\n"310311    @click.command()312    @click.option("--arg", nargs=2, multiple=True)313    def cmd(arg):314        for item in arg:315            click.echo("|".join(item))316317    result = runner.invoke(318        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}319    )320    assert not result.exception321    assert result.output == "x|1\ny|2\n"322323324def test_show_envvar(runner):325    @click.command()326    @click.option("--arg1", envvar="ARG1", show_envvar=True)327    def cmd(arg):328        pass329330    result = runner.invoke(cmd, ["--help"])331    assert not result.exception332    assert "ARG1" in result.output333334335def test_show_envvar_auto_prefix(runner):336    @click.command()337    @click.option("--arg1", show_envvar=True)338    def cmd(arg):339        pass340341    result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")342    assert not result.exception343    assert "TEST_ARG1" in result.output344345346def test_show_envvar_auto_prefix_dash_in_command(runner):347    @click.group()348    def cli():349        pass350351    @cli.command()352    @click.option("--baz", show_envvar=True)353    def foo_bar(baz):354        pass355356    result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")357    assert not result.exception358    assert "TEST_FOO_BAR_BAZ" in result.output359360361def test_custom_validation(runner):362    def validate_pos_int(ctx, param, value):363        if value < 0:364            raise click.BadParameter("Value needs to be positive")365        return value366367    @click.command()368    @click.option("--foo", callback=validate_pos_int, default=1)369    def cmd(foo):370        click.echo(foo)371372    result = runner.invoke(cmd, ["--foo", "-1"])373    assert "Invalid value for '--foo': Value needs to be positive" in result.output374375    result = runner.invoke(cmd, ["--foo", "42"])376    assert result.output == "42\n"377378379def test_winstyle_options(runner):380    @click.command()381    @click.option("/debug;/no-debug", help="Enables or disables debug mode.")382    def cmd(debug):383        click.echo(debug)384385    result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])386    assert result.output == "True\n"387    result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])388    assert result.output == "False\n"389    result = runner.invoke(cmd, [], help_option_names=["/?"])390    assert result.output == "False\n"391    result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])392    assert "/debug; /no-debug  Enables or disables debug mode." in result.output393    assert "/?                 Show this message and exit." in result.output394395396def test_legacy_options(runner):397    @click.command()398    @click.option("-whatever")399    def cmd(whatever):400        click.echo(whatever)401402    result = runner.invoke(cmd, ["-whatever", "42"])403    assert result.output == "42\n"404    result = runner.invoke(cmd, ["-whatever=23"])405    assert result.output == "23\n"406407408def test_missing_option_string_cast():409    ctx = click.Context(click.Command(""))410411    with pytest.raises(click.MissingParameter) as excinfo:412        click.Option(["-a"], required=True).full_process_value(ctx, None)413414    assert str(excinfo.value) == "missing parameter: a"415416417def test_missing_choice(runner):418    @click.command()419    @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)420    def cmd(foo):421        click.echo(foo)422423    result = runner.invoke(cmd)424    assert result.exit_code == 2425    error, separator, choices = result.output.partition("Choose from")426    assert "Error: Missing option '--foo'. " in error427    assert "Choose from" in separator428    assert "foo" in choices429    assert "bar" in choices430431432def test_case_insensitive_choice(runner):433    @click.command()434    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))435    def cmd(foo):436        click.echo(foo)437438    result = runner.invoke(cmd, ["--foo", "apple"])439    assert result.exit_code == 0440    assert result.output == "Apple\n"441442    result = runner.invoke(cmd, ["--foo", "oRANGe"])443    assert result.exit_code == 0444    assert result.output == "Orange\n"445446    result = runner.invoke(cmd, ["--foo", "Apple"])447    assert result.exit_code == 0448    assert result.output == "Apple\n"449450    @click.command()451    @click.option("--foo", type=click.Choice(["Orange", "Apple"]))452    def cmd2(foo):453        click.echo(foo)454455    result = runner.invoke(cmd2, ["--foo", "apple"])456    assert result.exit_code == 2457458    result = runner.invoke(cmd2, ["--foo", "oRANGe"])459    assert result.exit_code == 2460461    result = runner.invoke(cmd2, ["--foo", "Apple"])462    assert result.exit_code == 0463464465def test_case_insensitive_choice_returned_exactly(runner):466    @click.command()467    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))468    def cmd(foo):469        click.echo(foo)470471    result = runner.invoke(cmd, ["--foo", "apple"])472    assert result.exit_code == 0473    assert result.output == "Apple\n"474475476def test_option_help_preserve_paragraphs(runner):477    @click.command()478    @click.option(479        "-C",480        "--config",481        type=click.Path(),482        help="""Configuration file to use.483484        If not given, the environment variable CONFIG_FILE is consulted485        and used if set. If neither are given, a default configuration486        file is loaded.""",487    )488    def cmd(config):489        pass490491    result = runner.invoke(cmd, ["--help"],)492    assert result.exit_code == 0493    i = " " * 21494    assert (495        "  -C, --config PATH  Configuration file to use.\n"496        f"{i}\n"497        f"{i}If not given, the environment variable CONFIG_FILE is\n"498        f"{i}consulted and used if set. If neither are given, a default\n"499        f"{i}configuration file is loaded."500    ) in result.output501502503def test_argument_custom_class(runner):504    class CustomArgument(click.Argument):505        def get_default(self, ctx):506            """a dumb override of a default value for testing"""507            return "I am a default"508509    @click.command()510    @click.argument("testarg", cls=CustomArgument, default="you wont see me")511    def cmd(testarg):512        click.echo(testarg)513514    result = runner.invoke(cmd)515    assert "I am a default" in result.output516    assert "you wont see me" not in result.output517518519def test_option_custom_class(runner):520    class CustomOption(click.Option):521        def get_help_record(self, ctx):522            """a dumb override of a help text for testing"""523            return ("--help", "I am a help text")524525    @click.command()526    @click.option("--testoption", cls=CustomOption, help="you wont see me")527    def cmd(testoption):528        click.echo(testoption)529530    result = runner.invoke(cmd, ["--help"])531    assert "I am a help text" in result.output532    assert "you wont see me" not in result.output533534535def test_option_custom_class_reusable(runner):536    """Ensure we can reuse a custom class option. See Issue #926"""537538    class CustomOption(click.Option):539        def get_help_record(self, ctx):540            """a dumb override of a help text for testing"""541            return ("--help", "I am a help text")542543    # Assign to a variable to re-use the decorator.544    testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")545546    @click.command()547    @testoption548    def cmd1(testoption):549        click.echo(testoption)550551    @click.command()552    @testoption553    def cmd2(testoption):554        click.echo(testoption)555556    # Both of the commands should have the --help option now.557    for cmd in (cmd1, cmd2):558559        result = runner.invoke(cmd, ["--help"])560        assert "I am a help text" in result.output561        assert "you wont see me" not in result.output562563564def test_bool_flag_with_type(runner):565    @click.command()566    @click.option("--shout/--no-shout", default=False, type=bool)567    def cmd(shout):568        pass569570    result = runner.invoke(cmd)571    assert not result.exception572573574def test_aliases_for_flags(runner):575    @click.command()576    @click.option("--warnings/--no-warnings", " /-W", default=True)577    def cli(warnings):578        click.echo(warnings)579580    result = runner.invoke(cli, ["--warnings"])581    assert result.output == "True\n"582    result = runner.invoke(cli, ["--no-warnings"])583    assert result.output == "False\n"584    result = runner.invoke(cli, ["-W"])585    assert result.output == "False\n"586587    @click.command()588    @click.option("--warnings/--no-warnings", "-w", default=True)589    def cli_alt(warnings):590        click.echo(warnings)591592    result = runner.invoke(cli_alt, ["--warnings"])593    assert result.output == "True\n"594    result = runner.invoke(cli_alt, ["--no-warnings"])595    assert result.output == "False\n"596    result = runner.invoke(cli_alt, ["-w"])597    assert result.output == "True\n"598599600@pytest.mark.parametrize(601    "option_args,expected",602    [603        (["--aggressive", "--all", "-a"], "aggressive"),604        (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),605        (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),606        (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),607        (["-a", "-b", "-c"], "a"),608        (["-c", "-b", "-a"], "c"),609        (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),610        (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),611        (["--from", "-f", "_from"], "_from"),612        (["--return", "-r", "_ret"], "_ret"),613    ],614)615def test_option_names(runner, option_args, expected):616    @click.command()617    @click.option(*option_args, is_flag=True)618    def cmd(**kwargs):619        click.echo(str(kwargs[expected]))620621    assert cmd.params[0].name == expected622623    for form in option_args:624        if form.startswith("-"):625            result = runner.invoke(cmd, [form])626            assert result.output == "True\n"627628629def test_flag_duplicate_names(runner):630    with pytest.raises(ValueError, match="cannot use the same flag for true/false"):631        click.Option(["--foo/--foo"], default=False)632633634@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])635def test_show_default_boolean_flag_name(runner, default, expect):636    """When a boolean flag has distinct True/False opts, it should show637    the default opt name instead of the default value. It should only638    show one name even if multiple are declared.639    """640    opt = click.Option(641        ("--cache/--no-cache", "--c/--nc"),642        default=default,643        show_default=True,644        help="Enable/Disable the cache.",645    )646    ctx = click.Context(click.Command("test"))647    message = opt.get_help_record(ctx)[1]648    assert f"[default: {expect}]" in message649650651def test_show_default_boolean_flag_value(runner):652    """When a boolean flag only has one opt, it will show the default653    value, not the opt name.654    """655    opt = click.Option(656        ("--cache",), is_flag=True, show_default=True, help="Enable the cache.",657    )658    ctx = click.Context(click.Command("test"))659    message = opt.get_help_record(ctx)[1]660    assert "[default: False]" in message661662663@pytest.mark.parametrize(664    ("args", "expect"),665    [666        (None, (None, None, ())),667        (["--opt"], ("flag", None, ())),668        (["--opt", "-a", 42], ("flag", "42", ())),669        (["--opt", "test", "-a", 42], ("test", "42", ())),670        (["--opt=test", "-a", 42], ("test", "42", ())),671        (["-o"], ("flag", None, ())),672        (["-o", "-a", 42], ("flag", "42", ())),673        (["-o", "test", "-a", 42], ("test", "42", ())),674        (["-otest", "-a", 42], ("test", "42", ())),675        (["a", "b", "c"], (None, None, ("a", "b", "c"))),676        (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),677        (["--opt", "test"], ("test", None, ())),678        (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),679        (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),680    ],681)682def test_option_with_optional_value(runner, args, expect):683    @click.command()684    @click.option("-o", "--opt", is_flag=False, flag_value="flag")685    @click.option("-a")686    @click.argument("b", nargs=-1)687    def cli(opt, a, b):688        return opt, a, b689690    result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)691    assert result.return_value == expect