test_utils.py
This file
Path
tests/test_utils.py
861 lines · 27.3 KiB · Python
Last changed by
Fix pager test flackiness and add stress tests for `echo_via_pager` (#3499)Rowlando13before adoptionffcc749
History of this fileTake it
The walk stopped after 200 commits: lines older than c326df9 point at it.
Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 1–3why, one step back1import os2import pathlib3import statMerge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 4why, one step back4import subprocessFix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
line 5why, one step back5import sysImprove echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
line 6why, one step back6from collections import namedtupleMerge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 7why, one step back7from contextlib import nullcontextMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 8–9why, one step back8from decimal import Decimal9from fractions import FractionMerge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 10why, one step back10from functools import partialHandle empty bytes in echo (#3493)David Lordbefore adoptiona5f5aa6
line 11why, one step back11from io import BytesIOFix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
line 12why, one step back12from io import StringIOMerge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 13why, one step back13from unittest.mock import patchFix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 14–19why, one step back1415import pytest1617import click._termui_impl18import click.utils19from click._compat import WINMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 20–68why, one step back20from click._utils import UNSET212223def test_unset_sentinel():24 value = UNSET2526 assert value27 assert value is UNSET28 assert value == UNSET29 assert repr(value) == "Sentinel.UNSET"30 assert str(value) == "Sentinel.UNSET"31 assert bool(value) is True3233 # Try all native Python values that can be falsy or truthy.34 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing35 real_values = (36 None,37 True,38 False,39 0,40 1,41 0.0,42 1.0,43 0j,44 1j,45 Decimal(0),46 Decimal(1),47 Fraction(0, 1),48 Fraction(1, 1),49 "",50 "a",51 "UNSET",52 "Sentinel.UNSET",53 [1],54 (1),55 {1: "a"},56 set(),57 set([1]),58 frozenset(),59 frozenset([1]),60 range(0),61 range(1),62 )6364 for real_value in real_values:65 assert value != real_value66 assert value is not real_value6768 assert value not in real_valuesFix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 69–95why, one step back697071def test_echo(runner):72 with runner.isolation() as outstreams:73 click.echo("\N{SNOWMAN}")74 click.echo(b"\x44\x44")75 click.echo(42, nl=False)76 click.echo(b"a", nl=False)77 click.echo("\x1b[31mx\x1b[39m", nl=False)78 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")79 assert bytes == b"\xe2\x98\x83\nDD\n42ax"8081 # if wrapped, we expect bytes to survive.82 @click.command()83 def cli():84 click.echo(b"\xf6")8586 result = runner.invoke(cli, [])87 assert result.stdout_bytes == b"\xf6\n"8889 # Ensure we do not strip for bytes.90 with runner.isolation() as outstreams:91 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)92 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"939495def test_echo_custom_file():Merge stable into main (#2799)Rowlando13before adoptiond791537
line 96why, one step back96 f = StringIO()Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 97–98why, one step back97 click.echo("hello", file=f)98 assert f.getvalue() == "hello\n"Handle empty bytes in echo (#3493)David Lordbefore adoptiona5f5aa6
lines 99–102why, one step back99100 b = BytesIO()101 click.echo(b"", b)102 assert b.getvalue() == b"\n"Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 103–168why, one step back103104105def test_echo_no_streams(monkeypatch, runner):106 """echo should not fail when stdout and stderr are None with pythonw on Windows."""107 with runner.isolation():108 sys.stdout = None109 sys.stderr = None110 click.echo("test")111 click.echo("test", err=True)112113114@pytest.mark.parametrize(115 ("styles", "ref"),116 [117 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),118 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),119 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),120 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),121 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),122 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),123 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),124 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),125 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),126 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),127 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),128 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),129 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),130 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),131 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),132 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),133 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),134 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),135 ({"bold": True}, "\x1b[1mx y\x1b[0m"),136 ({"dim": True}, "\x1b[2mx y\x1b[0m"),137 ({"underline": True}, "\x1b[4mx y\x1b[0m"),138 ({"overline": True}, "\x1b[53mx y\x1b[0m"),139 ({"italic": True}, "\x1b[3mx y\x1b[0m"),140 ({"blink": True}, "\x1b[5mx y\x1b[0m"),141 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),142 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),143 ({"bold": False}, "\x1b[22mx y\x1b[0m"),144 ({"dim": False}, "\x1b[22mx y\x1b[0m"),145 ({"underline": False}, "\x1b[24mx y\x1b[0m"),146 ({"overline": False}, "\x1b[55mx y\x1b[0m"),147 ({"italic": False}, "\x1b[23mx y\x1b[0m"),148 ({"blink": False}, "\x1b[25mx y\x1b[0m"),149 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),150 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),151 ({"fg": "black", "reset": False}, "\x1b[30mx y"),152 ],153)154def test_styling(styles, ref):155 assert click.style("x y", **styles) == ref156 assert click.unstyle(ref) == "x y"157158159@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])160def test_unstyle_other_ansi(text, expect):161 assert click.unstyle(text) == expect162163164def test_filename_formatting():165 assert click.format_filename(b"foo.txt") == "foo.txt"166 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"167 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"168 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"use uv (#2918)Rowlando13before adoption2e1c742
line 169why, one step back169 assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 170–232why, one step back170171172def test_prompts(runner):173 @click.command()174 def test():175 if click.confirm("Foo"):176 click.echo("yes!")177 else:178 click.echo("no :(")179180 result = runner.invoke(test, input="y\n")181 assert not result.exception182 assert result.output == "Foo [y/N]: y\nyes!\n"183184 result = runner.invoke(test, input="\n")185 assert not result.exception186 assert result.output == "Foo [y/N]: \nno :(\n"187188 result = runner.invoke(test, input="n\n")189 assert not result.exception190 assert result.output == "Foo [y/N]: n\nno :(\n"191192 @click.command()193 def test_no():194 if click.confirm("Foo", default=True):195 click.echo("yes!")196 else:197 click.echo("no :(")198199 result = runner.invoke(test_no, input="y\n")200 assert not result.exception201 assert result.output == "Foo [Y/n]: y\nyes!\n"202203 result = runner.invoke(test_no, input="\n")204 assert not result.exception205 assert result.output == "Foo [Y/n]: \nyes!\n"206207 result = runner.invoke(test_no, input="n\n")208 assert not result.exception209 assert result.output == "Foo [Y/n]: n\nno :(\n"210211212def test_confirm_repeat(runner):213 cli = click.Command(214 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]215 )216 result = runner.invoke(cli, input="\ny\n")217 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"218219220@pytest.mark.skipif(WIN, reason="Different behavior on windows.")221def test_prompts_abort(monkeypatch, capsys):222 def f(_):223 raise KeyboardInterrupt()224225 monkeypatch.setattr("click.termui.hidden_prompt_func", f)226227 try:228 click.prompt("Password", hide_input=True)229 except click.Abort:230 click.echo("interrupted")231232 out, err = capsys.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 233–234why, one step back233 # On non-Windows, prompt is passed directly to getpass, not echoed separately234 assert out == "\ninterrupted\n"Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 235–236why, one step back235236Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 237–266why, one step back237@pytest.mark.skipif(WIN, reason="Different behavior on windows.")238@pytest.mark.parametrize(239 ("call", "expected_prompt"),240 [241 (lambda: click.prompt("Name"), "Name: "),242 (lambda: click.prompt("Pw", hide_input=True), "Pw: "),243 (lambda: click.prompt("IP", prompt_suffix="."), "IP."),244 (lambda: click.confirm("OK"), "OK [y/N]: "),245 ],246 ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],247)248def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):249 """On non-Windows, prompt and confirm pass the full prompt text to the250 underlying prompt function so readline handles editing correctly.251252 https://github.com/pallets/click/issues/2968253 https://github.com/pallets/click/pull/2969254 """255 received = []256257 def capture(text):258 received.append(text)259 return "y"260261 monkeypatch.setattr("click.termui.visible_prompt_func", capture)262 monkeypatch.setattr("click.termui.hidden_prompt_func", capture)263 call()264 assert received == [expected_prompt]265266Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0
lines 267–279why, one step back267def test_prompts_eof(runner):268 """If too few lines of input are given, prompt should exit, not hang."""269270 @click.command271 def echo():272 for _ in range(3):273 click.echo(click.prompt("", type=int))274275 # only provide two lines of input for three prompts276 result = runner.invoke(echo, input="1\n2\n")277 assert result.exit_code == 1278279Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 280–286why, one step back280def _test_gen_func():281 yield "a"282 yield "b"283 yield "c"284 yield "abc"285286Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
line 287why, one step back287def _test_gen_func_fails():Fix pager test flackiness and add stress tests for `echo_via_pager` (#3499)Rowlando13before adoptionffcc749
lines 288–292why, one step back288 raise RuntimeError("This is a test.")289 yield # unreachable, keeps this a generator function290291292def _test_gen_func_yields_then_fails():Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
lines 293–320why, one step back293 yield "test"294 raise RuntimeError("This is a test.")295296297def _test_gen_func_echo(file=None):298 yield "test"299 click.echo("hello", file=file)300 yield "test"301302303def _test_simulate_keyboard_interrupt(file=None):304 yield "output_before_keyboard_interrupt"305 raise KeyboardInterrupt()306307308EchoViaPagerTest = namedtuple(309 "EchoViaPagerTest",310 (311 "description",312 "test_input",313 "expected_pager",314 "expected_stdout",315 "expected_stderr",316 "expected_error",317 ),318)319320Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 321–322why, one step back321@pytest.mark.skipif(WIN, reason="Different behavior on windows.")322@pytest.mark.parametrize(Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
lines 323–325why, one step back323 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]324)325@pytest.mark.parametrize(Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 326–327why, one step back326 "test",327 [Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
lines 328–375why, one step back328 # We need to pass a parameter function instead of a plain param329 # as pytest.mark.parametrize will reuse the parameters causing the330 # generators to be used up so they will not yield anymore331 EchoViaPagerTest(332 description="Plain string argument",333 test_input=lambda: "just text",334 expected_pager="just text\n",335 expected_stdout="",336 expected_stderr="",337 expected_error=None,338 ),339 EchoViaPagerTest(340 description="Iterable argument",341 test_input=lambda: ["itera", "ble"],342 expected_pager="iterable\n",343 expected_stdout="",344 expected_stderr="",345 expected_error=None,346 ),347 EchoViaPagerTest(348 description="Generator function argument",349 test_input=lambda: _test_gen_func,350 expected_pager="abcabc\n",351 expected_stdout="",352 expected_stderr="",353 expected_error=None,354 ),355 EchoViaPagerTest(356 description="String generator argument",357 test_input=lambda: _test_gen_func(),358 expected_pager="abcabc\n",359 expected_stdout="",360 expected_stderr="",361 expected_error=None,362 ),363 EchoViaPagerTest(364 description="Number generator expression argument",365 test_input=lambda: (c for c in range(6)),366 expected_pager="012345\n",367 expected_stdout="",368 expected_stderr="",369 expected_error=None,370 ),371 EchoViaPagerTest(372 description="Exception in generator function argument",373 test_input=lambda: _test_gen_func_fails,374 # Because generator throws early on, the pager did not have375 # a chance yet to write the file.Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 376why, one step back376 expected_pager="",Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
lines 377–385why, one step back377 expected_stdout="",378 expected_stderr="",379 expected_error=RuntimeError,380 ),381 EchoViaPagerTest(382 description="Exception in generator argument",383 test_input=lambda: _test_gen_func_fails,384 # Because generator throws early on, the pager did not have a385 # chance yet to write the file.Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 386why, one step back386 expected_pager="",Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
lines 387–418why, one step back387 expected_stdout="",388 expected_stderr="",389 expected_error=RuntimeError,390 ),391 EchoViaPagerTest(392 description="Keyboard interrupt should not terminate the pager",393 test_input=lambda: _test_simulate_keyboard_interrupt(),394 # Due to the keyboard interrupt during pager execution, click program395 # should abort, but the pager should stay open.396 # This allows users to cancel the program and search in the pager397 # output, before they decide to terminate the pager.398 expected_pager="output_before_keyboard_interrupt",399 expected_stdout="",400 expected_stderr="",401 expected_error=KeyboardInterrupt,402 ),403 EchoViaPagerTest(404 description="Writing to stdout during generator execution",405 test_input=lambda: _test_gen_func_echo(),406 expected_pager="testtest\n",407 expected_stdout="hello\n",408 expected_stderr="",409 expected_error=None,410 ),411 EchoViaPagerTest(412 description="Writing to stderr during generator execution",413 test_input=lambda: _test_gen_func_echo(file=sys.stderr),414 expected_pager="testtest\n",415 expected_stdout="",416 expected_stderr="hello\n",417 expected_error=None,418 ),Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 419–420why, one step back419 ],420)Fix pager test leaks (#3238)Rowlando13before adoption5df1001
line 421why, one step back421def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 422why, one step back422 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 423–424why, one step back423 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)424Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
lines 425–429why, one step back425 test_input = test.test_input()426 expected_pager = test.expected_pager427 expected_stdout = test.expected_stdout428 expected_stderr = test.expected_stderr429 expected_error = test.expected_errorFix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
line 430why, one step back430Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 431why, one step back431 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
line 432why, one step back432Fix pager test leaks (#3238)Rowlando13before adoption5df1001
line 433why, one step back433 pager_out_tmp = tmp_path / "pager_out.txt"Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
lines 434–443why, one step back434 with pager_out_tmp.open("w") as f:435 force_subprocess_stdout = patch.object(436 subprocess,437 "Popen",438 partial(subprocess.Popen, stdout=f),439 )440 with force_subprocess_stdout:441 with check_raise:442 click.echo_via_pager(test_input)443Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
line 444why, one step back444 out, err = capfd.readouterr()Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
line 445why, one step back445Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 446why, one step back446 pager = pager_out_tmp.read_text()Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
line 447why, one step back447update dev dependenciesDavid Lordbefore adoptionf14b750
lines 448–456why, one step back448 assert pager == expected_pager, (449 f"Unexpected pager output in test case '{test.description}'"450 )451 assert out == expected_stdout, (452 f"Unexpected stdout in test case '{test.description}'"453 )454 assert err == expected_stderr, (455 f"Unexpected stderr in test case '{test.description}'"456 )Fix pager test flackiness and add stress tests for `echo_via_pager` (#3499)Rowlando13before adoptionffcc749
lines 457–525why, one step back457458459@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):461 """A generator that yields then raises: click writes the partial output to462 the pager stream before propagating the exception.463464 The pager file content is intentionally NOT asserted: pipe-drain timing465 between click and the pager subprocess is outside click's control466 (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent467 to the pager, which is deterministic regardless of scheduling.468 """469 monkeypatch.setitem(os.environ, "PAGER", "cat")470 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)471472 writes: list[str] = []473 real_write = click._termui_impl.MaybeStripAnsi.write474475 def spy(self, text):476 writes.append(text)477 return real_write(self, text)478479 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480481 pager_out_tmp = tmp_path / "pager_out.txt"482 with (483 pager_out_tmp.open("w") as f,484 patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),485 pytest.raises(RuntimeError, match="This is a test."),486 ):487 click.echo_via_pager(_test_gen_func_yields_then_fails())488489 assert "".join(writes) == "test", (490 f"click should have written the yielded chunk before exception, got {writes!r}"491 )492493494@pytest.mark.stress495@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496@pytest.mark.parametrize("_", range(1000))497def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498 """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499500 Regression coverage for the cleanup path in ``_pipepager``'s exception501 handler (issue #2899, PR #3470). Each iteration spawns a real pager502 subprocess, raises before any data is written and check there is no leak.503 """504 monkeypatch.setitem(os.environ, "PAGER", "cat")505 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)506507 spawned: list[subprocess.Popen] = []508 real_popen = subprocess.Popen509510 def tracking_popen(*args, **kwargs):511 p = real_popen(*args, **kwargs)512 spawned.append(p)513 return p514515 pager_out_tmp = tmp_path / "pager_out.txt"516 with (517 pager_out_tmp.open("w") as f,518 patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),519 pytest.raises(RuntimeError),520 ):521 click.echo_via_pager(_test_gen_func_fails())522523 assert spawned, "pager subprocess was never started"524 for p in spawned:525 assert p.returncode is not None, "pager subprocess not reaped"Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 526–549why, one step back526527528def test_echo_color_flag(monkeypatch, capfd):529 isatty = True530 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531532 text = "foo"533 styled_text = click.style(text, fg="red")534 assert styled_text == "\x1b[31mfoo\x1b[0m"535536 click.echo(styled_text, color=False)537 out, err = capfd.readouterr()538 assert out == f"{text}\n"539540 click.echo(styled_text, color=True)541 out, err = capfd.readouterr()542 assert out == f"{styled_text}\n"543544 isatty = True545 click.echo(styled_text)546 out, err = capfd.readouterr()547 assert out == f"{styled_text}\n"548549 isatty = FalseMerge stable into main (#2799)Rowlando13before adoptiond791537
lines 550–559why, one step back550 # Faking isatty() is not enough on Windows;551 # the implementation caches the colorama wrapped stream552 # so we have to use a new stream for each test553 stream = StringIO()554 click.echo(styled_text, file=stream)555 assert stream.getvalue() == f"{text}\n"556557 stream = StringIO()558 click.echo(styled_text, file=stream, color=True)559 assert stream.getvalue() == f"{styled_text}\n"Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 560–591why, one step back560561562def test_prompt_cast_default(capfd, monkeypatch):563 monkeypatch.setattr(sys, "stdin", StringIO("\n"))564 value = click.prompt("value", default="100", type=int)565 capfd.readouterr()566 assert isinstance(value, int)567568569@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")570def test_echo_writing_to_standard_error(capfd, monkeypatch):571 def emulate_input(text):572 """Emulate keyboard input."""573 monkeypatch.setattr(sys, "stdin", StringIO(text))574575 click.echo("Echo to standard output")576 out, err = capfd.readouterr()577 assert out == "Echo to standard output\n"578 assert err == ""579580 click.echo("Echo to standard error", err=True)581 out, err = capfd.readouterr()582 assert out == ""583 assert err == "Echo to standard error\n"584585 emulate_input("asdlkj\n")586 click.prompt("Prompt to stdin")587 out, err = capfd.readouterr()588 assert out == "Prompt to stdin: "589 assert err == ""590591 emulate_input("asdlkj\n")Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 592–596why, one step back592 click.prompt("Prompt to stdin with no suffix", prompt_suffix="")593 out, err = capfd.readouterr()594 assert out == "Prompt to stdin with no suffix"595 assert err == ""596Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 597–599why, one step back597 # On non-Windows the full prompt goes through redirect_stdout so598 # nothing leaks to stdout when err=True.599 # https://github.com/pallets/click/issues/2968Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 600why, one step back600 emulate_input("asdlkj\n")Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 601–602why, one step back601 click.prompt("Prompt to stderr", err=True)602 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 603–604why, one step back603 assert out == ""604 assert err == "Prompt to stderr: "Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
line 605why, one step back605Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
line 606why, one step back606 # https://github.com/pallets/click/issues/3019Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 607–609why, one step back607 emulate_input("asdlkj\n")608 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)609 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 610–611why, one step back610 assert out == ""611 assert err == "Prompt to stderr with no suffix"Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 612why, one step back612Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 613–619why, one step back613 emulate_input("y\n")614 click.confirm("Prompt to stdin")615 out, err = capfd.readouterr()616 assert out == "Prompt to stdin [y/N]: "617 assert err == ""618619 emulate_input("y\n")Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 620–624why, one step back620 click.confirm("Prompt to stdin with no suffix", prompt_suffix="")621 out, err = capfd.readouterr()622 assert out == "Prompt to stdin with no suffix [y/N]"623 assert err == ""624Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
line 625why, one step back625 # https://github.com/pallets/click/issues/2968Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 626why, one step back626 emulate_input("y\n")Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 627–628why, one step back627 click.confirm("Prompt to stderr", err=True)628 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 629–630why, one step back629 assert out == ""630 assert err == "Prompt to stderr [y/N]: "Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 631why, one step back631Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
line 632why, one step back632 # https://github.com/pallets/click/issues/3019Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 633–635why, one step back633 emulate_input("y\n")634 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)635 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 636–637why, one step back636 assert out == ""637 assert err == "Prompt to stderr with no suffix [y/N]"Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 638–777why, one step back638639 monkeypatch.setattr(click.termui, "isatty", lambda x: True)640 monkeypatch.setattr(click.termui, "getchar", lambda: " ")641642 click.pause("Pause to stdout")643 out, err = capfd.readouterr()644 assert out == "Pause to stdout\n"645 assert err == ""646647 click.pause("Pause to stderr", err=True)648 out, err = capfd.readouterr()649 assert out == ""650 assert err == "Pause to stderr\n"651652653def test_echo_with_capsys(capsys):654 click.echo("Capture me.")655 out, err = capsys.readouterr()656 assert out == "Capture me.\n"657658659def test_open_file(runner):660 @click.command()661 @click.argument("filename")662 def cli(filename):663 with click.open_file(filename) as f:664 click.echo(f.read())665666 click.echo("meep")667668 with runner.isolated_filesystem():669 with open("hello.txt", "w") as f:670 f.write("Cool stuff")671672 result = runner.invoke(cli, ["hello.txt"])673 assert result.exception is None674 assert result.output == "Cool stuff\nmeep\n"675676 result = runner.invoke(cli, ["-"], input="foobar")677 assert result.exception is None678 assert result.output == "foobar\nmeep\n"679680681def test_open_file_pathlib_dash(runner):682 @click.command()683 @click.argument(684 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)685 )686 def cli(filename):687 click.echo(str(type(filename)))688689 with click.open_file(filename) as f:690 click.echo(f.read())691692 result = runner.invoke(cli, ["-"], input="value")693 assert result.exception is None694 assert result.output == "pathlib.Path\nvalue\n"695696697def test_open_file_ignore_errors_stdin(runner):698 @click.command()699 @click.argument("filename")700 def cli(filename):701 with click.open_file(filename, errors="ignore") as f:702 click.echo(f.read())703704 result = runner.invoke(cli, ["-"], input=os.urandom(16))705 assert result.exception is None706707708def test_open_file_respects_ignore(runner):709 with runner.isolated_filesystem():710 with open("test.txt", "w") as f:711 f.write("Hello world!")712713 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:714 assert f.errors == "ignore"715716717def test_open_file_ignore_invalid_utf8(runner):718 with runner.isolated_filesystem():719 with open("test.txt", "wb") as f:720 f.write(b"\xe2\x28\xa1")721722 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:723 f.read()724725726def test_open_file_ignore_no_encoding(runner):727 with runner.isolated_filesystem():728 with open("test.bin", "wb") as f:729 f.write(os.urandom(16))730731 with click.open_file("test.bin", errors="ignore") as f:732 f.read()733734735@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")736@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])737def test_open_file_atomic_permissions_existing_file(runner, permissions):738 with runner.isolated_filesystem():739 with open("existing.txt", "w") as f:740 f.write("content")741 os.chmod("existing.txt", permissions)742743 @click.command()744 @click.argument("filename")745 def cli(filename):746 click.open_file(filename, "w", atomic=True).close()747748 result = runner.invoke(cli, ["existing.txt"])749 assert result.exception is None750 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions751752753@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")754def test_open_file_atomic_permissions_new_file(runner):755 with runner.isolated_filesystem():756757 @click.command()758 @click.argument("filename")759 def cli(filename):760 click.open_file(filename, "w", atomic=True).close()761762 # Create a test file to get the expected permissions for new files763 # according to the current umask.764 with open("test.txt", "w"):765 pass766 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)767768 result = runner.invoke(cli, ["new.txt"])769 assert result.exception is None770 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions771772773def test_iter_keepopenfile(tmpdir):774 expected = list(map(str, range(10)))775 p = tmpdir.mkdir("testdir").join("testfile")776 p.write("\n".join(expected))777 with p.open() as f:drop end of life python versions (#2893)David Lordbefore adoption498f882
line 778why, one step back778 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 779–787why, one step back779 assert e_line == a_line.strip()780781782def test_iter_lazyfile(tmpdir):783 expected = list(map(str, range(10)))784 p = tmpdir.mkdir("testdir").join("testfile")785 p.write("\n".join(expected))786 with p.open() as f:787 with click.utils.LazyFile(f.name) as lf:drop end of life python versions (#2893)David Lordbefore adoption498f882
line 788why, one step back788 for e_line, a_line in zip(expected, lf, strict=False):Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 789–819why, one step back789 assert e_line == a_line.strip()790791792class MockMain:793 __slots__ = "__package__"794795 def __init__(self, package_name):796 self.__package__ = package_name797798799@pytest.mark.parametrize(800 ("path", "main", "expected"),801 [802 ("example.py", None, "example.py"),803 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),804 ("example", None, "example"),805 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),806 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),807 (str(pathlib.Path("./example")), "", "example"),808 ],809)810def test_detect_program_name(path, main, expected):811 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected812813814def test_expand_args(monkeypatch):815 user = os.path.expanduser("~")816 assert user in click.utils._expand_args(["~"])817 monkeypatch.setenv("CLICK_TEST", "hello")818 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])819 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])Don't test using a file in docs/ (#3102)Rowlando13before adoptionea70da4
lines 820–822why, one step back820 assert os.path.join("tests", "conftest.py") in click.utils._expand_args(821 ["**/conftest.py"]822 )Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9
lines 823–861why, one step back823 assert "*.not-found" in click.utils._expand_args(["*.not-found"])824 # a bad glob pattern, such as a pytest identifier, should return itself825 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"826827828@pytest.mark.parametrize(829 ("value", "max_length", "expect"),830 [831 pytest.param("", 10, "", id="empty"),832 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),833 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),834 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),835 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),836 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),837 pytest.param(838 "token in ~/.netrc ciao ciao",839 20,840 "token in ~/.netrc...",841 id="ignore dot in word",842 ),843 ],844)845@pytest.mark.parametrize(846 "alter",847 [848 pytest.param(None, id=""),849 pytest.param(850 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"851 ),852 ],853)854def test_make_default_short_help(value, max_length, alter, expect):855 assert len(expect) <= max_length856857 if alter:858 value = alter(value)859860 out = click.utils.make_default_short_help(value, max_length)861 assert out == expect