test_basic.py
This file
Path
tests/test_basic.py
735 lines · 20.0 KiB · Python
Last changed by
Merge branch 'main' into stableDavid Lordbefore adoption81a482f
History of this fileTake it
The walk stopped after 200 commits: lines older than 7586834 point at it.
Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 1–3why, one step back1from __future__ import annotations23import enumMerge branch '8.1.x'David Lordbefore adoption7586834
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 UNSETMerge branch '8.1.x'David Lordbefore adoption7586834
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 ],Merge branch '8.1.x'David Lordbefore adoption7586834
line 225why, one step back225)Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 226why, one step back226def test_boolean_switch(runner, args, default, expect):Merge branch '8.1.x'David Lordbefore adoption7586834
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)Merge branch '8.1.x'David Lordbefore adoption7586834
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–330why, 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-3146199461319 """320321 @click.command()322 @click.option("--upper", "case", flag_value="upper", default=default)323 @click.option("--lower", "case", flag_value="lower")324 def cli(case):325 click.echo(repr(case), nl=False)326327 result = runner.invoke(cli, args)328 assert result.output == repr(expected)329330Merge branch '8.1.x'David Lordbefore adoption7586834
lines 331–477why, one step back331def test_file_option(runner):332 @click.command()333 @click.option("--file", type=click.File("w"))334 def input(file):335 file.write("Hello World!\n")336337 @click.command()338 @click.option("--file", type=click.File("r"))339 def output(file):340 click.echo(file.read())341342 with runner.isolated_filesystem():343 result_in = runner.invoke(input, ["--file=example.txt"])344 result_out = runner.invoke(output, ["--file=example.txt"])345346 assert not result_in.exception347 assert result_in.output == ""348 assert not result_out.exception349 assert result_out.output == "Hello World!\n\n"350351352def test_file_lazy_mode(runner):353 do_io = False354355 @click.command()356 @click.option("--file", type=click.File("w"))357 def input(file):358 if do_io:359 file.write("Hello World!\n")360361 @click.command()362 @click.option("--file", type=click.File("r"))363 def output(file):364 pass365366 with runner.isolated_filesystem():367 os.mkdir("example.txt")368369 do_io = True370 result_in = runner.invoke(input, ["--file=example.txt"])371 assert result_in.exit_code == 1372373 do_io = False374 result_in = runner.invoke(input, ["--file=example.txt"])375 assert result_in.exit_code == 0376377 result_out = runner.invoke(output, ["--file=example.txt"])378 assert result_out.exception379380 @click.command()381 @click.option("--file", type=click.File("w", lazy=False))382 def input_non_lazy(file):383 file.write("Hello World!\n")384385 with runner.isolated_filesystem():386 os.mkdir("example.txt")387 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])388 assert result_in.exit_code == 2389 assert "Invalid value for '--file': 'example.txt'" in result_in.output390391392def test_path_option(runner):393 @click.command()394 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))395 def write_to_dir(o):396 with open(os.path.join(o, "foo.txt"), "wb") as f:397 f.write(b"meh\n")398399 with runner.isolated_filesystem():400 os.mkdir("test")401402 result = runner.invoke(write_to_dir, ["-O", "test"])403 assert not result.exception404405 with open("test/foo.txt", "rb") as f:406 assert f.read() == b"meh\n"407408 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])409 assert "is a file" in result.output410411 @click.command()412 @click.option("-f", type=click.Path(exists=True))413 def showtype(f):414 click.echo(f"is_file={os.path.isfile(f)}")415 click.echo(f"is_dir={os.path.isdir(f)}")416417 with runner.isolated_filesystem():418 result = runner.invoke(showtype, ["-f", "xxx"])419 assert "does not exist" in result.output420421 result = runner.invoke(showtype, ["-f", "."])422 assert "is_file=False" in result.output423 assert "is_dir=True" in result.output424425 @click.command()426 @click.option("-f", type=click.Path())427 def exists(f):428 click.echo(f"exists={os.path.exists(f)}")429430 with runner.isolated_filesystem():431 result = runner.invoke(exists, ["-f", "xxx"])432 assert "exists=False" in result.output433434 result = runner.invoke(exists, ["-f", "."])435 assert "exists=True" in result.output436437438def test_choice_option(runner):439 @click.command()440 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))441 def cli(method):442 click.echo(method)443444 result = runner.invoke(cli, ["--method=foo"])445 assert not result.exception446 assert result.output == "foo\n"447448 result = runner.invoke(cli, ["--method=meh"])449 assert result.exit_code == 2450 assert (451 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."452 in result.output453 )454455 result = runner.invoke(cli, ["--help"])456 assert "--method [foo|bar|baz]" in result.output457458459def test_choice_argument(runner):460 @click.command()461 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))462 def cli(method):463 click.echo(method)464465 result = runner.invoke(cli, ["foo"])466 assert not result.exception467 assert result.output == "foo\n"468469 result = runner.invoke(cli, ["meh"])470 assert result.exit_code == 2471 assert (472 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"473 " 'bar', 'baz'." in result.output474 )475476 result = runner.invoke(cli, ["--help"])477 assert "{foo|bar|baz}" in result.outputExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 478–544why, one step back478479480def test_choice_argument_enum(runner):481 class MyEnum(str, enum.Enum):482 FOO = "foo-value"483 BAR = "bar-value"484 BAZ = "baz-value"485486 @click.command()487 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))488 def cli(method: MyEnum):489 assert isinstance(method, MyEnum)490 click.echo(method)491492 result = runner.invoke(cli, ["foo"])493 assert result.output == "foo-value\n"494 assert not result.exception495496 result = runner.invoke(cli, ["meh"])497 assert result.exit_code == 2498 assert (499 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"500 " 'bar', 'baz'." in result.output501 )502503 result = runner.invoke(cli, ["--help"])504 assert "{foo|bar|baz}" in result.output505506507def test_choice_argument_custom_type(runner):508 class MyClass:509 def __init__(self, value: str) -> None:510 self.value = value511512 def __str__(self) -> str:513 return self.value514515 @click.command()516 @click.argument(517 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])518 )519 def cli(method: MyClass):520 assert isinstance(method, MyClass)521 click.echo(method)522523 result = runner.invoke(cli, ["foo"])524 assert not result.exception525 assert result.output == "foo\n"526527 result = runner.invoke(cli, ["meh"])528 assert result.exit_code == 2529 assert (530 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"531 " 'bar', 'baz'." in result.output532 )533534 result = runner.invoke(cli, ["--help"])535 assert "{foo|bar|baz}" in result.output536537538def test_choice_argument_none(runner):539 @click.command()540 @click.argument(541 "method", type=click.Choice(["not-none", None], case_sensitive=False)542 )543 def cli(method: str | None):544 assert isinstance(method, str) or method is NoneMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 545why, one step back545 click.echo(repr(method), nl=False)Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 546–548why, one step back546547 result = runner.invoke(cli, ["not-none"])548 assert not result.exceptionMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 549why, one step back549 assert result.output == repr("not-none")Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 550–551why, one step back550551 result = runner.invoke(cli, ["none"])Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 552–555why, one step back552 assert not result.exception553 assert result.output == repr(None)554555 result = runner.invoke(cli, [])Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 556why, one step back556 assert result.exceptionMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 557–563why, one step back557 assert (558 "Error: Missing argument '{not-none|none}'. "559 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr560 )561562 result = runner.invoke(cli, ["--help"])563 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")Merge branch '8.1.x'David Lordbefore adoption7586834
lines 564–735why, one step back564565566def test_datetime_option_default(runner):567 @click.command()568 @click.option("--start_date", type=click.DateTime())569 def cli(start_date):570 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))571572 result = runner.invoke(cli, ["--start_date=2015-09-29"])573 assert not result.exception574 assert result.output == "2015-09-29T00:00:00\n"575576 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])577 assert not result.exception578 assert result.output == "2015-09-29T09:11:22\n"579580 result = runner.invoke(cli, ["--start_date=2015-09"])581 assert result.exit_code == 2582 assert (583 "Invalid value for '--start_date': '2015-09' does not match the formats"584 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."585 ) in result.output586587 result = runner.invoke(cli, ["--help"])588 assert (589 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output590 )591592593def test_datetime_option_custom(runner):594 @click.command()595 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))596 def cli(start_date):597 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))598599 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])600 assert not result.exception601 assert result.output == "2010-06-05T00:00:00\n"602603604def test_required_option(runner):605 @click.command()606 @click.option("--foo", required=True)607 def cli(foo):608 click.echo(foo)609610 result = runner.invoke(cli, [])611 assert result.exit_code == 2612 assert "Missing option '--foo'" in result.output613614615def test_evaluation_order(runner):616 called = []617618 def memo(ctx, param, value):619 called.append(value)620 return value621622 @click.command()623 @click.option("--missing", default="missing", is_eager=False, callback=memo)624 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)625 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)626 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)627 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)628 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)629 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)630 def cli(**x):631 pass632633 result = runner.invoke(634 cli,635 [636 "--eager-flag2",637 "--eager-flag1",638 "--normal-flag2",639 "--eager-flag3",640 "--normal-flag3",641 "--normal-flag3",642 "--normal-flag1",643 "--normal-flag1",644 ],645 )646 assert not result.exception647 assert called == [648 "eager2",649 "eager1",650 "eager3",651 "normal2",652 "normal3",653 "normal1",654 "missing",655 ]656657658def test_hidden_option(runner):659 @click.command()660 @click.option("--nope", hidden=True)661 def cli(nope):662 click.echo(nope)663664 result = runner.invoke(cli, ["--help"])665 assert result.exit_code == 0666 assert "--nope" not in result.output667668669def test_hidden_command(runner):670 @click.group()671 def cli():672 pass673674 @cli.command(hidden=True)675 def nope():676 pass677678 result = runner.invoke(cli, ["--help"])679 assert result.exit_code == 0680 assert "nope" not in result.output681682683def test_hidden_group(runner):684 @click.group()685 def cli():686 pass687688 @cli.group(hidden=True)689 def subgroup():690 pass691692 @subgroup.command()693 def nope():694 pass695696 result = runner.invoke(cli, ["--help"])697 assert result.exit_code == 0698 assert "subgroup" not in result.output699 assert "nope" not in result.output700701702def test_summary_line(runner):703 @click.group()704 def cli():705 pass706707 @cli.command()708 def cmd():709 """710 Summary line without period711712 Here is a sentence. And here too.713 """714 pass715716 result = runner.invoke(cli, ["--help"])717 assert "Summary line without period" in result.output718 assert "Here is a sentence." not in result.output719720721def test_help_invalid_default(runner):722 cli = click.Command(723 "cli",724 params=[725 click.Option(726 ["-a"],727 type=click.Path(exists=True),728 default="not found",729 show_default=True,730 ),731 ],732 )733 result = runner.invoke(cli, ["--help"])734 assert result.exit_code == 0735 assert "default: not found" in result.output