test_basic.py
This file
Path
tests/test_basic.py
575 lines · 15.1 KiB · Python
Last changed by
Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
History of this fileTake it
The walk stopped after 200 commits: lines older than ca1d017 point at it.
Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 1–105why, one step back1import os2from itertools import chain34import pytest56import click789def test_basic_functionality(runner):10 @click.command()11 def cli():12 """Hello World!"""13 click.echo("I EXECUTED")1415 result = runner.invoke(cli, ["--help"])16 assert not result.exception17 assert "Hello World!" in result.output18 assert "Show this message and exit." in result.output19 assert result.exit_code == 020 assert "I EXECUTED" not in result.output2122 result = runner.invoke(cli, [])23 assert not result.exception24 assert "I EXECUTED" in result.output25 assert result.exit_code == 0262728def test_repr():29 @click.command()30 def command():31 pass3233 @click.group()34 def group():35 pass3637 @group.command()38 def subcommand():39 pass4041 assert repr(command) == "<Command command>"42 assert repr(group) == "<Group group>"43 assert repr(subcommand) == "<Command subcommand>"444546def test_return_values():47 @click.command()48 def cli():49 return 425051 with cli.make_context("foo", []) as ctx:52 rv = cli.invoke(ctx)53 assert rv == 42545556def test_basic_group(runner):57 @click.group()58 def cli():59 """This is the root."""60 click.echo("ROOT EXECUTED")6162 @cli.command()63 def subcommand():64 """This is a subcommand."""65 click.echo("SUBCOMMAND EXECUTED")6667 result = runner.invoke(cli, ["--help"])68 assert not result.exception69 assert "COMMAND [ARGS]..." in result.output70 assert "This is the root" in result.output71 assert "This is a subcommand." in result.output72 assert result.exit_code == 073 assert "ROOT EXECUTED" not in result.output7475 result = runner.invoke(cli, ["subcommand"])76 assert not result.exception77 assert result.exit_code == 078 assert "ROOT EXECUTED" in result.output79 assert "SUBCOMMAND EXECUTED" in result.output808182def test_group_commands_dict(runner):83 """A Group can be built with a dict of commands."""8485 @click.command()86 def sub():87 click.echo("sub", nl=False)8889 cli = click.Group(commands={"other": sub})90 result = runner.invoke(cli, ["other"])91 assert result.output == "sub"929394def test_group_from_list(runner):95 """A Group can be built with a list of commands."""9697 @click.command()98 def sub():99 click.echo("sub", nl=False)100101 cli = click.Group(commands=[sub])102 result = runner.invoke(cli, ["sub"])103 assert result.output == "sub"104105Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 106–116why, one step back106@pytest.mark.parametrize(107 ("args", "expect"),108 [109 ([], "S:[no value]"),110 (["--s=42"], "S:[42]"),111 (["--s"], "Error: Option '--s' requires an argument."),112 (["--s="], "S:[]"),113 (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),114 ],115)116def test_string_option(runner, args, expect):Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 117why, one step back117 @click.command()Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 118–120why, one step back118 @click.option("--s", default="no value")119 def cli(s):120 click.echo(f"S:[{s}]")Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 121why, one step back121Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 122–123why, one step back122 result = runner.invoke(cli, args)123 assert expect in result.outputMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 124why, one step back124Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 125–128why, one step back125 if expect.startswith("Error:"):126 assert result.exception is not None127 else:128 assert result.exception is NoneMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 129–130why, one step back129130Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 131–139why, one step back131@pytest.mark.parametrize(132 ("args", "expect"),133 [134 ([], "I:[84]"),135 (["--i=23"], "I:[46]"),136 (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),137 ],138)139def test_int_option(runner, args, expect):Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 140why, one step back140 @click.command()Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 141–143why, one step back141 @click.option("--i", default=42)142 def cli(i):143 click.echo(f"I:[{i * 2}]")Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 144why, one step back144Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 145–146why, one step back145 result = runner.invoke(cli, args)146 assert expect in result.outputMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 147why, one step back147Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 148–151why, one step back148 if expect.startswith("Error:"):149 assert result.exception is not None150 else:151 assert result.exception is NoneMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 152–153why, one step back152153Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 154–165why, one step back154@pytest.mark.parametrize(155 ("args", "expect"),156 [157 ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"),158 (159 ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"],160 "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]",161 ),162 (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."),163 ],164)165def test_uuid_option(runner, args, expect):Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 166–172why, one step back166 @click.command()167 @click.option(168 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID169 )170 def cli(u):171 click.echo(f"U:[{u}]")172Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 173–174why, one step back173 result = runner.invoke(cli, args)174 assert expect in result.outputMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 175why, one step back175Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 176–179why, one step back176 if expect.startswith("Error:"):177 assert result.exception is not None178 else:179 assert result.exception is NoneMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 180–181why, one step back180181Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 182–190why, one step back182@pytest.mark.parametrize(183 ("args", "expect"),184 [185 ([], "F:[42.0]"),186 ("--f=23.5", "F:[23.5]"),187 ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."),188 ],189)190def test_float_option(runner, args, expect):Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 191why, one step back191 @click.command()Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 192–194why, one step back192 @click.option("--f", default=42.0)193 def cli(f):194 click.echo(f"F:[{f}]")Merge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 195why, one step back195Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 196–197why, one step back196 result = runner.invoke(cli, args)197 assert expect in result.outputMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 198why, one step back198Merge pull request #1845 from BALaka-18/organize-testsDavid Lordbefore adoption5828a16
lines 199–202why, one step back199 if expect.startswith("Error:"):200 assert result.exception is not None201 else:202 assert result.exception is NoneMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 203–204why, one step back203204Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 205–213why, one step back205@pytest.mark.parametrize("default", [True, False])206@pytest.mark.parametrize(207 ("args", "expect"), [(["--on"], True), (["--off"], False), ([], None)]208)209def test_boolean_switch(runner, default, args, expect):210 @click.command()211 @click.option("--on/--off", default=default)212 def cli(on):213 return onMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 214why, one step back214Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 215–216why, one step back215 if expect is None:216 expect = defaultMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 217why, one step back217Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 218–219why, one step back218 result = runner.invoke(cli, args, standalone_mode=False)219 assert result.return_value is expectMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 220–221why, one step back220221Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 222–228why, one step back222@pytest.mark.parametrize("default", [True, False])223@pytest.mark.parametrize(("args", "expect"), [(["--f"], True), ([], False)])224def test_boolean_flag(runner, default, args, expect):225 @click.command()226 @click.option("--f", is_flag=True, default=default)227 def cli(f):228 return fMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
line 229why, one step back229Merge pull request #2057 from mawassk/format-testsDavid Lordbefore adoption7796147
lines 230–234why, one step back230 if default:231 expect = not expect232233 result = runner.invoke(cli, args, standalone_mode=False)234 assert result.return_value is expectMerge pull request #1747 from pallets/dependabot/pip/pip-tools-5.5.0dependabot-preview[bot]before adoptionca1d017
lines 235–558why, one step back235236237@pytest.mark.parametrize(238 ("value", "expect"),239 chain(240 ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),241 ((x, "False") for x in ("0", "false", "f", "no", "n", "off")),242 ),243)244def test_boolean_conversion(runner, value, expect):245 @click.command()246 @click.option("--flag", type=bool)247 def cli(flag):248 click.echo(flag, nl=False)249250 result = runner.invoke(cli, ["--flag", value])251 assert result.output == expect252253 result = runner.invoke(cli, ["--flag", value.title()])254 assert result.output == expect255256257def test_file_option(runner):258 @click.command()259 @click.option("--file", type=click.File("w"))260 def input(file):261 file.write("Hello World!\n")262263 @click.command()264 @click.option("--file", type=click.File("r"))265 def output(file):266 click.echo(file.read())267268 with runner.isolated_filesystem():269 result_in = runner.invoke(input, ["--file=example.txt"])270 result_out = runner.invoke(output, ["--file=example.txt"])271272 assert not result_in.exception273 assert result_in.output == ""274 assert not result_out.exception275 assert result_out.output == "Hello World!\n\n"276277278def test_file_lazy_mode(runner):279 do_io = False280281 @click.command()282 @click.option("--file", type=click.File("w"))283 def input(file):284 if do_io:285 file.write("Hello World!\n")286287 @click.command()288 @click.option("--file", type=click.File("r"))289 def output(file):290 pass291292 with runner.isolated_filesystem():293 os.mkdir("example.txt")294295 do_io = True296 result_in = runner.invoke(input, ["--file=example.txt"])297 assert result_in.exit_code == 1298299 do_io = False300 result_in = runner.invoke(input, ["--file=example.txt"])301 assert result_in.exit_code == 0302303 result_out = runner.invoke(output, ["--file=example.txt"])304 assert result_out.exception305306 @click.command()307 @click.option("--file", type=click.File("w", lazy=False))308 def input_non_lazy(file):309 file.write("Hello World!\n")310311 with runner.isolated_filesystem():312 os.mkdir("example.txt")313 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])314 assert result_in.exit_code == 2315 assert "Invalid value for '--file': 'example.txt'" in result_in.output316317318def test_path_option(runner):319 @click.command()320 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))321 def write_to_dir(o):322 with open(os.path.join(o, "foo.txt"), "wb") as f:323 f.write(b"meh\n")324325 with runner.isolated_filesystem():326 os.mkdir("test")327328 result = runner.invoke(write_to_dir, ["-O", "test"])329 assert not result.exception330331 with open("test/foo.txt", "rb") as f:332 assert f.read() == b"meh\n"333334 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])335 assert "is a file" in result.output336337 @click.command()338 @click.option("-f", type=click.Path(exists=True))339 def showtype(f):340 click.echo(f"is_file={os.path.isfile(f)}")341 click.echo(f"is_dir={os.path.isdir(f)}")342343 with runner.isolated_filesystem():344 result = runner.invoke(showtype, ["-f", "xxx"])345 assert "does not exist" in result.output346347 result = runner.invoke(showtype, ["-f", "."])348 assert "is_file=False" in result.output349 assert "is_dir=True" in result.output350351 @click.command()352 @click.option("-f", type=click.Path())353 def exists(f):354 click.echo(f"exists={os.path.exists(f)}")355356 with runner.isolated_filesystem():357 result = runner.invoke(exists, ["-f", "xxx"])358 assert "exists=False" in result.output359360 result = runner.invoke(exists, ["-f", "."])361 assert "exists=True" in result.output362363364def test_choice_option(runner):365 @click.command()366 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))367 def cli(method):368 click.echo(method)369370 result = runner.invoke(cli, ["--method=foo"])371 assert not result.exception372 assert result.output == "foo\n"373374 result = runner.invoke(cli, ["--method=meh"])375 assert result.exit_code == 2376 assert (377 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."378 in result.output379 )380381 result = runner.invoke(cli, ["--help"])382 assert "--method [foo|bar|baz]" in result.output383384385def test_choice_argument(runner):386 @click.command()387 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))388 def cli(method):389 click.echo(method)390391 result = runner.invoke(cli, ["foo"])392 assert not result.exception393 assert result.output == "foo\n"394395 result = runner.invoke(cli, ["meh"])396 assert result.exit_code == 2397 assert (398 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"399 " 'bar', 'baz'." in result.output400 )401402 result = runner.invoke(cli, ["--help"])403 assert "{foo|bar|baz}" in result.output404405406def test_datetime_option_default(runner):407 @click.command()408 @click.option("--start_date", type=click.DateTime())409 def cli(start_date):410 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))411412 result = runner.invoke(cli, ["--start_date=2015-09-29"])413 assert not result.exception414 assert result.output == "2015-09-29T00:00:00\n"415416 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])417 assert not result.exception418 assert result.output == "2015-09-29T09:11:22\n"419420 result = runner.invoke(cli, ["--start_date=2015-09"])421 assert result.exit_code == 2422 assert (423 "Invalid value for '--start_date': '2015-09' does not match the formats"424 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."425 ) in result.output426427 result = runner.invoke(cli, ["--help"])428 assert (429 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output430 )431432433def test_datetime_option_custom(runner):434 @click.command()435 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))436 def cli(start_date):437 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))438439 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])440 assert not result.exception441 assert result.output == "2010-06-05T00:00:00\n"442443444def test_required_option(runner):445 @click.command()446 @click.option("--foo", required=True)447 def cli(foo):448 click.echo(foo)449450 result = runner.invoke(cli, [])451 assert result.exit_code == 2452 assert "Missing option '--foo'" in result.output453454455def test_evaluation_order(runner):456 called = []457458 def memo(ctx, param, value):459 called.append(value)460 return value461462 @click.command()463 @click.option("--missing", default="missing", is_eager=False, callback=memo)464 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)465 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)466 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)467 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)468 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)469 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)470 def cli(**x):471 pass472473 result = runner.invoke(474 cli,475 [476 "--eager-flag2",477 "--eager-flag1",478 "--normal-flag2",479 "--eager-flag3",480 "--normal-flag3",481 "--normal-flag3",482 "--normal-flag1",483 "--normal-flag1",484 ],485 )486 assert not result.exception487 assert called == [488 "eager2",489 "eager1",490 "eager3",491 "normal2",492 "normal3",493 "normal1",494 "missing",495 ]496497498def test_hidden_option(runner):499 @click.command()500 @click.option("--nope", hidden=True)501 def cli(nope):502 click.echo(nope)503504 result = runner.invoke(cli, ["--help"])505 assert result.exit_code == 0506 assert "--nope" not in result.output507508509def test_hidden_command(runner):510 @click.group()511 def cli():512 pass513514 @cli.command(hidden=True)515 def nope():516 pass517518 result = runner.invoke(cli, ["--help"])519 assert result.exit_code == 0520 assert "nope" not in result.output521522523def test_hidden_group(runner):524 @click.group()525 def cli():526 pass527528 @cli.group(hidden=True)529 def subgroup():530 pass531532 @subgroup.command()533 def nope():534 pass535536 result = runner.invoke(cli, ["--help"])537 assert result.exit_code == 0538 assert "subgroup" not in result.output539 assert "nope" not in result.output540541542def test_summary_line(runner):543 @click.group()544 def cli():545 pass546547 @cli.command()548 def cmd():549 """550 Summary line without period551552 Here is a sentence. And here too.553 """554 pass555556 result = runner.invoke(cli, ["--help"])557 assert "Summary line without period" in result.output558 assert "Here is a sentence." not in result.outputMerge branch '8.0.x'David Lordbefore adoption29df879
lines 559–575why, one step back559560561def test_help_invalid_default(runner):562 cli = click.Command(563 "cli",564 params=[565 click.Option(566 ["-a"],567 type=click.Path(exists=True),568 default="not found",569 show_default=True,570 ),571 ],572 )573 result = runner.invoke(cli, ["--help"])574 assert result.exit_code == 0575 assert "default: not found" in result.output