test_basic.py
This file
Path
tests/test_basic.py
741 lines · 20.3 KiB · Python
Last changed by
Add cross-reference to tests from `test_defaults.py` (#3223)Rowlando13before adoptionfa7f035
History of this fileTake it
The walk stopped after 200 commits: lines older than 02046e7 point at it.
Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 1–3why, one step back1from __future__ import annotations23import enumupdate test workflow triggerDavid Lordbefore adoption02046e7
lines 4–9why, one step back4import os5from itertools import chain67import pytest89import clickMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 10why, one step back10from click._utils import UNSETupdate test workflow triggerDavid Lordbefore adoption02046e7
lines 11–209why, one step back111213def 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(Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 210–224why, one step back210 ("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 ],update test workflow triggerDavid Lordbefore adoption02046e7
line 225why, one step back225)Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 226why, one step back226def test_boolean_switch(runner, args, default, expect):update test workflow triggerDavid Lordbefore adoption02046e7
lines 227–235why, one step back227 @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 expect234235Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 236–242why, one step back236@pytest.mark.parametrize(237 ("default", "args", "expect"),238 (239 (True, ["--f"], True),240 (True, [], True),241 (False, ["--f"], True),242 (False, [], False),Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 243–246why, one step back243 # Boolean flags have a 3-states logic.244 # See: https://github.com/pallets/click/issues/3024#issue-3285556668245 (None, ["--f"], True),246 (None, [], None),Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 247–248why, one step back247 ),248)update test workflow triggerDavid Lordbefore adoption02046e7
lines 249–278why, one step back249def 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 == expect277278Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 279–318why, one step back279@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 # Special case: if default=True and flag_value is set, the value returned is the306 # flag_value, not the True Python value itself.307 (True, [], "upper"),308 # Non-string defaults are process as strings by the default Parameter's type.309 (False, [], "False"),310 (42, [], "42"),311 (12.3, [], "12.3"),312 ),313)314def test_flag_value_dual_options(runner, default, args, expected):315 """Check how default is processed when options compete for the same variable name.316317 Covers the regression reported in318 https://github.com/pallets/click/issues/3024#issuecomment-3146199461Add cross-reference to tests from `test_defaults.py` (#3223)Rowlando13before adoptionfa7f035
lines 319–324why, one step back319320 .. hint::321 Similar to ``test_options.py::test_default_dual_option_callback``.322323 ``test_defaults.py::test_shared_param_prefers_first_default``324 is a smoke-test complement that exercises both default placements.Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 325–336why, one step back325 """326327 @click.command()328 @click.option("--upper", "case", flag_value="upper", default=default)329 @click.option("--lower", "case", flag_value="lower")330 def cli(case):331 click.echo(repr(case), nl=False)332333 result = runner.invoke(cli, args)334 assert result.output == repr(expected)335336update test workflow triggerDavid Lordbefore adoption02046e7
lines 337–483why, one step back337def test_file_option(runner):338 @click.command()339 @click.option("--file", type=click.File("w"))340 def input(file):341 file.write("Hello World!\n")342343 @click.command()344 @click.option("--file", type=click.File("r"))345 def output(file):346 click.echo(file.read())347348 with runner.isolated_filesystem():349 result_in = runner.invoke(input, ["--file=example.txt"])350 result_out = runner.invoke(output, ["--file=example.txt"])351352 assert not result_in.exception353 assert result_in.output == ""354 assert not result_out.exception355 assert result_out.output == "Hello World!\n\n"356357358def test_file_lazy_mode(runner):359 do_io = False360361 @click.command()362 @click.option("--file", type=click.File("w"))363 def input(file):364 if do_io:365 file.write("Hello World!\n")366367 @click.command()368 @click.option("--file", type=click.File("r"))369 def output(file):370 pass371372 with runner.isolated_filesystem():373 os.mkdir("example.txt")374375 do_io = True376 result_in = runner.invoke(input, ["--file=example.txt"])377 assert result_in.exit_code == 1378379 do_io = False380 result_in = runner.invoke(input, ["--file=example.txt"])381 assert result_in.exit_code == 0382383 result_out = runner.invoke(output, ["--file=example.txt"])384 assert result_out.exception385386 @click.command()387 @click.option("--file", type=click.File("w", lazy=False))388 def input_non_lazy(file):389 file.write("Hello World!\n")390391 with runner.isolated_filesystem():392 os.mkdir("example.txt")393 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])394 assert result_in.exit_code == 2395 assert "Invalid value for '--file': 'example.txt'" in result_in.output396397398def test_path_option(runner):399 @click.command()400 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))401 def write_to_dir(o):402 with open(os.path.join(o, "foo.txt"), "wb") as f:403 f.write(b"meh\n")404405 with runner.isolated_filesystem():406 os.mkdir("test")407408 result = runner.invoke(write_to_dir, ["-O", "test"])409 assert not result.exception410411 with open("test/foo.txt", "rb") as f:412 assert f.read() == b"meh\n"413414 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])415 assert "is a file" in result.output416417 @click.command()418 @click.option("-f", type=click.Path(exists=True))419 def showtype(f):420 click.echo(f"is_file={os.path.isfile(f)}")421 click.echo(f"is_dir={os.path.isdir(f)}")422423 with runner.isolated_filesystem():424 result = runner.invoke(showtype, ["-f", "xxx"])425 assert "does not exist" in result.output426427 result = runner.invoke(showtype, ["-f", "."])428 assert "is_file=False" in result.output429 assert "is_dir=True" in result.output430431 @click.command()432 @click.option("-f", type=click.Path())433 def exists(f):434 click.echo(f"exists={os.path.exists(f)}")435436 with runner.isolated_filesystem():437 result = runner.invoke(exists, ["-f", "xxx"])438 assert "exists=False" in result.output439440 result = runner.invoke(exists, ["-f", "."])441 assert "exists=True" in result.output442443444def test_choice_option(runner):445 @click.command()446 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))447 def cli(method):448 click.echo(method)449450 result = runner.invoke(cli, ["--method=foo"])451 assert not result.exception452 assert result.output == "foo\n"453454 result = runner.invoke(cli, ["--method=meh"])455 assert result.exit_code == 2456 assert (457 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."458 in result.output459 )460461 result = runner.invoke(cli, ["--help"])462 assert "--method [foo|bar|baz]" in result.output463464465def test_choice_argument(runner):466 @click.command()467 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))468 def cli(method):469 click.echo(method)470471 result = runner.invoke(cli, ["foo"])472 assert not result.exception473 assert result.output == "foo\n"474475 result = runner.invoke(cli, ["meh"])476 assert result.exit_code == 2477 assert (478 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"479 " 'bar', 'baz'." in result.output480 )481482 result = runner.invoke(cli, ["--help"])483 assert "{foo|bar|baz}" in result.outputExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 484–550why, one step back484485486def test_choice_argument_enum(runner):487 class MyEnum(str, enum.Enum):488 FOO = "foo-value"489 BAR = "bar-value"490 BAZ = "baz-value"491492 @click.command()493 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))494 def cli(method: MyEnum):495 assert isinstance(method, MyEnum)496 click.echo(method)497498 result = runner.invoke(cli, ["foo"])499 assert result.output == "foo-value\n"500 assert not result.exception501502 result = runner.invoke(cli, ["meh"])503 assert result.exit_code == 2504 assert (505 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"506 " 'bar', 'baz'." in result.output507 )508509 result = runner.invoke(cli, ["--help"])510 assert "{foo|bar|baz}" in result.output511512513def test_choice_argument_custom_type(runner):514 class MyClass:515 def __init__(self, value: str) -> None:516 self.value = value517518 def __str__(self) -> str:519 return self.value520521 @click.command()522 @click.argument(523 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])524 )525 def cli(method: MyClass):526 assert isinstance(method, MyClass)527 click.echo(method)528529 result = runner.invoke(cli, ["foo"])530 assert not result.exception531 assert result.output == "foo\n"532533 result = runner.invoke(cli, ["meh"])534 assert result.exit_code == 2535 assert (536 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"537 " 'bar', 'baz'." in result.output538 )539540 result = runner.invoke(cli, ["--help"])541 assert "{foo|bar|baz}" in result.output542543544def test_choice_argument_none(runner):545 @click.command()546 @click.argument(547 "method", type=click.Choice(["not-none", None], case_sensitive=False)548 )549 def cli(method: str | None):550 assert isinstance(method, str) or method is NoneMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 551why, one step back551 click.echo(repr(method), nl=False)Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 552–554why, one step back552553 result = runner.invoke(cli, ["not-none"])554 assert not result.exceptionMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 555why, one step back555 assert result.output == repr("not-none")Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 556–557why, one step back556557 result = runner.invoke(cli, ["none"])Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 558–561why, one step back558 assert not result.exception559 assert result.output == repr(None)560561 result = runner.invoke(cli, [])Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 562why, one step back562 assert result.exceptionMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 563–569why, one step back563 assert (564 "Error: Missing argument '{not-none|none}'. "565 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr566 )567568 result = runner.invoke(cli, ["--help"])569 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")update test workflow triggerDavid Lordbefore adoption02046e7
lines 570–741why, one step back570571572def test_datetime_option_default(runner):573 @click.command()574 @click.option("--start_date", type=click.DateTime())575 def cli(start_date):576 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))577578 result = runner.invoke(cli, ["--start_date=2015-09-29"])579 assert not result.exception580 assert result.output == "2015-09-29T00:00:00\n"581582 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])583 assert not result.exception584 assert result.output == "2015-09-29T09:11:22\n"585586 result = runner.invoke(cli, ["--start_date=2015-09"])587 assert result.exit_code == 2588 assert (589 "Invalid value for '--start_date': '2015-09' does not match the formats"590 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."591 ) in result.output592593 result = runner.invoke(cli, ["--help"])594 assert (595 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output596 )597598599def test_datetime_option_custom(runner):600 @click.command()601 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))602 def cli(start_date):603 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))604605 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])606 assert not result.exception607 assert result.output == "2010-06-05T00:00:00\n"608609610def test_required_option(runner):611 @click.command()612 @click.option("--foo", required=True)613 def cli(foo):614 click.echo(foo)615616 result = runner.invoke(cli, [])617 assert result.exit_code == 2618 assert "Missing option '--foo'" in result.output619620621def test_evaluation_order(runner):622 called = []623624 def memo(ctx, param, value):625 called.append(value)626 return value627628 @click.command()629 @click.option("--missing", default="missing", is_eager=False, callback=memo)630 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)631 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)632 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)633 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)634 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)635 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)636 def cli(**x):637 pass638639 result = runner.invoke(640 cli,641 [642 "--eager-flag2",643 "--eager-flag1",644 "--normal-flag2",645 "--eager-flag3",646 "--normal-flag3",647 "--normal-flag3",648 "--normal-flag1",649 "--normal-flag1",650 ],651 )652 assert not result.exception653 assert called == [654 "eager2",655 "eager1",656 "eager3",657 "normal2",658 "normal3",659 "normal1",660 "missing",661 ]662663664def test_hidden_option(runner):665 @click.command()666 @click.option("--nope", hidden=True)667 def cli(nope):668 click.echo(nope)669670 result = runner.invoke(cli, ["--help"])671 assert result.exit_code == 0672 assert "--nope" not in result.output673674675def test_hidden_command(runner):676 @click.group()677 def cli():678 pass679680 @cli.command(hidden=True)681 def nope():682 pass683684 result = runner.invoke(cli, ["--help"])685 assert result.exit_code == 0686 assert "nope" not in result.output687688689def test_hidden_group(runner):690 @click.group()691 def cli():692 pass693694 @cli.group(hidden=True)695 def subgroup():696 pass697698 @subgroup.command()699 def nope():700 pass701702 result = runner.invoke(cli, ["--help"])703 assert result.exit_code == 0704 assert "subgroup" not in result.output705 assert "nope" not in result.output706707708def test_summary_line(runner):709 @click.group()710 def cli():711 pass712713 @cli.command()714 def cmd():715 """716 Summary line without period717718 Here is a sentence. And here too.719 """720 pass721722 result = runner.invoke(cli, ["--help"])723 assert "Summary line without period" in result.output724 assert "Here is a sentence." not in result.output725726727def test_help_invalid_default(runner):728 cli = click.Command(729 "cli",730 params=[731 click.Option(732 ["-a"],733 type=click.Path(exists=True),734 default="not found",735 show_default=True,736 ),737 ],738 )739 result = runner.invoke(cli, ["--help"])740 assert result.exit_code == 0741 assert "default: not found" in result.output