test_utils.py
This file
Path
tests/test_utils.py
723 lines · 22.4 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
1import os2import pathlib3import stat4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import StringIO12from pathlib import Path13from tempfile import tempdir14from unittest.mock import patch1516import pytest1718import click._termui_impl19import click.utils20from click._compat import WIN21from click._utils import UNSET222324def test_unset_sentinel():25 value = UNSET2627 assert value28 assert value is UNSET29 assert value == UNSET30 assert repr(value) == "Sentinel.UNSET"31 assert str(value) == "Sentinel.UNSET"32 assert bool(value) is True33 assert value is not True3435 # Try all native Python values that can be falsy or truthy.36 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing37 real_values = (38 None,39 True,40 False,41 0,42 1,43 0.0,44 1.0,45 0j,46 1j,47 Decimal(0),48 Decimal(1),49 Fraction(0, 1),50 Fraction(1, 1),51 "",52 "a",53 "UNSET",54 "Sentinel.UNSET",55 [1],56 (1),57 {1: "a"},58 set(),59 set([1]),60 frozenset(),61 frozenset([1]),62 range(0),63 range(1),64 )6566 for real_value in real_values:67 assert value != real_value68 assert value is not real_value6970 assert value not in real_values717273def test_echo(runner):74 with runner.isolation() as outstreams:75 click.echo("\N{SNOWMAN}")76 click.echo(b"\x44\x44")77 click.echo(42, nl=False)78 click.echo(b"a", nl=False)79 click.echo("\x1b[31mx\x1b[39m", nl=False)80 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")81 assert bytes == b"\xe2\x98\x83\nDD\n42ax"8283 # if wrapped, we expect bytes to survive.84 @click.command()85 def cli():86 click.echo(b"\xf6")8788 result = runner.invoke(cli, [])89 assert result.stdout_bytes == b"\xf6\n"9091 # Ensure we do not strip for bytes.92 with runner.isolation() as outstreams:93 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)94 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"959697def test_echo_custom_file():98 f = StringIO()99 click.echo("hello", file=f)100 assert f.getvalue() == "hello\n"101102103def test_echo_no_streams(monkeypatch, runner):104 """echo should not fail when stdout and stderr are None with pythonw on Windows."""105 with runner.isolation():106 sys.stdout = None107 sys.stderr = None108 click.echo("test")109 click.echo("test", err=True)110111112@pytest.mark.parametrize(113 ("styles", "ref"),114 [115 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),116 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),117 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),118 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),119 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),120 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),121 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),122 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),123 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),124 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),125 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),126 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),127 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),128 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),129 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),130 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),131 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),132 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),133 ({"bold": True}, "\x1b[1mx y\x1b[0m"),134 ({"dim": True}, "\x1b[2mx y\x1b[0m"),135 ({"underline": True}, "\x1b[4mx y\x1b[0m"),136 ({"overline": True}, "\x1b[53mx y\x1b[0m"),137 ({"italic": True}, "\x1b[3mx y\x1b[0m"),138 ({"blink": True}, "\x1b[5mx y\x1b[0m"),139 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),140 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),141 ({"bold": False}, "\x1b[22mx y\x1b[0m"),142 ({"dim": False}, "\x1b[22mx y\x1b[0m"),143 ({"underline": False}, "\x1b[24mx y\x1b[0m"),144 ({"overline": False}, "\x1b[55mx y\x1b[0m"),145 ({"italic": False}, "\x1b[23mx y\x1b[0m"),146 ({"blink": False}, "\x1b[25mx y\x1b[0m"),147 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),148 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),149 ({"fg": "black", "reset": False}, "\x1b[30mx y"),150 ],151)152def test_styling(styles, ref):153 assert click.style("x y", **styles) == ref154 assert click.unstyle(ref) == "x y"155156157@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])158def test_unstyle_other_ansi(text, expect):159 assert click.unstyle(text) == expect160161162def test_filename_formatting():163 assert click.format_filename(b"foo.txt") == "foo.txt"164 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"165 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"166 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"167 assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"168169170def test_prompts(runner):171 @click.command()172 def test():173 if click.confirm("Foo"):174 click.echo("yes!")175 else:176 click.echo("no :(")177178 result = runner.invoke(test, input="y\n")179 assert not result.exception180 assert result.output == "Foo [y/N]: y\nyes!\n"181182 result = runner.invoke(test, input="\n")183 assert not result.exception184 assert result.output == "Foo [y/N]: \nno :(\n"185186 result = runner.invoke(test, input="n\n")187 assert not result.exception188 assert result.output == "Foo [y/N]: n\nno :(\n"189190 @click.command()191 def test_no():192 if click.confirm("Foo", default=True):193 click.echo("yes!")194 else:195 click.echo("no :(")196197 result = runner.invoke(test_no, input="y\n")198 assert not result.exception199 assert result.output == "Foo [Y/n]: y\nyes!\n"200201 result = runner.invoke(test_no, input="\n")202 assert not result.exception203 assert result.output == "Foo [Y/n]: \nyes!\n"204205 result = runner.invoke(test_no, input="n\n")206 assert not result.exception207 assert result.output == "Foo [Y/n]: n\nno :(\n"208209210def test_confirm_repeat(runner):211 cli = click.Command(212 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]213 )214 result = runner.invoke(cli, input="\ny\n")215 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"216217218@pytest.mark.skipif(WIN, reason="Different behavior on windows.")219def test_prompts_abort(monkeypatch, capsys):220 def f(_):221 raise KeyboardInterrupt()222223 monkeypatch.setattr("click.termui.hidden_prompt_func", f)224225 try:226 click.prompt("Password", hide_input=True)227 except click.Abort:228 click.echo("interrupted")229230 out, err = capsys.readouterr()231 assert out == "Password:\ninterrupted\n"232233234def test_prompts_eof(runner):235 """If too few lines of input are given, prompt should exit, not hang."""236237 @click.command238 def echo():239 for _ in range(3):240 click.echo(click.prompt("", type=int))241242 # only provide two lines of input for three prompts243 result = runner.invoke(echo, input="1\n2\n")244 assert result.exit_code == 1245246247def _test_gen_func():248 yield "a"249 yield "b"250 yield "c"251 yield "abc"252253254def _test_gen_func_fails():255 yield "test"256 raise RuntimeError("This is a test.")257258259def _test_gen_func_echo(file=None):260 yield "test"261 click.echo("hello", file=file)262 yield "test"263264265def _test_simulate_keyboard_interrupt(file=None):266 yield "output_before_keyboard_interrupt"267 raise KeyboardInterrupt()268269270EchoViaPagerTest = namedtuple(271 "EchoViaPagerTest",272 (273 "description",274 "test_input",275 "expected_pager",276 "expected_stdout",277 "expected_stderr",278 "expected_error",279 ),280)281282283@pytest.mark.skipif(WIN, reason="Different behavior on windows.")284@pytest.mark.parametrize(285 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]286)287@pytest.mark.parametrize(288 "test",289 [290 # We need to pass a parameter function instead of a plain param291 # as pytest.mark.parametrize will reuse the parameters causing the292 # generators to be used up so they will not yield anymore293 EchoViaPagerTest(294 description="Plain string argument",295 test_input=lambda: "just text",296 expected_pager="just text\n",297 expected_stdout="",298 expected_stderr="",299 expected_error=None,300 ),301 EchoViaPagerTest(302 description="Iterable argument",303 test_input=lambda: ["itera", "ble"],304 expected_pager="iterable\n",305 expected_stdout="",306 expected_stderr="",307 expected_error=None,308 ),309 EchoViaPagerTest(310 description="Generator function argument",311 test_input=lambda: _test_gen_func,312 expected_pager="abcabc\n",313 expected_stdout="",314 expected_stderr="",315 expected_error=None,316 ),317 EchoViaPagerTest(318 description="String generator argument",319 test_input=lambda: _test_gen_func(),320 expected_pager="abcabc\n",321 expected_stdout="",322 expected_stderr="",323 expected_error=None,324 ),325 EchoViaPagerTest(326 description="Number generator expression argument",327 test_input=lambda: (c for c in range(6)),328 expected_pager="012345\n",329 expected_stdout="",330 expected_stderr="",331 expected_error=None,332 ),333 EchoViaPagerTest(334 description="Exception in generator function argument",335 test_input=lambda: _test_gen_func_fails,336 # Because generator throws early on, the pager did not have337 # a chance yet to write the file.338 expected_pager="",339 expected_stdout="",340 expected_stderr="",341 expected_error=RuntimeError,342 ),343 EchoViaPagerTest(344 description="Exception in generator argument",345 test_input=lambda: _test_gen_func_fails,346 # Because generator throws early on, the pager did not have a347 # chance yet to write the file.348 expected_pager="",349 expected_stdout="",350 expected_stderr="",351 expected_error=RuntimeError,352 ),353 EchoViaPagerTest(354 description="Keyboard interrupt should not terminate the pager",355 test_input=lambda: _test_simulate_keyboard_interrupt(),356 # Due to the keyboard interrupt during pager execution, click program357 # should abort, but the pager should stay open.358 # This allows users to cancel the program and search in the pager359 # output, before they decide to terminate the pager.360 expected_pager="output_before_keyboard_interrupt",361 expected_stdout="",362 expected_stderr="",363 expected_error=KeyboardInterrupt,364 ),365 EchoViaPagerTest(366 description="Writing to stdout during generator execution",367 test_input=lambda: _test_gen_func_echo(),368 expected_pager="testtest\n",369 expected_stdout="hello\n",370 expected_stderr="",371 expected_error=None,372 ),373 EchoViaPagerTest(374 description="Writing to stderr during generator execution",375 test_input=lambda: _test_gen_func_echo(file=sys.stderr),376 expected_pager="testtest\n",377 expected_stdout="",378 expected_stderr="hello\n",379 expected_error=None,380 ),381 ],382)383def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):384 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)385 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)386387 test_input = test.test_input()388 expected_pager = test.expected_pager389 expected_stdout = test.expected_stdout390 expected_stderr = test.expected_stderr391 expected_error = test.expected_error392393 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()394395 pager_out_tmp = Path(tempdir) / "pager_out.txt"396 pager_out_tmp.unlink(missing_ok=True)397 with pager_out_tmp.open("w") as f:398 force_subprocess_stdout = patch.object(399 subprocess,400 "Popen",401 partial(subprocess.Popen, stdout=f),402 )403 with force_subprocess_stdout:404 with check_raise:405 click.echo_via_pager(test_input)406407 out, err = capfd.readouterr()408409 pager = pager_out_tmp.read_text()410411 assert pager == expected_pager, (412 f"Unexpected pager output in test case '{test.description}'"413 )414 assert out == expected_stdout, (415 f"Unexpected stdout in test case '{test.description}'"416 )417 assert err == expected_stderr, (418 f"Unexpected stderr in test case '{test.description}'"419 )420421422def test_echo_color_flag(monkeypatch, capfd):423 isatty = True424 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)425426 text = "foo"427 styled_text = click.style(text, fg="red")428 assert styled_text == "\x1b[31mfoo\x1b[0m"429430 click.echo(styled_text, color=False)431 out, err = capfd.readouterr()432 assert out == f"{text}\n"433434 click.echo(styled_text, color=True)435 out, err = capfd.readouterr()436 assert out == f"{styled_text}\n"437438 isatty = True439 click.echo(styled_text)440 out, err = capfd.readouterr()441 assert out == f"{styled_text}\n"442443 isatty = False444 # Faking isatty() is not enough on Windows;445 # the implementation caches the colorama wrapped stream446 # so we have to use a new stream for each test447 stream = StringIO()448 click.echo(styled_text, file=stream)449 assert stream.getvalue() == f"{text}\n"450451 stream = StringIO()452 click.echo(styled_text, file=stream, color=True)453 assert stream.getvalue() == f"{styled_text}\n"454455456def test_prompt_cast_default(capfd, monkeypatch):457 monkeypatch.setattr(sys, "stdin", StringIO("\n"))458 value = click.prompt("value", default="100", type=int)459 capfd.readouterr()460 assert isinstance(value, int)461462463@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")464def test_echo_writing_to_standard_error(capfd, monkeypatch):465 def emulate_input(text):466 """Emulate keyboard input."""467 monkeypatch.setattr(sys, "stdin", StringIO(text))468469 click.echo("Echo to standard output")470 out, err = capfd.readouterr()471 assert out == "Echo to standard output\n"472 assert err == ""473474 click.echo("Echo to standard error", err=True)475 out, err = capfd.readouterr()476 assert out == ""477 assert err == "Echo to standard error\n"478479 emulate_input("asdlkj\n")480 click.prompt("Prompt to stdin")481 out, err = capfd.readouterr()482 assert out == "Prompt to stdin: "483 assert err == ""484485 emulate_input("asdlkj\n")486 click.prompt("Prompt to stderr", err=True)487 out, err = capfd.readouterr()488 assert out == " "489 assert err == "Prompt to stderr:"490491 emulate_input("y\n")492 click.confirm("Prompt to stdin")493 out, err = capfd.readouterr()494 assert out == "Prompt to stdin [y/N]: "495 assert err == ""496497 emulate_input("y\n")498 click.confirm("Prompt to stderr", err=True)499 out, err = capfd.readouterr()500 assert out == " "501 assert err == "Prompt to stderr [y/N]:"502503 monkeypatch.setattr(click.termui, "isatty", lambda x: True)504 monkeypatch.setattr(click.termui, "getchar", lambda: " ")505506 click.pause("Pause to stdout")507 out, err = capfd.readouterr()508 assert out == "Pause to stdout\n"509 assert err == ""510511 click.pause("Pause to stderr", err=True)512 out, err = capfd.readouterr()513 assert out == ""514 assert err == "Pause to stderr\n"515516517def test_echo_with_capsys(capsys):518 click.echo("Capture me.")519 out, err = capsys.readouterr()520 assert out == "Capture me.\n"521522523def test_open_file(runner):524 @click.command()525 @click.argument("filename")526 def cli(filename):527 with click.open_file(filename) as f:528 click.echo(f.read())529530 click.echo("meep")531532 with runner.isolated_filesystem():533 with open("hello.txt", "w") as f:534 f.write("Cool stuff")535536 result = runner.invoke(cli, ["hello.txt"])537 assert result.exception is None538 assert result.output == "Cool stuff\nmeep\n"539540 result = runner.invoke(cli, ["-"], input="foobar")541 assert result.exception is None542 assert result.output == "foobar\nmeep\n"543544545def test_open_file_pathlib_dash(runner):546 @click.command()547 @click.argument(548 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)549 )550 def cli(filename):551 click.echo(str(type(filename)))552553 with click.open_file(filename) as f:554 click.echo(f.read())555556 result = runner.invoke(cli, ["-"], input="value")557 assert result.exception is None558 assert result.output == "pathlib.Path\nvalue\n"559560561def test_open_file_ignore_errors_stdin(runner):562 @click.command()563 @click.argument("filename")564 def cli(filename):565 with click.open_file(filename, errors="ignore") as f:566 click.echo(f.read())567568 result = runner.invoke(cli, ["-"], input=os.urandom(16))569 assert result.exception is None570571572def test_open_file_respects_ignore(runner):573 with runner.isolated_filesystem():574 with open("test.txt", "w") as f:575 f.write("Hello world!")576577 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:578 assert f.errors == "ignore"579580581def test_open_file_ignore_invalid_utf8(runner):582 with runner.isolated_filesystem():583 with open("test.txt", "wb") as f:584 f.write(b"\xe2\x28\xa1")585586 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:587 f.read()588589590def test_open_file_ignore_no_encoding(runner):591 with runner.isolated_filesystem():592 with open("test.bin", "wb") as f:593 f.write(os.urandom(16))594595 with click.open_file("test.bin", errors="ignore") as f:596 f.read()597598599@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")600@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])601def test_open_file_atomic_permissions_existing_file(runner, permissions):602 with runner.isolated_filesystem():603 with open("existing.txt", "w") as f:604 f.write("content")605 os.chmod("existing.txt", permissions)606607 @click.command()608 @click.argument("filename")609 def cli(filename):610 click.open_file(filename, "w", atomic=True).close()611612 result = runner.invoke(cli, ["existing.txt"])613 assert result.exception is None614 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions615616617@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")618def test_open_file_atomic_permissions_new_file(runner):619 with runner.isolated_filesystem():620621 @click.command()622 @click.argument("filename")623 def cli(filename):624 click.open_file(filename, "w", atomic=True).close()625626 # Create a test file to get the expected permissions for new files627 # according to the current umask.628 with open("test.txt", "w"):629 pass630 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)631632 result = runner.invoke(cli, ["new.txt"])633 assert result.exception is None634 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions635636637def test_iter_keepopenfile(tmpdir):638 expected = list(map(str, range(10)))639 p = tmpdir.mkdir("testdir").join("testfile")640 p.write("\n".join(expected))641 with p.open() as f:642 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):643 assert e_line == a_line.strip()644645646def test_iter_lazyfile(tmpdir):647 expected = list(map(str, range(10)))648 p = tmpdir.mkdir("testdir").join("testfile")649 p.write("\n".join(expected))650 with p.open() as f:651 with click.utils.LazyFile(f.name) as lf:652 for e_line, a_line in zip(expected, lf, strict=False):653 assert e_line == a_line.strip()654655656class MockMain:657 __slots__ = "__package__"658659 def __init__(self, package_name):660 self.__package__ = package_name661662663@pytest.mark.parametrize(664 ("path", "main", "expected"),665 [666 ("example.py", None, "example.py"),667 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),668 ("example", None, "example"),669 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),670 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),671 (str(pathlib.Path("./example")), "", "example"),672 ],673)674def test_detect_program_name(path, main, expected):675 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected676677678def test_expand_args(monkeypatch):679 user = os.path.expanduser("~")680 assert user in click.utils._expand_args(["~"])681 monkeypatch.setenv("CLICK_TEST", "hello")682 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])683 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])684 assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])685 assert "*.not-found" in click.utils._expand_args(["*.not-found"])686 # a bad glob pattern, such as a pytest identifier, should return itself687 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"688689690@pytest.mark.parametrize(691 ("value", "max_length", "expect"),692 [693 pytest.param("", 10, "", id="empty"),694 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),695 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),696 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),697 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),698 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),699 pytest.param(700 "token in ~/.netrc ciao ciao",701 20,702 "token in ~/.netrc...",703 id="ignore dot in word",704 ),705 ],706)707@pytest.mark.parametrize(708 "alter",709 [710 pytest.param(None, id=""),711 pytest.param(712 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"713 ),714 ],715)716def test_make_default_short_help(value, max_length, alter, expect):717 assert len(expect) <= max_length718719 if alter:720 value = alter(value)721722 out = click.utils.make_default_short_help(value, max_length)723 assert out == expect