test_utils.py
This file
Path
tests/test_utils.py
792 lines · 24.8 KiB · Python
Last changed by
fix skip conditionDavid Lordbefore adoption6cb3477
History of this fileTake it
The walk stopped after 200 commits: lines older than dd63959 point at it.
[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 1–3why, one step back1import os2import pathlib3import statMerge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
line 4why, one step back4import subprocess[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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 BytesIO[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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 patch[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 14–18why, one step back1415import pytest1617import click._termui_impl18import click.utilsfix: Skip flaky pager test on macOS with free-threaded Python 3.14t (#3470)David Lordbefore adoptionbee3314
line 19why, one step back19from click._compat import MAC[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
line 20why, one step back20from click._compat import WINMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 21–69why, one step back21from 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 True3334 # Try all native Python values that can be falsy or truthy.35 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing36 real_values = (37 None,38 True,39 False,40 0,41 1,42 0.0,43 1.0,44 0j,45 1j,46 Decimal(0),47 Decimal(1),48 Fraction(0, 1),49 Fraction(1, 1),50 "",51 "a",52 "UNSET",53 "Sentinel.UNSET",54 [1],55 (1),56 {1: "a"},57 set(),58 set([1]),59 frozenset(),60 frozenset([1]),61 range(0),62 range(1),63 )6465 for real_value in real_values:66 assert value != real_value67 assert value is not real_value6869 assert value not in real_values[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 70–96why, one step back707172def test_echo(runner):73 with runner.isolation() as outstreams:74 click.echo("\N{SNOWMAN}")75 click.echo(b"\x44\x44")76 click.echo(42, nl=False)77 click.echo(b"a", nl=False)78 click.echo("\x1b[31mx\x1b[39m", nl=False)79 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")80 assert bytes == b"\xe2\x98\x83\nDD\n42ax"8182 # if wrapped, we expect bytes to survive.83 @click.command()84 def cli():85 click.echo(b"\xf6")8687 result = runner.invoke(cli, [])88 assert result.stdout_bytes == b"\xf6\n"8990 # Ensure we do not strip for bytes.91 with runner.isolation() as outstreams:92 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)93 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"949596def test_echo_custom_file():Merge stable into main (#2799)Rowlando13before adoptiond791537
line 97why, one step back97 f = StringIO()[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 98–99why, one step back98 click.echo("hello", file=f)99 assert f.getvalue() == "hello\n"Handle empty bytes in echo (#3493)David Lordbefore adoptiona5f5aa6
lines 100–103why, one step back100101 b = BytesIO()102 click.echo(b"", b)103 assert b.getvalue() == b"\n"[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 104–169why, one step back104105106def test_echo_no_streams(monkeypatch, runner):107 """echo should not fail when stdout and stderr are None with pythonw on Windows."""108 with runner.isolation():109 sys.stdout = None110 sys.stderr = None111 click.echo("test")112 click.echo("test", err=True)113114115@pytest.mark.parametrize(116 ("styles", "ref"),117 [118 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),119 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),120 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),121 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),122 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),123 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),124 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),125 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),126 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),127 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),128 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),129 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),130 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),131 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),132 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),133 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),134 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),135 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),136 ({"bold": True}, "\x1b[1mx y\x1b[0m"),137 ({"dim": True}, "\x1b[2mx y\x1b[0m"),138 ({"underline": True}, "\x1b[4mx y\x1b[0m"),139 ({"overline": True}, "\x1b[53mx y\x1b[0m"),140 ({"italic": True}, "\x1b[3mx y\x1b[0m"),141 ({"blink": True}, "\x1b[5mx y\x1b[0m"),142 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),143 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),144 ({"bold": False}, "\x1b[22mx y\x1b[0m"),145 ({"dim": False}, "\x1b[22mx y\x1b[0m"),146 ({"underline": False}, "\x1b[24mx y\x1b[0m"),147 ({"overline": False}, "\x1b[55mx y\x1b[0m"),148 ({"italic": False}, "\x1b[23mx y\x1b[0m"),149 ({"blink": False}, "\x1b[25mx y\x1b[0m"),150 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),151 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),152 ({"fg": "black", "reset": False}, "\x1b[30mx y"),153 ],154)155def test_styling(styles, ref):156 assert click.style("x y", **styles) == ref157 assert click.unstyle(ref) == "x y"158159160@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])161def test_unstyle_other_ansi(text, expect):162 assert click.unstyle(text) == expect163164165def test_filename_formatting():166 assert click.format_filename(b"foo.txt") == "foo.txt"167 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"168 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"169 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"use uv (#2918)Rowlando13before adoption2e1c742
line 170why, one step back170 assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 171–233why, one step back171172173def test_prompts(runner):174 @click.command()175 def test():176 if click.confirm("Foo"):177 click.echo("yes!")178 else:179 click.echo("no :(")180181 result = runner.invoke(test, input="y\n")182 assert not result.exception183 assert result.output == "Foo [y/N]: y\nyes!\n"184185 result = runner.invoke(test, input="\n")186 assert not result.exception187 assert result.output == "Foo [y/N]: \nno :(\n"188189 result = runner.invoke(test, input="n\n")190 assert not result.exception191 assert result.output == "Foo [y/N]: n\nno :(\n"192193 @click.command()194 def test_no():195 if click.confirm("Foo", default=True):196 click.echo("yes!")197 else:198 click.echo("no :(")199200 result = runner.invoke(test_no, input="y\n")201 assert not result.exception202 assert result.output == "Foo [Y/n]: y\nyes!\n"203204 result = runner.invoke(test_no, input="\n")205 assert not result.exception206 assert result.output == "Foo [Y/n]: \nyes!\n"207208 result = runner.invoke(test_no, input="n\n")209 assert not result.exception210 assert result.output == "Foo [Y/n]: n\nno :(\n"211212213def test_confirm_repeat(runner):214 cli = click.Command(215 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]216 )217 result = runner.invoke(cli, input="\ny\n")218 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"219220221@pytest.mark.skipif(WIN, reason="Different behavior on windows.")222def test_prompts_abort(monkeypatch, capsys):223 def f(_):224 raise KeyboardInterrupt()225226 monkeypatch.setattr("click.termui.hidden_prompt_func", f)227228 try:229 click.prompt("Password", hide_input=True)230 except click.Abort:231 click.echo("interrupted")232233 out, err = capsys.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 234–235why, one step back234 # On non-Windows, prompt is passed directly to getpass, not echoed separately235 assert out == "\ninterrupted\n"[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 236–237why, one step back236237Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 238–267why, one step back238@pytest.mark.skipif(WIN, reason="Different behavior on windows.")239@pytest.mark.parametrize(240 ("call", "expected_prompt"),241 [242 (lambda: click.prompt("Name"), "Name: "),243 (lambda: click.prompt("Pw", hide_input=True), "Pw: "),244 (lambda: click.prompt("IP", prompt_suffix="."), "IP."),245 (lambda: click.confirm("OK"), "OK [y/N]: "),246 ],247 ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],248)249def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):250 """On non-Windows, prompt and confirm pass the full prompt text to the251 underlying prompt function so readline handles editing correctly.252253 https://github.com/pallets/click/issues/2968254 https://github.com/pallets/click/pull/2969255 """256 received = []257258 def capture(text):259 received.append(text)260 return "y"261262 monkeypatch.setattr("click.termui.visible_prompt_func", capture)263 monkeypatch.setattr("click.termui.hidden_prompt_func", capture)264 call()265 assert received == [expected_prompt]266267Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0
lines 268–280why, one step back268def test_prompts_eof(runner):269 """If too few lines of input are given, prompt should exit, not hang."""270271 @click.command272 def echo():273 for _ in range(3):274 click.echo(click.prompt("", type=int))275276 # only provide two lines of input for three prompts277 result = runner.invoke(echo, input="1\n2\n")278 assert result.exit_code == 1279280[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 281–287why, one step back281def _test_gen_func():282 yield "a"283 yield "b"284 yield "c"285 yield "abc"286287Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b
lines 288–316why, one step back288def _test_gen_func_fails():289 yield "test"290 raise RuntimeError("This is a test.")291292293def _test_gen_func_echo(file=None):294 yield "test"295 click.echo("hello", file=file)296 yield "test"297298299def _test_simulate_keyboard_interrupt(file=None):300 yield "output_before_keyboard_interrupt"301 raise KeyboardInterrupt()302303304EchoViaPagerTest = namedtuple(305 "EchoViaPagerTest",306 (307 "description",308 "test_input",309 "expected_pager",310 "expected_stdout",311 "expected_stderr",312 "expected_error",313 ),314)315316[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
line 317why, one step back317@pytest.mark.skipif(WIN, reason="Different behavior on windows.")fix: Skip flaky pager test on macOS with free-threaded Python 3.14t (#3470)David Lordbefore adoptionbee3314
line 318why, one step back318@pytest.mark.skipif(fix skip conditionDavid Lordbefore adoption6cb3477
line 319why, one step back319 MAC and sys.version_info >= (3, 13) and not sys._is_gil_enabled(),fix: Skip flaky pager test on macOS with free-threaded Python 3.14t (#3470)David Lordbefore adoptionbee3314
lines 320–321why, one step back320 reason="Generator exception tests are flaky in Python 3.14t on macOS.",321)[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
line 322why, one step back322@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([pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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 ),[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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)[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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_error[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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()[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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)443[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
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 )[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 457–480why, one step back457458459def test_echo_color_flag(monkeypatch, capfd):460 isatty = True461 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)462463 text = "foo"464 styled_text = click.style(text, fg="red")465 assert styled_text == "\x1b[31mfoo\x1b[0m"466467 click.echo(styled_text, color=False)468 out, err = capfd.readouterr()469 assert out == f"{text}\n"470471 click.echo(styled_text, color=True)472 out, err = capfd.readouterr()473 assert out == f"{styled_text}\n"474475 isatty = True476 click.echo(styled_text)477 out, err = capfd.readouterr()478 assert out == f"{styled_text}\n"479480 isatty = FalseMerge stable into main (#2799)Rowlando13before adoptiond791537
lines 481–490why, one step back481 # Faking isatty() is not enough on Windows;482 # the implementation caches the colorama wrapped stream483 # so we have to use a new stream for each test484 stream = StringIO()485 click.echo(styled_text, file=stream)486 assert stream.getvalue() == f"{text}\n"487488 stream = StringIO()489 click.echo(styled_text, file=stream, color=True)490 assert stream.getvalue() == f"{styled_text}\n"[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 491–522why, one step back491492493def test_prompt_cast_default(capfd, monkeypatch):494 monkeypatch.setattr(sys, "stdin", StringIO("\n"))495 value = click.prompt("value", default="100", type=int)496 capfd.readouterr()497 assert isinstance(value, int)498499500@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")501def test_echo_writing_to_standard_error(capfd, monkeypatch):502 def emulate_input(text):503 """Emulate keyboard input."""504 monkeypatch.setattr(sys, "stdin", StringIO(text))505506 click.echo("Echo to standard output")507 out, err = capfd.readouterr()508 assert out == "Echo to standard output\n"509 assert err == ""510511 click.echo("Echo to standard error", err=True)512 out, err = capfd.readouterr()513 assert out == ""514 assert err == "Echo to standard error\n"515516 emulate_input("asdlkj\n")517 click.prompt("Prompt to stdin")518 out, err = capfd.readouterr()519 assert out == "Prompt to stdin: "520 assert err == ""521522 emulate_input("asdlkj\n")Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 523–527why, one step back523 click.prompt("Prompt to stdin with no suffix", prompt_suffix="")524 out, err = capfd.readouterr()525 assert out == "Prompt to stdin with no suffix"526 assert err == ""527Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 528–530why, one step back528 # On non-Windows the full prompt goes through redirect_stdout so529 # nothing leaks to stdout when err=True.530 # https://github.com/pallets/click/issues/2968Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 531why, one step back531 emulate_input("asdlkj\n")[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 532–533why, one step back532 click.prompt("Prompt to stderr", err=True)533 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 534–535why, one step back534 assert out == ""535 assert err == "Prompt to stderr: "[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
line 536why, one step back536Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
line 537why, one step back537 # https://github.com/pallets/click/issues/3019Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 538–540why, one step back538 emulate_input("asdlkj\n")539 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)540 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 541–542why, one step back541 assert out == ""542 assert err == "Prompt to stderr with no suffix"Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 543why, one step back543[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 544–550why, one step back544 emulate_input("y\n")545 click.confirm("Prompt to stdin")546 out, err = capfd.readouterr()547 assert out == "Prompt to stdin [y/N]: "548 assert err == ""549550 emulate_input("y\n")Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 551–555why, one step back551 click.confirm("Prompt to stdin with no suffix", prompt_suffix="")552 out, err = capfd.readouterr()553 assert out == "Prompt to stdin with no suffix [y/N]"554 assert err == ""555Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
line 556why, one step back556 # https://github.com/pallets/click/issues/2968Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 557why, one step back557 emulate_input("y\n")[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 558–559why, one step back558 click.confirm("Prompt to stderr", err=True)559 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 560–561why, one step back560 assert out == ""561 assert err == "Prompt to stderr [y/N]: "Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
line 562why, one step back562Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
line 563why, one step back563 # https://github.com/pallets/click/issues/3019Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96
lines 564–566why, one step back564 emulate_input("y\n")565 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)566 out, err = capfd.readouterr()Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a
lines 567–568why, one step back567 assert out == ""568 assert err == "Prompt to stderr with no suffix [y/N]"[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 569–708why, one step back569570 monkeypatch.setattr(click.termui, "isatty", lambda x: True)571 monkeypatch.setattr(click.termui, "getchar", lambda: " ")572573 click.pause("Pause to stdout")574 out, err = capfd.readouterr()575 assert out == "Pause to stdout\n"576 assert err == ""577578 click.pause("Pause to stderr", err=True)579 out, err = capfd.readouterr()580 assert out == ""581 assert err == "Pause to stderr\n"582583584def test_echo_with_capsys(capsys):585 click.echo("Capture me.")586 out, err = capsys.readouterr()587 assert out == "Capture me.\n"588589590def test_open_file(runner):591 @click.command()592 @click.argument("filename")593 def cli(filename):594 with click.open_file(filename) as f:595 click.echo(f.read())596597 click.echo("meep")598599 with runner.isolated_filesystem():600 with open("hello.txt", "w") as f:601 f.write("Cool stuff")602603 result = runner.invoke(cli, ["hello.txt"])604 assert result.exception is None605 assert result.output == "Cool stuff\nmeep\n"606607 result = runner.invoke(cli, ["-"], input="foobar")608 assert result.exception is None609 assert result.output == "foobar\nmeep\n"610611612def test_open_file_pathlib_dash(runner):613 @click.command()614 @click.argument(615 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)616 )617 def cli(filename):618 click.echo(str(type(filename)))619620 with click.open_file(filename) as f:621 click.echo(f.read())622623 result = runner.invoke(cli, ["-"], input="value")624 assert result.exception is None625 assert result.output == "pathlib.Path\nvalue\n"626627628def test_open_file_ignore_errors_stdin(runner):629 @click.command()630 @click.argument("filename")631 def cli(filename):632 with click.open_file(filename, errors="ignore") as f:633 click.echo(f.read())634635 result = runner.invoke(cli, ["-"], input=os.urandom(16))636 assert result.exception is None637638639def test_open_file_respects_ignore(runner):640 with runner.isolated_filesystem():641 with open("test.txt", "w") as f:642 f.write("Hello world!")643644 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:645 assert f.errors == "ignore"646647648def test_open_file_ignore_invalid_utf8(runner):649 with runner.isolated_filesystem():650 with open("test.txt", "wb") as f:651 f.write(b"\xe2\x28\xa1")652653 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:654 f.read()655656657def test_open_file_ignore_no_encoding(runner):658 with runner.isolated_filesystem():659 with open("test.bin", "wb") as f:660 f.write(os.urandom(16))661662 with click.open_file("test.bin", errors="ignore") as f:663 f.read()664665666@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")667@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])668def test_open_file_atomic_permissions_existing_file(runner, permissions):669 with runner.isolated_filesystem():670 with open("existing.txt", "w") as f:671 f.write("content")672 os.chmod("existing.txt", permissions)673674 @click.command()675 @click.argument("filename")676 def cli(filename):677 click.open_file(filename, "w", atomic=True).close()678679 result = runner.invoke(cli, ["existing.txt"])680 assert result.exception is None681 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions682683684@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")685def test_open_file_atomic_permissions_new_file(runner):686 with runner.isolated_filesystem():687688 @click.command()689 @click.argument("filename")690 def cli(filename):691 click.open_file(filename, "w", atomic=True).close()692693 # Create a test file to get the expected permissions for new files694 # according to the current umask.695 with open("test.txt", "w"):696 pass697 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)698699 result = runner.invoke(cli, ["new.txt"])700 assert result.exception is None701 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions702703704def test_iter_keepopenfile(tmpdir):705 expected = list(map(str, range(10)))706 p = tmpdir.mkdir("testdir").join("testfile")707 p.write("\n".join(expected))708 with p.open() as f:drop end of life python versions (#2893)David Lordbefore adoption498f882
line 709why, one step back709 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 710–718why, one step back710 assert e_line == a_line.strip()711712713def test_iter_lazyfile(tmpdir):714 expected = list(map(str, range(10)))715 p = tmpdir.mkdir("testdir").join("testfile")716 p.write("\n".join(expected))717 with p.open() as f:718 with click.utils.LazyFile(f.name) as lf:drop end of life python versions (#2893)David Lordbefore adoption498f882
line 719why, one step back719 for e_line, a_line in zip(expected, lf, strict=False):[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 720–750why, one step back720 assert e_line == a_line.strip()721722723class MockMain:724 __slots__ = "__package__"725726 def __init__(self, package_name):727 self.__package__ = package_name728729730@pytest.mark.parametrize(731 ("path", "main", "expected"),732 [733 ("example.py", None, "example.py"),734 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),735 ("example", None, "example"),736 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),737 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),738 (str(pathlib.Path("./example")), "", "example"),739 ],740)741def test_detect_program_name(path, main, expected):742 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected743744745def test_expand_args(monkeypatch):746 user = os.path.expanduser("~")747 assert user in click.utils._expand_args(["~"])748 monkeypatch.setenv("CLICK_TEST", "hello")749 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])750 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])Don't test using a file in docs/ (#3102)Rowlando13before adoptionea70da4
lines 751–753why, one step back751 assert os.path.join("tests", "conftest.py") in click.utils._expand_args(752 ["**/conftest.py"]753 )[pre-commit.ci] pre-commit autoupdate (#2718)David Lordbefore adoptiondd63959
lines 754–792why, one step back754 assert "*.not-found" in click.utils._expand_args(["*.not-found"])755 # a bad glob pattern, such as a pytest identifier, should return itself756 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"757758759@pytest.mark.parametrize(760 ("value", "max_length", "expect"),761 [762 pytest.param("", 10, "", id="empty"),763 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),764 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),765 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),766 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),767 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),768 pytest.param(769 "token in ~/.netrc ciao ciao",770 20,771 "token in ~/.netrc...",772 id="ignore dot in word",773 ),774 ],775)776@pytest.mark.parametrize(777 "alter",778 [779 pytest.param(None, id=""),780 pytest.param(781 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"782 ),783 ],784)785def test_make_default_short_help(value, max_length, alter, expect):786 assert len(expect) <= max_length787788 if alter:789 value = alter(value)790791 out = click.utils.make_default_short_help(value, max_length)792 assert out == expect