Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

745 lines · 23.1 KiB · Python

Last changed by

Fix pager test leaks (#3238)Rowlando13before adoption5df1001

History of this file

Take it

The walk stopped after 200 commits: lines older than 1a3baf7 point at it.

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 1–3why, one step back
1import os
2import pathlib3import stat

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 4why, one step back
4import subprocess

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

line 5why, one step back
5import sys

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

line 6why, one step back
6from collections import namedtuple

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 7why, one step back
7from contextlib import nullcontext

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 8–9why, one step back
8from decimal import Decimal
9from fractions import Fraction

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 10why, one step back
10from functools import partial

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

line 11why, one step back
11from io import StringIO

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 12why, one step back
12from unittest.mock import patch

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 13–18why, one step back
13
14import pytest1516import click._termui_impl17import click.utils18from click._compat import WIN

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 19–67why, one step back
19from click._utils import UNSET
202122def test_unset_sentinel():23 value = UNSET2425 assert value26 assert value is UNSET27 assert value == UNSET28 assert repr(value) == "Sentinel.UNSET"29 assert str(value) == "Sentinel.UNSET"30 assert bool(value) is True3132 # Try all native Python values that can be falsy or truthy.33 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing34 real_values = (35 None,36 True,37 False,38 0,39 1,40 0.0,41 1.0,42 0j,43 1j,44 Decimal(0),45 Decimal(1),46 Fraction(0, 1),47 Fraction(1, 1),48 "",49 "a",50 "UNSET",51 "Sentinel.UNSET",52 [1],53 (1),54 {1: "a"},55 set(),56 set([1]),57 frozenset(),58 frozenset([1]),59 range(0),60 range(1),61 )6263 for real_value in real_values:64 assert value != real_value65 assert value is not real_value6667 assert value not in real_values

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 68–94why, one step back
68
6970def test_echo(runner):71 with runner.isolation() as outstreams:72 click.echo("\N{SNOWMAN}")73 click.echo(b"\x44\x44")74 click.echo(42, nl=False)75 click.echo(b"a", nl=False)76 click.echo("\x1b[31mx\x1b[39m", nl=False)77 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")78 assert bytes == b"\xe2\x98\x83\nDD\n42ax"7980 # if wrapped, we expect bytes to survive.81 @click.command()82 def cli():83 click.echo(b"\xf6")8485 result = runner.invoke(cli, [])86 assert result.stdout_bytes == b"\xf6\n"8788 # Ensure we do not strip for bytes.89 with runner.isolation() as outstreams:90 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)91 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"929394def test_echo_custom_file():

Merge stable into main (#2799)Rowlando13before adoptiond791537

line 95why, one step back
95 f = StringIO()

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 96–163why, one step back
96 click.echo("hello", file=f)
97 assert f.getvalue() == "hello\n"9899100def test_echo_no_streams(monkeypatch, runner):101 """echo should not fail when stdout and stderr are None with pythonw on Windows."""102 with runner.isolation():103 sys.stdout = None104 sys.stderr = None105 click.echo("test")106 click.echo("test", err=True)107108109@pytest.mark.parametrize(110 ("styles", "ref"),111 [112 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),113 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),114 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),115 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),116 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),117 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),118 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),119 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),120 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),121 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),122 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),123 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),124 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),125 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),126 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),127 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),128 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),129 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),130 ({"bold": True}, "\x1b[1mx y\x1b[0m"),131 ({"dim": True}, "\x1b[2mx y\x1b[0m"),132 ({"underline": True}, "\x1b[4mx y\x1b[0m"),133 ({"overline": True}, "\x1b[53mx y\x1b[0m"),134 ({"italic": True}, "\x1b[3mx y\x1b[0m"),135 ({"blink": True}, "\x1b[5mx y\x1b[0m"),136 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),137 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),138 ({"bold": False}, "\x1b[22mx y\x1b[0m"),139 ({"dim": False}, "\x1b[22mx y\x1b[0m"),140 ({"underline": False}, "\x1b[24mx y\x1b[0m"),141 ({"overline": False}, "\x1b[55mx y\x1b[0m"),142 ({"italic": False}, "\x1b[23mx y\x1b[0m"),143 ({"blink": False}, "\x1b[25mx y\x1b[0m"),144 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),145 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),146 ({"fg": "black", "reset": False}, "\x1b[30mx y"),147 ],148)149def test_styling(styles, ref):150 assert click.style("x y", **styles) == ref151 assert click.unstyle(ref) == "x y"152153154@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])155def test_unstyle_other_ansi(text, expect):156 assert click.unstyle(text) == expect157158159def test_filename_formatting():160 assert click.format_filename(b"foo.txt") == "foo.txt"161 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"162 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"163 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"

use uv (#2918)Rowlando13before adoption2e1c742

line 164why, one step back
164 assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 165–230why, one step back
165
166167def test_prompts(runner):168 @click.command()169 def test():170 if click.confirm("Foo"):171 click.echo("yes!")172 else:173 click.echo("no :(")174175 result = runner.invoke(test, input="y\n")176 assert not result.exception177 assert result.output == "Foo [y/N]: y\nyes!\n"178179 result = runner.invoke(test, input="\n")180 assert not result.exception181 assert result.output == "Foo [y/N]: \nno :(\n"182183 result = runner.invoke(test, input="n\n")184 assert not result.exception185 assert result.output == "Foo [y/N]: n\nno :(\n"186187 @click.command()188 def test_no():189 if click.confirm("Foo", default=True):190 click.echo("yes!")191 else:192 click.echo("no :(")193194 result = runner.invoke(test_no, input="y\n")195 assert not result.exception196 assert result.output == "Foo [Y/n]: y\nyes!\n"197198 result = runner.invoke(test_no, input="\n")199 assert not result.exception200 assert result.output == "Foo [Y/n]: \nyes!\n"201202 result = runner.invoke(test_no, input="n\n")203 assert not result.exception204 assert result.output == "Foo [Y/n]: n\nno :(\n"205206207def test_confirm_repeat(runner):208 cli = click.Command(209 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]210 )211 result = runner.invoke(cli, input="\ny\n")212 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"213214215@pytest.mark.skipif(WIN, reason="Different behavior on windows.")216def test_prompts_abort(monkeypatch, capsys):217 def f(_):218 raise KeyboardInterrupt()219220 monkeypatch.setattr("click.termui.hidden_prompt_func", f)221222 try:223 click.prompt("Password", hide_input=True)224 except click.Abort:225 click.echo("interrupted")226227 out, err = capsys.readouterr()228 assert out == "Password:\ninterrupted\n"229230

Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0

lines 231–243why, one step back
231def test_prompts_eof(runner):
232 """If too few lines of input are given, prompt should exit, not hang."""233234 @click.command235 def echo():236 for _ in range(3):237 click.echo(click.prompt("", type=int))238239 # only provide two lines of input for three prompts240 result = runner.invoke(echo, input="1\n2\n")241 assert result.exit_code == 1242243

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 244–250why, one step back
244def _test_gen_func():
245 yield "a"246 yield "b"247 yield "c"248 yield "abc"249250

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

lines 251–279why, one step back
251def _test_gen_func_fails():
252 yield "test"253 raise RuntimeError("This is a test.")254255256def _test_gen_func_echo(file=None):257 yield "test"258 click.echo("hello", file=file)259 yield "test"260261262def _test_simulate_keyboard_interrupt(file=None):263 yield "output_before_keyboard_interrupt"264 raise KeyboardInterrupt()265266267EchoViaPagerTest = namedtuple(268 "EchoViaPagerTest",269 (270 "description",271 "test_input",272 "expected_pager",273 "expected_stdout",274 "expected_stderr",275 "expected_error",276 ),277)278279

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 280–281why, one step back
280@pytest.mark.skipif(WIN, reason="Different behavior on windows.")
281@pytest.mark.parametrize(

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

lines 282–284why, one step back
282 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]
283)284@pytest.mark.parametrize(

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 285–286why, one step back
285 "test",
286 [

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

lines 287–334why, one step back
287 # We need to pass a parameter function instead of a plain param
288 # as pytest.mark.parametrize will reuse the parameters causing the289 # generators to be used up so they will not yield anymore290 EchoViaPagerTest(291 description="Plain string argument",292 test_input=lambda: "just text",293 expected_pager="just text\n",294 expected_stdout="",295 expected_stderr="",296 expected_error=None,297 ),298 EchoViaPagerTest(299 description="Iterable argument",300 test_input=lambda: ["itera", "ble"],301 expected_pager="iterable\n",302 expected_stdout="",303 expected_stderr="",304 expected_error=None,305 ),306 EchoViaPagerTest(307 description="Generator function argument",308 test_input=lambda: _test_gen_func,309 expected_pager="abcabc\n",310 expected_stdout="",311 expected_stderr="",312 expected_error=None,313 ),314 EchoViaPagerTest(315 description="String generator argument",316 test_input=lambda: _test_gen_func(),317 expected_pager="abcabc\n",318 expected_stdout="",319 expected_stderr="",320 expected_error=None,321 ),322 EchoViaPagerTest(323 description="Number generator expression argument",324 test_input=lambda: (c for c in range(6)),325 expected_pager="012345\n",326 expected_stdout="",327 expected_stderr="",328 expected_error=None,329 ),330 EchoViaPagerTest(331 description="Exception in generator function argument",332 test_input=lambda: _test_gen_func_fails,333 # Because generator throws early on, the pager did not have334 # a chance yet to write the file.

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 335why, one step back
335 expected_pager="",

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

lines 336–344why, one step back
336 expected_stdout="",
337 expected_stderr="",338 expected_error=RuntimeError,339 ),340 EchoViaPagerTest(341 description="Exception in generator argument",342 test_input=lambda: _test_gen_func_fails,343 # Because generator throws early on, the pager did not have a344 # chance yet to write the file.

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 345why, one step back
345 expected_pager="",

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

lines 346–377why, one step back
346 expected_stdout="",
347 expected_stderr="",348 expected_error=RuntimeError,349 ),350 EchoViaPagerTest(351 description="Keyboard interrupt should not terminate the pager",352 test_input=lambda: _test_simulate_keyboard_interrupt(),353 # Due to the keyboard interrupt during pager execution, click program354 # should abort, but the pager should stay open.355 # This allows users to cancel the program and search in the pager356 # output, before they decide to terminate the pager.357 expected_pager="output_before_keyboard_interrupt",358 expected_stdout="",359 expected_stderr="",360 expected_error=KeyboardInterrupt,361 ),362 EchoViaPagerTest(363 description="Writing to stdout during generator execution",364 test_input=lambda: _test_gen_func_echo(),365 expected_pager="testtest\n",366 expected_stdout="hello\n",367 expected_stderr="",368 expected_error=None,369 ),370 EchoViaPagerTest(371 description="Writing to stderr during generator execution",372 test_input=lambda: _test_gen_func_echo(file=sys.stderr),373 expected_pager="testtest\n",374 expected_stdout="",375 expected_stderr="hello\n",376 expected_error=None,377 ),

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 378–379why, one step back
378 ],
379)

Fix pager test leaks (#3238)Rowlando13before adoption5df1001

line 380why, one step back
380def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 381why, one step back
381 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 382–383why, one step back
382 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)
383

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

lines 384–388why, one step back
384 test_input = test.test_input()
385 expected_pager = test.expected_pager386 expected_stdout = test.expected_stdout387 expected_stderr = test.expected_stderr388 expected_error = test.expected_error

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

line 389why, one step back
389

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 390why, one step back
390 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

line 391why, one step back
391

Fix pager test leaks (#3238)Rowlando13before adoption5df1001

line 392why, one step back
392 pager_out_tmp = tmp_path / "pager_out.txt"

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

lines 393–402why, one step back
393 with pager_out_tmp.open("w") as f:
394 force_subprocess_stdout = patch.object(395 subprocess,396 "Popen",397 partial(subprocess.Popen, stdout=f),398 )399 with force_subprocess_stdout:400 with check_raise:401 click.echo_via_pager(test_input)402

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

line 403why, one step back
403 out, err = capfd.readouterr()

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

line 404why, one step back
404

Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4

line 405why, one step back
405 pager = pager_out_tmp.read_text()

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

line 406why, one step back
406

update dev dependenciesDavid Lordbefore adoptionf14b750

lines 407–415why, one step back
407 assert pager == expected_pager, (
408 f"Unexpected pager output in test case '{test.description}'"409 )410 assert out == expected_stdout, (411 f"Unexpected stdout in test case '{test.description}'"412 )413 assert err == expected_stderr, (414 f"Unexpected stderr in test case '{test.description}'"415 )

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 416–439why, one step back
416
417418def test_echo_color_flag(monkeypatch, capfd):419 isatty = True420 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)421422 text = "foo"423 styled_text = click.style(text, fg="red")424 assert styled_text == "\x1b[31mfoo\x1b[0m"425426 click.echo(styled_text, color=False)427 out, err = capfd.readouterr()428 assert out == f"{text}\n"429430 click.echo(styled_text, color=True)431 out, err = capfd.readouterr()432 assert out == f"{styled_text}\n"433434 isatty = True435 click.echo(styled_text)436 out, err = capfd.readouterr()437 assert out == f"{styled_text}\n"438439 isatty = False

Merge stable into main (#2799)Rowlando13before adoptiond791537

lines 440–449why, one step back
440 # Faking isatty() is not enough on Windows;
441 # the implementation caches the colorama wrapped stream442 # so we have to use a new stream for each test443 stream = StringIO()444 click.echo(styled_text, file=stream)445 assert stream.getvalue() == f"{text}\n"446447 stream = StringIO()448 click.echo(styled_text, file=stream, color=True)449 assert stream.getvalue() == f"{styled_text}\n"

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 450–481why, one step back
450
451452def test_prompt_cast_default(capfd, monkeypatch):453 monkeypatch.setattr(sys, "stdin", StringIO("\n"))454 value = click.prompt("value", default="100", type=int)455 capfd.readouterr()456 assert isinstance(value, int)457458459@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")460def test_echo_writing_to_standard_error(capfd, monkeypatch):461 def emulate_input(text):462 """Emulate keyboard input."""463 monkeypatch.setattr(sys, "stdin", StringIO(text))464465 click.echo("Echo to standard output")466 out, err = capfd.readouterr()467 assert out == "Echo to standard output\n"468 assert err == ""469470 click.echo("Echo to standard error", err=True)471 out, err = capfd.readouterr()472 assert out == ""473 assert err == "Echo to standard error\n"474475 emulate_input("asdlkj\n")476 click.prompt("Prompt to stdin")477 out, err = capfd.readouterr()478 assert out == "Prompt to stdin: "479 assert err == ""480481 emulate_input("asdlkj\n")

Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96

lines 482–487why, one step back
482 click.prompt("Prompt to stdin with no suffix", prompt_suffix="")
483 out, err = capfd.readouterr()484 assert out == "Prompt to stdin with no suffix"485 assert err == ""486487 emulate_input("asdlkj\n")

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 488–492why, one step back
488 click.prompt("Prompt to stderr", err=True)
489 out, err = capfd.readouterr()490 assert out == " "491 assert err == "Prompt to stderr:"492

Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96

lines 493–498why, one step back
493 emulate_input("asdlkj\n")
494 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)495 out, err = capfd.readouterr()496 assert out == "x"497 assert err == "Prompt to stderr with no suffi"498

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 499–505why, one step back
499 emulate_input("y\n")
500 click.confirm("Prompt to stdin")501 out, err = capfd.readouterr()502 assert out == "Prompt to stdin [y/N]: "503 assert err == ""504505 emulate_input("y\n")

Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96

lines 506–511why, one step back
506 click.confirm("Prompt to stdin with no suffix", prompt_suffix="")
507 out, err = capfd.readouterr()508 assert out == "Prompt to stdin with no suffix [y/N]"509 assert err == ""510511 emulate_input("y\n")

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 512–515why, one step back
512 click.confirm("Prompt to stderr", err=True)
513 out, err = capfd.readouterr()514 assert out == " "515 assert err == "Prompt to stderr [y/N]:"

Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96

lines 516–521why, one step back
516
517 emulate_input("y\n")518 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)519 out, err = capfd.readouterr()520 assert out == "]"521 assert err == "Prompt to stderr with no suffix [y/N"

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 522–661why, one step back
522
523 monkeypatch.setattr(click.termui, "isatty", lambda x: True)524 monkeypatch.setattr(click.termui, "getchar", lambda: " ")525526 click.pause("Pause to stdout")527 out, err = capfd.readouterr()528 assert out == "Pause to stdout\n"529 assert err == ""530531 click.pause("Pause to stderr", err=True)532 out, err = capfd.readouterr()533 assert out == ""534 assert err == "Pause to stderr\n"535536537def test_echo_with_capsys(capsys):538 click.echo("Capture me.")539 out, err = capsys.readouterr()540 assert out == "Capture me.\n"541542543def test_open_file(runner):544 @click.command()545 @click.argument("filename")546 def cli(filename):547 with click.open_file(filename) as f:548 click.echo(f.read())549550 click.echo("meep")551552 with runner.isolated_filesystem():553 with open("hello.txt", "w") as f:554 f.write("Cool stuff")555556 result = runner.invoke(cli, ["hello.txt"])557 assert result.exception is None558 assert result.output == "Cool stuff\nmeep\n"559560 result = runner.invoke(cli, ["-"], input="foobar")561 assert result.exception is None562 assert result.output == "foobar\nmeep\n"563564565def test_open_file_pathlib_dash(runner):566 @click.command()567 @click.argument(568 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)569 )570 def cli(filename):571 click.echo(str(type(filename)))572573 with click.open_file(filename) as f:574 click.echo(f.read())575576 result = runner.invoke(cli, ["-"], input="value")577 assert result.exception is None578 assert result.output == "pathlib.Path\nvalue\n"579580581def test_open_file_ignore_errors_stdin(runner):582 @click.command()583 @click.argument("filename")584 def cli(filename):585 with click.open_file(filename, errors="ignore") as f:586 click.echo(f.read())587588 result = runner.invoke(cli, ["-"], input=os.urandom(16))589 assert result.exception is None590591592def test_open_file_respects_ignore(runner):593 with runner.isolated_filesystem():594 with open("test.txt", "w") as f:595 f.write("Hello world!")596597 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:598 assert f.errors == "ignore"599600601def test_open_file_ignore_invalid_utf8(runner):602 with runner.isolated_filesystem():603 with open("test.txt", "wb") as f:604 f.write(b"\xe2\x28\xa1")605606 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:607 f.read()608609610def test_open_file_ignore_no_encoding(runner):611 with runner.isolated_filesystem():612 with open("test.bin", "wb") as f:613 f.write(os.urandom(16))614615 with click.open_file("test.bin", errors="ignore") as f:616 f.read()617618619@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")620@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])621def test_open_file_atomic_permissions_existing_file(runner, permissions):622 with runner.isolated_filesystem():623 with open("existing.txt", "w") as f:624 f.write("content")625 os.chmod("existing.txt", permissions)626627 @click.command()628 @click.argument("filename")629 def cli(filename):630 click.open_file(filename, "w", atomic=True).close()631632 result = runner.invoke(cli, ["existing.txt"])633 assert result.exception is None634 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions635636637@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")638def test_open_file_atomic_permissions_new_file(runner):639 with runner.isolated_filesystem():640641 @click.command()642 @click.argument("filename")643 def cli(filename):644 click.open_file(filename, "w", atomic=True).close()645646 # Create a test file to get the expected permissions for new files647 # according to the current umask.648 with open("test.txt", "w"):649 pass650 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)651652 result = runner.invoke(cli, ["new.txt"])653 assert result.exception is None654 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions655656657def test_iter_keepopenfile(tmpdir):658 expected = list(map(str, range(10)))659 p = tmpdir.mkdir("testdir").join("testfile")660 p.write("\n".join(expected))661 with p.open() as f:

drop end of life python versions (#2893)David Lordbefore adoption498f882

line 662why, one step back
662 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 663–671why, one step back
663 assert e_line == a_line.strip()
664665666def test_iter_lazyfile(tmpdir):667 expected = list(map(str, range(10)))668 p = tmpdir.mkdir("testdir").join("testfile")669 p.write("\n".join(expected))670 with p.open() as f:671 with click.utils.LazyFile(f.name) as lf:

drop end of life python versions (#2893)David Lordbefore adoption498f882

line 672why, one step back
672 for e_line, a_line in zip(expected, lf, strict=False):

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 673–703why, one step back
673 assert e_line == a_line.strip()
674675676class MockMain:677 __slots__ = "__package__"678679 def __init__(self, package_name):680 self.__package__ = package_name681682683@pytest.mark.parametrize(684 ("path", "main", "expected"),685 [686 ("example.py", None, "example.py"),687 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),688 ("example", None, "example"),689 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),690 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),691 (str(pathlib.Path("./example")), "", "example"),692 ],693)694def test_detect_program_name(path, main, expected):695 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected696697698def test_expand_args(monkeypatch):699 user = os.path.expanduser("~")700 assert user in click.utils._expand_args(["~"])701 monkeypatch.setenv("CLICK_TEST", "hello")702 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])703 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])

Don't test using a file in docs/ (#3102)Rowlando13before adoptionea70da4

lines 704–706why, one step back
704 assert os.path.join("tests", "conftest.py") in click.utils._expand_args(
705 ["**/conftest.py"]706 )

use ruff lint and format (#2658)David Lordbefore adoption1a3baf7

lines 707–745why, one step back
707 assert "*.not-found" in click.utils._expand_args(["*.not-found"])
708 # a bad glob pattern, such as a pytest identifier, should return itself709 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"710711712@pytest.mark.parametrize(713 ("value", "max_length", "expect"),714 [715 pytest.param("", 10, "", id="empty"),716 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),717 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),718 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),719 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),720 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),721 pytest.param(722 "token in ~/.netrc ciao ciao",723 20,724 "token in ~/.netrc...",725 id="ignore dot in word",726 ),727 ],728)729@pytest.mark.parametrize(730 "alter",731 [732 pytest.param(None, id=""),733 pytest.param(734 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"735 ),736 ],737)738def test_make_default_short_help(value, max_length, alter, expect):739 assert len(expect) <= max_length740741 if alter:742 value = alter(value)743744 out = click.utils.make_default_short_help(value, max_length)745 assert out == expect