Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

733 lines · 19.9 KiB · Python

Last changed by

Add comments about the test casesKevin Deldyckebefore adoptionc498ced

History of this file

Take it

1from __future__ import annotations23import enum4import os5from itertools import chain67import pytest89import click10from click._utils import UNSET111213def test_basic_functionality(runner):14    @click.command()15    def cli():16        """Hello World!"""17        click.echo("I EXECUTED")1819    result = runner.invoke(cli, ["--help"])20    assert not result.exception21    assert "Hello World!" in result.output22    assert "Show this message and exit." in result.output23    assert result.exit_code == 024    assert "I EXECUTED" not in result.output2526    result = runner.invoke(cli, [])27    assert not result.exception28    assert "I EXECUTED" in result.output29    assert result.exit_code == 0303132def test_repr():33    @click.command()34    def command():35        pass3637    @click.group()38    def group():39        pass4041    @group.command()42    def subcommand():43        pass4445    assert repr(command) == "<Command command>"46    assert repr(group) == "<Group group>"47    assert repr(subcommand) == "<Command subcommand>"484950def test_return_values():51    @click.command()52    def cli():53        return 425455    with cli.make_context("foo", []) as ctx:56        rv = cli.invoke(ctx)57        assert rv == 42585960def test_basic_group(runner):61    @click.group()62    def cli():63        """This is the root."""64        click.echo("ROOT EXECUTED")6566    @cli.command()67    def subcommand():68        """This is a subcommand."""69        click.echo("SUBCOMMAND EXECUTED")7071    result = runner.invoke(cli, ["--help"])72    assert not result.exception73    assert "COMMAND [ARGS]..." in result.output74    assert "This is the root" in result.output75    assert "This is a subcommand." in result.output76    assert result.exit_code == 077    assert "ROOT EXECUTED" not in result.output7879    result = runner.invoke(cli, ["subcommand"])80    assert not result.exception81    assert result.exit_code == 082    assert "ROOT EXECUTED" in result.output83    assert "SUBCOMMAND EXECUTED" in result.output848586def test_group_commands_dict(runner):87    """A Group can be built with a dict of commands."""8889    @click.command()90    def sub():91        click.echo("sub", nl=False)9293    cli = click.Group(commands={"other": sub})94    result = runner.invoke(cli, ["other"])95    assert result.output == "sub"969798def test_group_from_list(runner):99    """A Group can be built with a list of commands."""100101    @click.command()102    def sub():103        click.echo("sub", nl=False)104105    cli = click.Group(commands=[sub])106    result = runner.invoke(cli, ["sub"])107    assert result.output == "sub"108109110@pytest.mark.parametrize(111    ("args", "expect"),112    [113        ([], "S:[no value]"),114        (["--s=42"], "S:[42]"),115        (["--s"], "Error: Option '--s' requires an argument."),116        (["--s="], "S:[]"),117        (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),118    ],119)120def test_string_option(runner, args, expect):121    @click.command()122    @click.option("--s", default="no value")123    def cli(s):124        click.echo(f"S:[{s}]")125126    result = runner.invoke(cli, args)127    assert expect in result.output128129    if expect.startswith("Error:"):130        assert result.exception is not None131    else:132        assert result.exception is None133134135@pytest.mark.parametrize(136    ("args", "expect"),137    [138        ([], "I:[84]"),139        (["--i=23"], "I:[46]"),140        (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),141    ],142)143def test_int_option(runner, args, expect):144    @click.command()145    @click.option("--i", default=42)146    def cli(i):147        click.echo(f"I:[{i * 2}]")148149    result = runner.invoke(cli, args)150    assert expect in result.output151152    if expect.startswith("Error:"):153        assert result.exception is not None154    else:155        assert result.exception is None156157158@pytest.mark.parametrize(159    ("args", "expect"),160    [161        ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"),162        (163            ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"],164            "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]",165        ),166        (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."),167    ],168)169def test_uuid_option(runner, args, expect):170    @click.command()171    @click.option(172        "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID173    )174    def cli(u):175        click.echo(f"U:[{u}]")176177    result = runner.invoke(cli, args)178    assert expect in result.output179180    if expect.startswith("Error:"):181        assert result.exception is not None182    else:183        assert result.exception is None184185186@pytest.mark.parametrize(187    ("args", "expect"),188    [189        ([], "F:[42.0]"),190        ("--f=23.5", "F:[23.5]"),191        ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."),192    ],193)194def test_float_option(runner, args, expect):195    @click.command()196    @click.option("--f", default=42.0)197    def cli(f):198        click.echo(f"F:[{f}]")199200    result = runner.invoke(cli, args)201    assert expect in result.output202203    if expect.startswith("Error:"):204        assert result.exception is not None205    else:206        assert result.exception is None207208209@pytest.mark.parametrize(210    ("args", "default", "expect"),211    [212        (["--on"], True, True),213        (["--on"], False, True),214        (["--on"], None, True),215        (["--on"], UNSET, True),216        (["--off"], True, False),217        (["--off"], False, False),218        (["--off"], None, False),219        (["--off"], UNSET, False),220        ([], True, True),221        ([], False, False),222        ([], None, None),223        ([], UNSET, False),224    ],225)226def test_boolean_switch(runner, args, default, expect):227    @click.command()228    @click.option("--on/--off", default=default)229    def cli(on):230        return on231232    result = runner.invoke(cli, args, standalone_mode=False)233    assert result.return_value is expect234235236@pytest.mark.parametrize(237    ("default", "args", "expect"),238    (239        (True, ["--f"], True),240        (True, [], True),241        (False, ["--f"], True),242        (False, [], False),243        # Boolean flags have a 3-states logic.244        # See: https://github.com/pallets/click/issues/3024#issue-3285556668245        (None, ["--f"], True),246        (None, [], None),247    ),248)249def test_boolean_flag(runner, default, args, expect):250    @click.command()251    @click.option("--f", is_flag=True, default=default)252    def cli(f):253        return f254255    result = runner.invoke(cli, args, standalone_mode=False)256    assert result.return_value is expect257258259@pytest.mark.parametrize(260    ("value", "expect"),261    chain(262        ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),263        ((x, "False") for x in ("0", "false", "f", "no", "n", "off")),264    ),265)266def test_boolean_conversion(runner, value, expect):267    @click.command()268    @click.option("--flag", type=bool)269    def cli(flag):270        click.echo(flag, nl=False)271272    result = runner.invoke(cli, ["--flag", value])273    assert result.output == expect274275    result = runner.invoke(cli, ["--flag", value.title()])276    assert result.output == expect277278279@pytest.mark.parametrize(280    ("default", "args", "expected"),281    # These test cases are similar to the ones in282    # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.283    (284        # Each option is returning its own flag_value, whatever the default is.285        (True, ["--upper"], "upper"),286        (True, ["--lower"], "lower"),287        (False, ["--upper"], "upper"),288        (False, ["--lower"], "lower"),289        (None, ["--upper"], "upper"),290        (None, ["--lower"], "lower"),291        (UNSET, ["--upper"], "upper"),292        (UNSET, ["--lower"], "lower"),293        # Check that the last option wins when both are specified.294        (True, ["--upper", "--lower"], "lower"),295        (True, ["--lower", "--upper"], "upper"),296        # Check that the default is returned as-is when no option is specified.297        ("upper", [], "upper"),298        ("lower", [], "lower"),299        ("uPPer", [], "uPPer"),300        ("lOwEr", [], "lOwEr"),301        (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),302        (None, [], None),303        # Default is normalized to None if it is UNSET.304        (UNSET, [], None),305        # Non-string defaults are process as strings by the default Parameter's type.306        (True, [], "True"),307        (False, [], "False"),308        (42, [], "42"),309        (12.3, [], "12.3"),310    ),311)312def test_flag_value_dual_options(runner, default, args, expected):313    """Check how default is processed when options compete for the same variable name.314315    Covers the regression reported in316    https://github.com/pallets/click/issues/3024#issuecomment-3146199461317    """318319    @click.command()320    @click.option("--upper", "case", flag_value="upper", default=default)321    @click.option("--lower", "case", flag_value="lower")322    def cli(case):323        click.echo(repr(case), nl=False)324325    result = runner.invoke(cli, args)326    assert result.output == repr(expected)327328329def test_file_option(runner):330    @click.command()331    @click.option("--file", type=click.File("w"))332    def input(file):333        file.write("Hello World!\n")334335    @click.command()336    @click.option("--file", type=click.File("r"))337    def output(file):338        click.echo(file.read())339340    with runner.isolated_filesystem():341        result_in = runner.invoke(input, ["--file=example.txt"])342        result_out = runner.invoke(output, ["--file=example.txt"])343344    assert not result_in.exception345    assert result_in.output == ""346    assert not result_out.exception347    assert result_out.output == "Hello World!\n\n"348349350def test_file_lazy_mode(runner):351    do_io = False352353    @click.command()354    @click.option("--file", type=click.File("w"))355    def input(file):356        if do_io:357            file.write("Hello World!\n")358359    @click.command()360    @click.option("--file", type=click.File("r"))361    def output(file):362        pass363364    with runner.isolated_filesystem():365        os.mkdir("example.txt")366367        do_io = True368        result_in = runner.invoke(input, ["--file=example.txt"])369        assert result_in.exit_code == 1370371        do_io = False372        result_in = runner.invoke(input, ["--file=example.txt"])373        assert result_in.exit_code == 0374375        result_out = runner.invoke(output, ["--file=example.txt"])376        assert result_out.exception377378    @click.command()379    @click.option("--file", type=click.File("w", lazy=False))380    def input_non_lazy(file):381        file.write("Hello World!\n")382383    with runner.isolated_filesystem():384        os.mkdir("example.txt")385        result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])386        assert result_in.exit_code == 2387        assert "Invalid value for '--file': 'example.txt'" in result_in.output388389390def test_path_option(runner):391    @click.command()392    @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))393    def write_to_dir(o):394        with open(os.path.join(o, "foo.txt"), "wb") as f:395            f.write(b"meh\n")396397    with runner.isolated_filesystem():398        os.mkdir("test")399400        result = runner.invoke(write_to_dir, ["-O", "test"])401        assert not result.exception402403        with open("test/foo.txt", "rb") as f:404            assert f.read() == b"meh\n"405406        result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])407        assert "is a file" in result.output408409    @click.command()410    @click.option("-f", type=click.Path(exists=True))411    def showtype(f):412        click.echo(f"is_file={os.path.isfile(f)}")413        click.echo(f"is_dir={os.path.isdir(f)}")414415    with runner.isolated_filesystem():416        result = runner.invoke(showtype, ["-f", "xxx"])417        assert "does not exist" in result.output418419        result = runner.invoke(showtype, ["-f", "."])420        assert "is_file=False" in result.output421        assert "is_dir=True" in result.output422423    @click.command()424    @click.option("-f", type=click.Path())425    def exists(f):426        click.echo(f"exists={os.path.exists(f)}")427428    with runner.isolated_filesystem():429        result = runner.invoke(exists, ["-f", "xxx"])430        assert "exists=False" in result.output431432        result = runner.invoke(exists, ["-f", "."])433        assert "exists=True" in result.output434435436def test_choice_option(runner):437    @click.command()438    @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))439    def cli(method):440        click.echo(method)441442    result = runner.invoke(cli, ["--method=foo"])443    assert not result.exception444    assert result.output == "foo\n"445446    result = runner.invoke(cli, ["--method=meh"])447    assert result.exit_code == 2448    assert (449        "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."450        in result.output451    )452453    result = runner.invoke(cli, ["--help"])454    assert "--method [foo|bar|baz]" in result.output455456457def test_choice_argument(runner):458    @click.command()459    @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))460    def cli(method):461        click.echo(method)462463    result = runner.invoke(cli, ["foo"])464    assert not result.exception465    assert result.output == "foo\n"466467    result = runner.invoke(cli, ["meh"])468    assert result.exit_code == 2469    assert (470        "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"471        " 'bar', 'baz'." in result.output472    )473474    result = runner.invoke(cli, ["--help"])475    assert "{foo|bar|baz}" in result.output476477478def test_choice_argument_enum(runner):479    class MyEnum(str, enum.Enum):480        FOO = "foo-value"481        BAR = "bar-value"482        BAZ = "baz-value"483484    @click.command()485    @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))486    def cli(method: MyEnum):487        assert isinstance(method, MyEnum)488        click.echo(method)489490    result = runner.invoke(cli, ["foo"])491    assert result.output == "foo-value\n"492    assert not result.exception493494    result = runner.invoke(cli, ["meh"])495    assert result.exit_code == 2496    assert (497        "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"498        " 'bar', 'baz'." in result.output499    )500501    result = runner.invoke(cli, ["--help"])502    assert "{foo|bar|baz}" in result.output503504505def test_choice_argument_custom_type(runner):506    class MyClass:507        def __init__(self, value: str) -> None:508            self.value = value509510        def __str__(self) -> str:511            return self.value512513    @click.command()514    @click.argument(515        "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])516    )517    def cli(method: MyClass):518        assert isinstance(method, MyClass)519        click.echo(method)520521    result = runner.invoke(cli, ["foo"])522    assert not result.exception523    assert result.output == "foo\n"524525    result = runner.invoke(cli, ["meh"])526    assert result.exit_code == 2527    assert (528        "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"529        " 'bar', 'baz'." in result.output530    )531532    result = runner.invoke(cli, ["--help"])533    assert "{foo|bar|baz}" in result.output534535536def test_choice_argument_none(runner):537    @click.command()538    @click.argument(539        "method", type=click.Choice(["not-none", None], case_sensitive=False)540    )541    def cli(method: str | None):542        assert isinstance(method, str) or method is None543        click.echo(repr(method), nl=False)544545    result = runner.invoke(cli, ["not-none"])546    assert not result.exception547    assert result.output == repr("not-none")548549    result = runner.invoke(cli, ["none"])550    assert not result.exception551    assert result.output == repr(None)552553    result = runner.invoke(cli, [])554    assert result.exception555    assert (556        "Error: Missing argument '{not-none|none}'. "557        "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr558    )559560    result = runner.invoke(cli, ["--help"])561    assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")562563564def test_datetime_option_default(runner):565    @click.command()566    @click.option("--start_date", type=click.DateTime())567    def cli(start_date):568        click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))569570    result = runner.invoke(cli, ["--start_date=2015-09-29"])571    assert not result.exception572    assert result.output == "2015-09-29T00:00:00\n"573574    result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])575    assert not result.exception576    assert result.output == "2015-09-29T09:11:22\n"577578    result = runner.invoke(cli, ["--start_date=2015-09"])579    assert result.exit_code == 2580    assert (581        "Invalid value for '--start_date': '2015-09' does not match the formats"582        " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."583    ) in result.output584585    result = runner.invoke(cli, ["--help"])586    assert (587        "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output588    )589590591def test_datetime_option_custom(runner):592    @click.command()593    @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))594    def cli(start_date):595        click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))596597    result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])598    assert not result.exception599    assert result.output == "2010-06-05T00:00:00\n"600601602def test_required_option(runner):603    @click.command()604    @click.option("--foo", required=True)605    def cli(foo):606        click.echo(foo)607608    result = runner.invoke(cli, [])609    assert result.exit_code == 2610    assert "Missing option '--foo'" in result.output611612613def test_evaluation_order(runner):614    called = []615616    def memo(ctx, param, value):617        called.append(value)618        return value619620    @click.command()621    @click.option("--missing", default="missing", is_eager=False, callback=memo)622    @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)623    @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)624    @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)625    @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)626    @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)627    @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)628    def cli(**x):629        pass630631    result = runner.invoke(632        cli,633        [634            "--eager-flag2",635            "--eager-flag1",636            "--normal-flag2",637            "--eager-flag3",638            "--normal-flag3",639            "--normal-flag3",640            "--normal-flag1",641            "--normal-flag1",642        ],643    )644    assert not result.exception645    assert called == [646        "eager2",647        "eager1",648        "eager3",649        "normal2",650        "normal3",651        "normal1",652        "missing",653    ]654655656def test_hidden_option(runner):657    @click.command()658    @click.option("--nope", hidden=True)659    def cli(nope):660        click.echo(nope)661662    result = runner.invoke(cli, ["--help"])663    assert result.exit_code == 0664    assert "--nope" not in result.output665666667def test_hidden_command(runner):668    @click.group()669    def cli():670        pass671672    @cli.command(hidden=True)673    def nope():674        pass675676    result = runner.invoke(cli, ["--help"])677    assert result.exit_code == 0678    assert "nope" not in result.output679680681def test_hidden_group(runner):682    @click.group()683    def cli():684        pass685686    @cli.group(hidden=True)687    def subgroup():688        pass689690    @subgroup.command()691    def nope():692        pass693694    result = runner.invoke(cli, ["--help"])695    assert result.exit_code == 0696    assert "subgroup" not in result.output697    assert "nope" not in result.output698699700def test_summary_line(runner):701    @click.group()702    def cli():703        pass704705    @cli.command()706    def cmd():707        """708        Summary line without period709710        Here is a sentence. And here too.711        """712        pass713714    result = runner.invoke(cli, ["--help"])715    assert "Summary line without period" in result.output716    assert "Here is a sentence." not in result.output717718719def test_help_invalid_default(runner):720    cli = click.Command(721        "cli",722        params=[723            click.Option(724                ["-a"],725                type=click.Path(exists=True),726                default="not found",727                show_default=True,728            ),729        ],730    )731    result = runner.invoke(cli, ["--help"])732    assert result.exit_code == 0733    assert "default: not found" in result.output