test_basic.py
This file
Path
tests/test_basic.py
704 lines · 18.7 KiB · Python
Last changed by
Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
History of this fileTake it
The walk stopped after 200 commits: lines older than 5828a16 point at it.
Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 1–3why, one step back1from __future__ import annotations23import enumMerge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 4–9why, one step back4import os5from itertools import chain67import pytest89import clickDifferentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
line 10why, one step back10from click._utils import UNSETMerge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 11–208why, 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 None207208Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
line 209why, one step back209@pytest.mark.parametrize(Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
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 pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
line 225why, one step back225)Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
line 226why, one step back226def test_boolean_switch(runner, args, default, expect):Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 227–230why, one step back227 @click.command()228 @click.option("--on/--off", default=default)229 def cli(on):230 return onMerge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
line 231why, one step back231Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 232–233why, one step back232 result = runner.invoke(cli, args, standalone_mode=False)233 assert result.return_value is expectMerge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 234–235why, one step back234235Fix 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),Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
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 pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 249–256why, 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 expectMerge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 257–278why, one step back257258259@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 == expect277278Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
lines 279–299why, one step back279@pytest.mark.parametrize(280 ("default", "args", "expect"),281 (282 # See: https://github.com/pallets/click/issues/3024#issuecomment-3146199461283 (True, ["--upper"], "upper"),284 (True, ["--lower"], "lower"),285 (True, [], "True"),286 ("upper", [], "upper"),287 ),288)289def test_flag_value(runner, default, args, expect):290 @click.command()291 @click.option("--upper", "transformation", flag_value="upper", default=default)292 @click.option("--lower", "transformation", flag_value="lower")293 def cli(transformation):294 click.echo(repr(transformation), nl=False)295296 result = runner.invoke(cli, args)297 assert result.output == repr(expect)298299Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 300–446why, one step back300def test_file_option(runner):301 @click.command()302 @click.option("--file", type=click.File("w"))303 def input(file):304 file.write("Hello World!\n")305306 @click.command()307 @click.option("--file", type=click.File("r"))308 def output(file):309 click.echo(file.read())310311 with runner.isolated_filesystem():312 result_in = runner.invoke(input, ["--file=example.txt"])313 result_out = runner.invoke(output, ["--file=example.txt"])314315 assert not result_in.exception316 assert result_in.output == ""317 assert not result_out.exception318 assert result_out.output == "Hello World!\n\n"319320321def test_file_lazy_mode(runner):322 do_io = False323324 @click.command()325 @click.option("--file", type=click.File("w"))326 def input(file):327 if do_io:328 file.write("Hello World!\n")329330 @click.command()331 @click.option("--file", type=click.File("r"))332 def output(file):333 pass334335 with runner.isolated_filesystem():336 os.mkdir("example.txt")337338 do_io = True339 result_in = runner.invoke(input, ["--file=example.txt"])340 assert result_in.exit_code == 1341342 do_io = False343 result_in = runner.invoke(input, ["--file=example.txt"])344 assert result_in.exit_code == 0345346 result_out = runner.invoke(output, ["--file=example.txt"])347 assert result_out.exception348349 @click.command()350 @click.option("--file", type=click.File("w", lazy=False))351 def input_non_lazy(file):352 file.write("Hello World!\n")353354 with runner.isolated_filesystem():355 os.mkdir("example.txt")356 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])357 assert result_in.exit_code == 2358 assert "Invalid value for '--file': 'example.txt'" in result_in.output359360361def test_path_option(runner):362 @click.command()363 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))364 def write_to_dir(o):365 with open(os.path.join(o, "foo.txt"), "wb") as f:366 f.write(b"meh\n")367368 with runner.isolated_filesystem():369 os.mkdir("test")370371 result = runner.invoke(write_to_dir, ["-O", "test"])372 assert not result.exception373374 with open("test/foo.txt", "rb") as f:375 assert f.read() == b"meh\n"376377 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])378 assert "is a file" in result.output379380 @click.command()381 @click.option("-f", type=click.Path(exists=True))382 def showtype(f):383 click.echo(f"is_file={os.path.isfile(f)}")384 click.echo(f"is_dir={os.path.isdir(f)}")385386 with runner.isolated_filesystem():387 result = runner.invoke(showtype, ["-f", "xxx"])388 assert "does not exist" in result.output389390 result = runner.invoke(showtype, ["-f", "."])391 assert "is_file=False" in result.output392 assert "is_dir=True" in result.output393394 @click.command()395 @click.option("-f", type=click.Path())396 def exists(f):397 click.echo(f"exists={os.path.exists(f)}")398399 with runner.isolated_filesystem():400 result = runner.invoke(exists, ["-f", "xxx"])401 assert "exists=False" in result.output402403 result = runner.invoke(exists, ["-f", "."])404 assert "exists=True" in result.output405406407def test_choice_option(runner):408 @click.command()409 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))410 def cli(method):411 click.echo(method)412413 result = runner.invoke(cli, ["--method=foo"])414 assert not result.exception415 assert result.output == "foo\n"416417 result = runner.invoke(cli, ["--method=meh"])418 assert result.exit_code == 2419 assert (420 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."421 in result.output422 )423424 result = runner.invoke(cli, ["--help"])425 assert "--method [foo|bar|baz]" in result.output426427428def test_choice_argument(runner):429 @click.command()430 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))431 def cli(method):432 click.echo(method)433434 result = runner.invoke(cli, ["foo"])435 assert not result.exception436 assert result.output == "foo\n"437438 result = runner.invoke(cli, ["meh"])439 assert result.exit_code == 2440 assert (441 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"442 " 'bar', 'baz'." in result.output443 )444445 result = runner.invoke(cli, ["--help"])446 assert "{foo|bar|baz}" in result.outputExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 447–513why, one step back447448449def test_choice_argument_enum(runner):450 class MyEnum(str, enum.Enum):451 FOO = "foo-value"452 BAR = "bar-value"453 BAZ = "baz-value"454455 @click.command()456 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))457 def cli(method: MyEnum):458 assert isinstance(method, MyEnum)459 click.echo(method)460461 result = runner.invoke(cli, ["foo"])462 assert result.output == "foo-value\n"463 assert not result.exception464465 result = runner.invoke(cli, ["meh"])466 assert result.exit_code == 2467 assert (468 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"469 " 'bar', 'baz'." in result.output470 )471472 result = runner.invoke(cli, ["--help"])473 assert "{foo|bar|baz}" in result.output474475476def test_choice_argument_custom_type(runner):477 class MyClass:478 def __init__(self, value: str) -> None:479 self.value = value480481 def __str__(self) -> str:482 return self.value483484 @click.command()485 @click.argument(486 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])487 )488 def cli(method: MyClass):489 assert isinstance(method, MyClass)490 click.echo(method)491492 result = runner.invoke(cli, ["foo"])493 assert not result.exception494 assert result.output == "foo\n"495496 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_none(runner):508 @click.command()509 @click.argument(510 "method", type=click.Choice(["not-none", None], case_sensitive=False)511 )512 def cli(method: str | None):513 assert isinstance(method, str) or method is NoneDifferentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
line 514why, one step back514 click.echo(repr(method), nl=False)Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 515–517why, one step back515516 result = runner.invoke(cli, ["not-none"])517 assert not result.exceptionDifferentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
line 518why, one step back518 assert result.output == repr("not-none")Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 519–520why, one step back519520 result = runner.invoke(cli, ["none"])Differentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
lines 521–524why, one step back521 assert not result.exception522 assert result.output == repr(None)523524 result = runner.invoke(cli, [])Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 525why, one step back525 assert result.exceptionDifferentiate absence of value and value of absence for `default` and `flag_value`Kevin Deldyckebefore adoptionb64ea07
lines 526–532why, one step back526 assert (527 "Error: Missing argument '{not-none|none}'. "528 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr529 )530531 result = runner.invoke(cli, ["--help"])532 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 533–704why, one step back533534535def test_datetime_option_default(runner):536 @click.command()537 @click.option("--start_date", type=click.DateTime())538 def cli(start_date):539 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))540541 result = runner.invoke(cli, ["--start_date=2015-09-29"])542 assert not result.exception543 assert result.output == "2015-09-29T00:00:00\n"544545 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])546 assert not result.exception547 assert result.output == "2015-09-29T09:11:22\n"548549 result = runner.invoke(cli, ["--start_date=2015-09"])550 assert result.exit_code == 2551 assert (552 "Invalid value for '--start_date': '2015-09' does not match the formats"553 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."554 ) in result.output555556 result = runner.invoke(cli, ["--help"])557 assert (558 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output559 )560561562def test_datetime_option_custom(runner):563 @click.command()564 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))565 def cli(start_date):566 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))567568 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])569 assert not result.exception570 assert result.output == "2010-06-05T00:00:00\n"571572573def test_required_option(runner):574 @click.command()575 @click.option("--foo", required=True)576 def cli(foo):577 click.echo(foo)578579 result = runner.invoke(cli, [])580 assert result.exit_code == 2581 assert "Missing option '--foo'" in result.output582583584def test_evaluation_order(runner):585 called = []586587 def memo(ctx, param, value):588 called.append(value)589 return value590591 @click.command()592 @click.option("--missing", default="missing", is_eager=False, callback=memo)593 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)594 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)595 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)596 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)597 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)598 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)599 def cli(**x):600 pass601602 result = runner.invoke(603 cli,604 [605 "--eager-flag2",606 "--eager-flag1",607 "--normal-flag2",608 "--eager-flag3",609 "--normal-flag3",610 "--normal-flag3",611 "--normal-flag1",612 "--normal-flag1",613 ],614 )615 assert not result.exception616 assert called == [617 "eager2",618 "eager1",619 "eager3",620 "normal2",621 "normal3",622 "normal1",623 "missing",624 ]625626627def test_hidden_option(runner):628 @click.command()629 @click.option("--nope", hidden=True)630 def cli(nope):631 click.echo(nope)632633 result = runner.invoke(cli, ["--help"])634 assert result.exit_code == 0635 assert "--nope" not in result.output636637638def test_hidden_command(runner):639 @click.group()640 def cli():641 pass642643 @cli.command(hidden=True)644 def nope():645 pass646647 result = runner.invoke(cli, ["--help"])648 assert result.exit_code == 0649 assert "nope" not in result.output650651652def test_hidden_group(runner):653 @click.group()654 def cli():655 pass656657 @cli.group(hidden=True)658 def subgroup():659 pass660661 @subgroup.command()662 def nope():663 pass664665 result = runner.invoke(cli, ["--help"])666 assert result.exit_code == 0667 assert "subgroup" not in result.output668 assert "nope" not in result.output669670671def test_summary_line(runner):672 @click.group()673 def cli():674 pass675676 @cli.command()677 def cmd():678 """679 Summary line without period680681 Here is a sentence. And here too.682 """683 pass684685 result = runner.invoke(cli, ["--help"])686 assert "Summary line without period" in result.output687 assert "Here is a sentence." not in result.output688689690def test_help_invalid_default(runner):691 cli = click.Command(692 "cli",693 params=[694 click.Option(695 ["-a"],696 type=click.Path(exists=True),697 default="not found",698 show_default=True,699 ),700 ],701 )702 result = runner.invoke(cli, ["--help"])703 assert result.exit_code == 0704 assert "default: not found" in result.output