test_utils.py
This file
Path
tests/test_utils.py
507 lines · 15.8 KiB · Python
Last changed by
use ruff lint and format (#2658)David Lordbefore adoption1a3baf7
History of this fileTake it
The walk stopped after 200 commits: lines older than 1cd7593 point at it.
Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 1–45why, one step back1import os2import pathlib3import stat4import sys5from io import StringIO67import pytest89import click._termui_impl10import click.utils11from click._compat import WIN121314def test_echo(runner):15 with runner.isolation() as outstreams:16 click.echo("\N{SNOWMAN}")17 click.echo(b"\x44\x44")18 click.echo(42, nl=False)19 click.echo(b"a", nl=False)20 click.echo("\x1b[31mx\x1b[39m", nl=False)21 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")22 assert bytes == b"\xe2\x98\x83\nDD\n42ax"2324 # if wrapped, we expect bytes to survive.25 @click.command()26 def cli():27 click.echo(b"\xf6")2829 result = runner.invoke(cli, [])30 assert result.stdout_bytes == b"\xf6\n"3132 # Ensure we do not strip for bytes.33 with runner.isolation() as outstreams:34 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)35 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"363738def test_echo_custom_file():39 import io4041 f = io.StringIO()42 click.echo("hello", file=f)43 assert f.getvalue() == "hello\n"4445Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 46–54why, one step back46def test_echo_no_streams(monkeypatch, runner):47 """echo should not fail when stdout and stderr are None with pythonw on Windows."""48 with runner.isolation():49 sys.stdout = None50 sys.stderr = None51 click.echo("test")52 click.echo("test", err=True)5354Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 55–77why, one step back55@pytest.mark.parametrize(56 ("styles", "ref"),57 [58 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),59 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),60 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),61 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),62 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),63 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),64 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),65 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),66 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),67 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),68 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),69 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),70 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),71 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),72 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),73 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),74 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),75 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),76 ({"bold": True}, "\x1b[1mx y\x1b[0m"),77 ({"dim": True}, "\x1b[2mx y\x1b[0m"),Merge pull request #1822 from rbanffy/overline-italicDavid Lordbefore adoptionc0f9c06
line 78why, one step back78 ({"underline": True}, "\x1b[4mx y\x1b[0m"),Merge branch '8.0.x'David Lordbefore adoption655918a
lines 79–80why, one step back79 ({"overline": True}, "\x1b[53mx y\x1b[0m"),80 ({"italic": True}, "\x1b[3mx y\x1b[0m"),Merge pull request #1822 from rbanffy/overline-italicDavid Lordbefore adoptionc0f9c06
lines 81–83why, one step back81 ({"blink": True}, "\x1b[5mx y\x1b[0m"),82 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),83 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),Merge branch '8.0.x'David Lordbefore adoption655918a
lines 84–91why, one step back84 ({"bold": False}, "\x1b[22mx y\x1b[0m"),85 ({"dim": False}, "\x1b[22mx y\x1b[0m"),86 ({"underline": False}, "\x1b[24mx y\x1b[0m"),87 ({"overline": False}, "\x1b[55mx y\x1b[0m"),88 ({"italic": False}, "\x1b[23mx y\x1b[0m"),89 ({"blink": False}, "\x1b[25mx y\x1b[0m"),90 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),91 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),Merge pull request #1822 from rbanffy/overline-italicDavid Lordbefore adoptionc0f9c06
line 92why, one step back92 ({"fg": "black", "reset": False}, "\x1b[30mx y"),Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 93–109why, one step back93 ],94)95def test_styling(styles, ref):96 assert click.style("x y", **styles) == ref97 assert click.unstyle(ref) == "x y"9899100@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])101def test_unstyle_other_ansi(text, expect):102 assert click.unstyle(text) == expect103104105def test_filename_formatting():106 assert click.format_filename(b"foo.txt") == "foo.txt"107 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"108 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"109 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 110why, one step back110 assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 111–170why, one step back111112113def test_prompts(runner):114 @click.command()115 def test():116 if click.confirm("Foo"):117 click.echo("yes!")118 else:119 click.echo("no :(")120121 result = runner.invoke(test, input="y\n")122 assert not result.exception123 assert result.output == "Foo [y/N]: y\nyes!\n"124125 result = runner.invoke(test, input="\n")126 assert not result.exception127 assert result.output == "Foo [y/N]: \nno :(\n"128129 result = runner.invoke(test, input="n\n")130 assert not result.exception131 assert result.output == "Foo [y/N]: n\nno :(\n"132133 @click.command()134 def test_no():135 if click.confirm("Foo", default=True):136 click.echo("yes!")137 else:138 click.echo("no :(")139140 result = runner.invoke(test_no, input="y\n")141 assert not result.exception142 assert result.output == "Foo [Y/n]: y\nyes!\n"143144 result = runner.invoke(test_no, input="\n")145 assert not result.exception146 assert result.output == "Foo [Y/n]: \nyes!\n"147148 result = runner.invoke(test_no, input="n\n")149 assert not result.exception150 assert result.output == "Foo [Y/n]: n\nno :(\n"151152153def test_confirm_repeat(runner):154 cli = click.Command(155 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]156 )157 result = runner.invoke(cli, input="\ny\n")158 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"159160161@pytest.mark.skipif(WIN, reason="Different behavior on windows.")162def test_prompts_abort(monkeypatch, capsys):163 def f(_):164 raise KeyboardInterrupt()165166 monkeypatch.setattr("click.termui.hidden_prompt_func", f)167168 try:169 click.prompt("Password", hide_input=True)170 except click.Abort:Merge pull request #1836 from MLH-Fellowship/fix-promptDavid Lordbefore adoption68b3d4f
line 171why, one step back171 click.echo("interrupted")Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 172–173why, one step back172173 out, err = capsys.readouterr()Merge pull request #1836 from MLH-Fellowship/fix-promptDavid Lordbefore adoption68b3d4f
line 174why, one step back174 assert out == "Password:\ninterrupted\n"Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 175–243why, one step back175176177def _test_gen_func():178 yield "a"179 yield "b"180 yield "c"181 yield "abc"182183184@pytest.mark.skipif(WIN, reason="Different behavior on windows.")185@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])186@pytest.mark.parametrize(187 "test",188 [189 # We need lambda here, because pytest will190 # reuse the parameters, and then the generators191 # are already used and will not yield anymore192 ("just text\n", lambda: "just text"),193 ("iterable\n", lambda: ["itera", "ble"]),194 ("abcabc\n", lambda: _test_gen_func),195 ("abcabc\n", lambda: _test_gen_func()),196 ("012345\n", lambda: (c for c in range(6))),197 ],198)199def test_echo_via_pager(monkeypatch, capfd, cat, test):200 monkeypatch.setitem(os.environ, "PAGER", cat)201 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)202203 expected_output = test[0]204 test_input = test[1]()205206 click.echo_via_pager(test_input)207208 out, err = capfd.readouterr()209 assert out == expected_output210211212@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")213def test_echo_color_flag(monkeypatch, capfd):214 isatty = True215 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)216217 text = "foo"218 styled_text = click.style(text, fg="red")219 assert styled_text == "\x1b[31mfoo\x1b[0m"220221 click.echo(styled_text, color=False)222 out, err = capfd.readouterr()223 assert out == f"{text}\n"224225 click.echo(styled_text, color=True)226 out, err = capfd.readouterr()227 assert out == f"{styled_text}\n"228229 isatty = True230 click.echo(styled_text)231 out, err = capfd.readouterr()232 assert out == f"{styled_text}\n"233234 isatty = False235 click.echo(styled_text)236 out, err = capfd.readouterr()237 assert out == f"{text}\n"238239240def test_prompt_cast_default(capfd, monkeypatch):241 monkeypatch.setattr(sys, "stdin", StringIO("\n"))242 value = click.prompt("value", default="100", type=int)243 capfd.readouterr()use ruff lint and format (#2658)David Lordbefore adoption1a3baf7
line 244why, one step back244 assert isinstance(value, int)Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 245–271why, one step back245246247@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")248def test_echo_writing_to_standard_error(capfd, monkeypatch):249 def emulate_input(text):250 """Emulate keyboard input."""251 monkeypatch.setattr(sys, "stdin", StringIO(text))252253 click.echo("Echo to standard output")254 out, err = capfd.readouterr()255 assert out == "Echo to standard output\n"256 assert err == ""257258 click.echo("Echo to standard error", err=True)259 out, err = capfd.readouterr()260 assert out == ""261 assert err == "Echo to standard error\n"262263 emulate_input("asdlkj\n")264 click.prompt("Prompt to stdin")265 out, err = capfd.readouterr()266 assert out == "Prompt to stdin: "267 assert err == ""268269 emulate_input("asdlkj\n")270 click.prompt("Prompt to stderr", err=True)271 out, err = capfd.readouterr()Merge pull request #1836 from MLH-Fellowship/fix-promptDavid Lordbefore adoption68b3d4f
lines 272–273why, one step back272 assert out == " "273 assert err == "Prompt to stderr:"Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 274–283why, one step back274275 emulate_input("y\n")276 click.confirm("Prompt to stdin")277 out, err = capfd.readouterr()278 assert out == "Prompt to stdin [y/N]: "279 assert err == ""280281 emulate_input("y\n")282 click.confirm("Prompt to stderr", err=True)283 out, err = capfd.readouterr()Merge branch '8.0.x'David Lordbefore adoption65eceb0
lines 284–285why, one step back284 assert out == " "285 assert err == "Prompt to stderr [y/N]:"Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 286–328why, one step back286287 monkeypatch.setattr(click.termui, "isatty", lambda x: True)288 monkeypatch.setattr(click.termui, "getchar", lambda: " ")289290 click.pause("Pause to stdout")291 out, err = capfd.readouterr()292 assert out == "Pause to stdout\n"293 assert err == ""294295 click.pause("Pause to stderr", err=True)296 out, err = capfd.readouterr()297 assert out == ""298 assert err == "Pause to stderr\n"299300301def test_echo_with_capsys(capsys):302 click.echo("Capture me.")303 out, err = capsys.readouterr()304 assert out == "Capture me.\n"305306307def test_open_file(runner):308 @click.command()309 @click.argument("filename")310 def cli(filename):311 with click.open_file(filename) as f:312 click.echo(f.read())313314 click.echo("meep")315316 with runner.isolated_filesystem():317 with open("hello.txt", "w") as f:318 f.write("Cool stuff")319320 result = runner.invoke(cli, ["hello.txt"])321 assert result.exception is None322 assert result.output == "Cool stuff\nmeep\n"323324 result = runner.invoke(cli, ["-"], input="foobar")325 assert result.exception is None326 assert result.output == "foobar\nmeep\n"327328Merge branch '8.0.x'David Lordbefore adoption0c85d80
lines 329–344why, one step back329def test_open_file_pathlib_dash(runner):330 @click.command()331 @click.argument(332 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)333 )334 def cli(filename):335 click.echo(str(type(filename)))336337 with click.open_file(filename) as f:338 click.echo(f.read())339340 result = runner.invoke(cli, ["-"], input="value")341 assert result.exception is None342 assert result.output == "pathlib.Path\nvalue\n"343344Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 345–452why, one step back345def test_open_file_ignore_errors_stdin(runner):346 @click.command()347 @click.argument("filename")348 def cli(filename):349 with click.open_file(filename, errors="ignore") as f:350 click.echo(f.read())351352 result = runner.invoke(cli, ["-"], input=os.urandom(16))353 assert result.exception is None354355356def test_open_file_respects_ignore(runner):357 with runner.isolated_filesystem():358 with open("test.txt", "w") as f:359 f.write("Hello world!")360361 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:362 assert f.errors == "ignore"363364365def test_open_file_ignore_invalid_utf8(runner):366 with runner.isolated_filesystem():367 with open("test.txt", "wb") as f:368 f.write(b"\xe2\x28\xa1")369370 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:371 f.read()372373374def test_open_file_ignore_no_encoding(runner):375 with runner.isolated_filesystem():376 with open("test.bin", "wb") as f:377 f.write(os.urandom(16))378379 with click.open_file("test.bin", errors="ignore") as f:380 f.read()381382383@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")384@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])385def test_open_file_atomic_permissions_existing_file(runner, permissions):386 with runner.isolated_filesystem():387 with open("existing.txt", "w") as f:388 f.write("content")389 os.chmod("existing.txt", permissions)390391 @click.command()392 @click.argument("filename")393 def cli(filename):394 click.open_file(filename, "w", atomic=True).close()395396 result = runner.invoke(cli, ["existing.txt"])397 assert result.exception is None398 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions399400401@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")402def test_open_file_atomic_permissions_new_file(runner):403 with runner.isolated_filesystem():404405 @click.command()406 @click.argument("filename")407 def cli(filename):408 click.open_file(filename, "w", atomic=True).close()409410 # Create a test file to get the expected permissions for new files411 # according to the current umask.412 with open("test.txt", "w"):413 pass414 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)415416 result = runner.invoke(cli, ["new.txt"])417 assert result.exception is None418 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions419420421def test_iter_keepopenfile(tmpdir):422 expected = list(map(str, range(10)))423 p = tmpdir.mkdir("testdir").join("testfile")424 p.write("\n".join(expected))425 with p.open() as f:426 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):427 assert e_line == a_line.strip()428429430def test_iter_lazyfile(tmpdir):431 expected = list(map(str, range(10)))432 p = tmpdir.mkdir("testdir").join("testfile")433 p.write("\n".join(expected))434 with p.open() as f:435 with click.utils.LazyFile(f.name) as lf:436 for e_line, a_line in zip(expected, lf):437 assert e_line == a_line.strip()438439440class MockMain:441 __slots__ = "__package__"442443 def __init__(self, package_name):444 self.__package__ = package_name445446447@pytest.mark.parametrize(448 ("path", "main", "expected"),449 [450 ("example.py", None, "example.py"),451 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),452 ("example", None, "example"),Merge pull request #2215 from adriangb/fix-anyioDavid Lordbefore adoptionbf9da48
lines 453–454why, one step back453 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),454 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 455why, one step back455 (str(pathlib.Path("./example")), "", "example"),Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 456–458why, one step back456 ],457)458def test_detect_program_name(path, main, expected):Merge pull request #2215 from adriangb/fix-anyioDavid Lordbefore adoptionbf9da48
line 459why, one step back459 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expectedMerge pull request #1830 from pallets/windows-globDavid Lordbefore adoption9330dba
lines 460–466why, one step back460461462def test_expand_args(monkeypatch):463 user = os.path.expanduser("~")464 assert user in click.utils._expand_args(["~"])465 monkeypatch.setenv("CLICK_TEST", "hello")466 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])switch to pyproject.toml (#2438)David Lordbefore adoption347529d
line 467why, one step back467 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])Merge pull request #1830 from pallets/windows-globDavid Lordbefore adoption9330dba
lines 468–469why, one step back468 assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])469 assert "*.not-found" in click.utils._expand_args(["*.not-found"])Merge pull request #2201 from pallets/windows-globDavid Lordbefore adoption4a88877
lines 470–471why, one step back470 # a bad glob pattern, such as a pytest identifier, should return itself471 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"Merge pull request #1850 from janLuke/fix/make-default-short-helpDavid Lordbefore adoption82a83fd
lines 472–507why, one step back472473474@pytest.mark.parametrize(475 ("value", "max_length", "expect"),476 [477 pytest.param("", 10, "", id="empty"),478 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),479 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),480 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),481 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),482 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),483 pytest.param(484 "token in ~/.netrc ciao ciao",485 20,486 "token in ~/.netrc...",487 id="ignore dot in word",488 ),489 ],490)491@pytest.mark.parametrize(492 "alter",493 [494 pytest.param(None, id=""),495 pytest.param(496 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"497 ),498 ],499)500def test_make_default_short_help(value, max_length, alter, expect):501 assert len(expect) <= max_length502503 if alter:504 value = alter(value)505506 out = click.utils.make_default_short_help(value, max_length)507 assert out == expect