| 1 |
import os |
| 2 |
import pathlib |
| 3 |
import stat |
| 4 |
import subprocess |
| 5 |
import sys |
| 6 |
from collections import namedtuple |
| 7 |
from contextlib import nullcontext |
| 8 |
from decimal import Decimal |
| 9 |
from fractions import Fraction |
| 10 |
from functools import partial |
| 11 |
from io import StringIO |
| 12 |
from unittest.mock import patch |
| 13 |
|
| 14 |
import pytest |
| 15 |
|
| 16 |
import click._termui_impl |
| 17 |
import click.utils |
| 18 |
from click._compat import WIN |
| 19 |
from click._utils import UNSET |
| 20 |
|
| 21 |
|
| 22 |
def test_unset_sentinel(): |
| 23 |
value = UNSET |
| 24 |
|
| 25 |
assert value |
| 26 |
assert value is UNSET |
| 27 |
assert value == UNSET |
| 28 |
assert repr(value) == "Sentinel.UNSET" |
| 29 |
assert str(value) == "Sentinel.UNSET" |
| 30 |
assert bool(value) is True |
| 31 |
|
| 32 |
# Try all native Python values that can be falsy or truthy. |
| 33 |
# See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing |
| 34 |
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 |
) |
| 62 |
|
| 63 |
for real_value in real_values: |
| 64 |
assert value != real_value |
| 65 |
assert value is not real_value |
| 66 |
|
| 67 |
assert value not in real_values |
| 68 |
|
| 69 |
|
| 70 |
def 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" |
| 79 |
|
| 80 |
# if wrapped, we expect bytes to survive. |
| 81 |
@click.command() |
| 82 |
def cli(): |
| 83 |
click.echo(b"\xf6") |
| 84 |
|
| 85 |
result = runner.invoke(cli, []) |
| 86 |
assert result.stdout_bytes == b"\xf6\n" |
| 87 |
|
| 88 |
# 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" |
| 92 |
|
| 93 |
|
| 94 |
def test_echo_custom_file(): |
| 95 |
f = StringIO() |
| 96 |
click.echo("hello", file=f) |
| 97 |
assert f.getvalue() == "hello\n" |
| 98 |
|
| 99 |
|
| 100 |
def 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 = None |
| 104 |
sys.stderr = None |
| 105 |
click.echo("test") |
| 106 |
click.echo("test", err=True) |
| 107 |
|
| 108 |
|
| 109 |
@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 |
) |
| 149 |
def test_styling(styles, ref): |
| 150 |
assert click.style("x y", **styles) == ref |
| 151 |
assert click.unstyle(ref) == "x y" |
| 152 |
|
| 153 |
|
| 154 |
@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")]) |
| 155 |
def test_unstyle_other_ansi(text, expect): |
| 156 |
assert click.unstyle(text) == expect |
| 157 |
|
| 158 |
|
| 159 |
def 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" |
| 164 |
assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt" |
| 165 |
|
| 166 |
|
| 167 |
def test_prompts(runner): |
| 168 |
@click.command() |
| 169 |
def test(): |
| 170 |
if click.confirm("Foo"): |
| 171 |
click.echo("yes!") |
| 172 |
else: |
| 173 |
click.echo("no :(") |
| 174 |
|
| 175 |
result = runner.invoke(test, input="y\n") |
| 176 |
assert not result.exception |
| 177 |
assert result.output == "Foo [y/N]: y\nyes!\n" |
| 178 |
|
| 179 |
result = runner.invoke(test, input="\n") |
| 180 |
assert not result.exception |
| 181 |
assert result.output == "Foo [y/N]: \nno :(\n" |
| 182 |
|
| 183 |
result = runner.invoke(test, input="n\n") |
| 184 |
assert not result.exception |
| 185 |
assert result.output == "Foo [y/N]: n\nno :(\n" |
| 186 |
|
| 187 |
@click.command() |
| 188 |
def test_no(): |
| 189 |
if click.confirm("Foo", default=True): |
| 190 |
click.echo("yes!") |
| 191 |
else: |
| 192 |
click.echo("no :(") |
| 193 |
|
| 194 |
result = runner.invoke(test_no, input="y\n") |
| 195 |
assert not result.exception |
| 196 |
assert result.output == "Foo [Y/n]: y\nyes!\n" |
| 197 |
|
| 198 |
result = runner.invoke(test_no, input="\n") |
| 199 |
assert not result.exception |
| 200 |
assert result.output == "Foo [Y/n]: \nyes!\n" |
| 201 |
|
| 202 |
result = runner.invoke(test_no, input="n\n") |
| 203 |
assert not result.exception |
| 204 |
assert result.output == "Foo [Y/n]: n\nno :(\n" |
| 205 |
|
| 206 |
|
| 207 |
def 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" |
| 213 |
|
| 214 |
|
| 215 |
@pytest.mark.skipif(WIN, reason="Different behavior on windows.") |
| 216 |
def test_prompts_abort(monkeypatch, capsys): |
| 217 |
def f(_): |
| 218 |
raise KeyboardInterrupt() |
| 219 |
|
| 220 |
monkeypatch.setattr("click.termui.hidden_prompt_func", f) |
| 221 |
|
| 222 |
try: |
| 223 |
click.prompt("Password", hide_input=True) |
| 224 |
except click.Abort: |
| 225 |
click.echo("interrupted") |
| 226 |
|
| 227 |
out, err = capsys.readouterr() |
| 228 |
assert out == "Password:\ninterrupted\n" |
| 229 |
|
| 230 |
|
| 231 |
def test_prompts_eof(runner): |
| 232 |
"""If too few lines of input are given, prompt should exit, not hang.""" |
| 233 |
|
| 234 |
@click.command |
| 235 |
def echo(): |
| 236 |
for _ in range(3): |
| 237 |
click.echo(click.prompt("", type=int)) |
| 238 |
|
| 239 |
# only provide two lines of input for three prompts |
| 240 |
result = runner.invoke(echo, input="1\n2\n") |
| 241 |
assert result.exit_code == 1 |
| 242 |
|
| 243 |
|
| 244 |
def _test_gen_func(): |
| 245 |
yield "a" |
| 246 |
yield "b" |
| 247 |
yield "c" |
| 248 |
yield "abc" |
| 249 |
|
| 250 |
|
| 251 |
def _test_gen_func_fails(): |
| 252 |
yield "test" |
| 253 |
raise RuntimeError("This is a test.") |
| 254 |
|
| 255 |
|
| 256 |
def _test_gen_func_echo(file=None): |
| 257 |
yield "test" |
| 258 |
click.echo("hello", file=file) |
| 259 |
yield "test" |
| 260 |
|
| 261 |
|
| 262 |
def _test_simulate_keyboard_interrupt(file=None): |
| 263 |
yield "output_before_keyboard_interrupt" |
| 264 |
raise KeyboardInterrupt() |
| 265 |
|
| 266 |
|
| 267 |
EchoViaPagerTest = namedtuple( |
| 268 |
"EchoViaPagerTest", |
| 269 |
( |
| 270 |
"description", |
| 271 |
"test_input", |
| 272 |
"expected_pager", |
| 273 |
"expected_stdout", |
| 274 |
"expected_stderr", |
| 275 |
"expected_error", |
| 276 |
), |
| 277 |
) |
| 278 |
|
| 279 |
|
| 280 |
@pytest.mark.skipif(WIN, reason="Different behavior on windows.") |
| 281 |
@pytest.mark.parametrize( |
| 282 |
"pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "] |
| 283 |
) |
| 284 |
@pytest.mark.parametrize( |
| 285 |
"test", |
| 286 |
[ |
| 287 |
# We need to pass a parameter function instead of a plain param |
| 288 |
# as pytest.mark.parametrize will reuse the parameters causing the |
| 289 |
# generators to be used up so they will not yield anymore |
| 290 |
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 have |
| 334 |
# a chance yet to write the file. |
| 335 |
expected_pager="", |
| 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 a |
| 344 |
# chance yet to write the file. |
| 345 |
expected_pager="", |
| 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 program |
| 354 |
# should abort, but the pager should stay open. |
| 355 |
# This allows users to cancel the program and search in the pager |
| 356 |
# 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 |
), |
| 378 |
], |
| 379 |
) |
| 380 |
def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path): |
| 381 |
monkeypatch.setitem(os.environ, "PAGER", pager_cmd) |
| 382 |
monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True) |
| 383 |
|
| 384 |
test_input = test.test_input() |
| 385 |
expected_pager = test.expected_pager |
| 386 |
expected_stdout = test.expected_stdout |
| 387 |
expected_stderr = test.expected_stderr |
| 388 |
expected_error = test.expected_error |
| 389 |
|
| 390 |
check_raise = pytest.raises(expected_error) if expected_error else nullcontext() |
| 391 |
|
| 392 |
pager_out_tmp = tmp_path / "pager_out.txt" |
| 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 |
|
| 403 |
out, err = capfd.readouterr() |
| 404 |
|
| 405 |
pager = pager_out_tmp.read_text() |
| 406 |
|
| 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 |
) |
| 416 |
|
| 417 |
|
| 418 |
def test_echo_color_flag(monkeypatch, capfd): |
| 419 |
isatty = True |
| 420 |
monkeypatch.setattr(click._compat, "isatty", lambda x: isatty) |
| 421 |
|
| 422 |
text = "foo" |
| 423 |
styled_text = click.style(text, fg="red") |
| 424 |
assert styled_text == "\x1b[31mfoo\x1b[0m" |
| 425 |
|
| 426 |
click.echo(styled_text, color=False) |
| 427 |
out, err = capfd.readouterr() |
| 428 |
assert out == f"{text}\n" |
| 429 |
|
| 430 |
click.echo(styled_text, color=True) |
| 431 |
out, err = capfd.readouterr() |
| 432 |
assert out == f"{styled_text}\n" |
| 433 |
|
| 434 |
isatty = True |
| 435 |
click.echo(styled_text) |
| 436 |
out, err = capfd.readouterr() |
| 437 |
assert out == f"{styled_text}\n" |
| 438 |
|
| 439 |
isatty = False |
| 440 |
# Faking isatty() is not enough on Windows; |
| 441 |
# the implementation caches the colorama wrapped stream |
| 442 |
# so we have to use a new stream for each test |
| 443 |
stream = StringIO() |
| 444 |
click.echo(styled_text, file=stream) |
| 445 |
assert stream.getvalue() == f"{text}\n" |
| 446 |
|
| 447 |
stream = StringIO() |
| 448 |
click.echo(styled_text, file=stream, color=True) |
| 449 |
assert stream.getvalue() == f"{styled_text}\n" |
| 450 |
|
| 451 |
|
| 452 |
def 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) |
| 457 |
|
| 458 |
|
| 459 |
@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.") |
| 460 |
def test_echo_writing_to_standard_error(capfd, monkeypatch): |
| 461 |
def emulate_input(text): |
| 462 |
"""Emulate keyboard input.""" |
| 463 |
monkeypatch.setattr(sys, "stdin", StringIO(text)) |
| 464 |
|
| 465 |
click.echo("Echo to standard output") |
| 466 |
out, err = capfd.readouterr() |
| 467 |
assert out == "Echo to standard output\n" |
| 468 |
assert err == "" |
| 469 |
|
| 470 |
click.echo("Echo to standard error", err=True) |
| 471 |
out, err = capfd.readouterr() |
| 472 |
assert out == "" |
| 473 |
assert err == "Echo to standard error\n" |
| 474 |
|
| 475 |
emulate_input("asdlkj\n") |
| 476 |
click.prompt("Prompt to stdin") |
| 477 |
out, err = capfd.readouterr() |
| 478 |
assert out == "Prompt to stdin: " |
| 479 |
assert err == "" |
| 480 |
|
| 481 |
emulate_input("asdlkj\n") |
| 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 == "" |
| 486 |
|
| 487 |
emulate_input("asdlkj\n") |
| 488 |
click.prompt("Prompt to stderr", err=True) |
| 489 |
out, err = capfd.readouterr() |
| 490 |
assert out == " " |
| 491 |
assert err == "Prompt to stderr:" |
| 492 |
|
| 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 |
|
| 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 == "" |
| 504 |
|
| 505 |
emulate_input("y\n") |
| 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 == "" |
| 510 |
|
| 511 |
emulate_input("y\n") |
| 512 |
click.confirm("Prompt to stderr", err=True) |
| 513 |
out, err = capfd.readouterr() |
| 514 |
assert out == " " |
| 515 |
assert err == "Prompt to stderr [y/N]:" |
| 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" |
| 522 |
|
| 523 |
monkeypatch.setattr(click.termui, "isatty", lambda x: True) |
| 524 |
monkeypatch.setattr(click.termui, "getchar", lambda: " ") |
| 525 |
|
| 526 |
click.pause("Pause to stdout") |
| 527 |
out, err = capfd.readouterr() |
| 528 |
assert out == "Pause to stdout\n" |
| 529 |
assert err == "" |
| 530 |
|
| 531 |
click.pause("Pause to stderr", err=True) |
| 532 |
out, err = capfd.readouterr() |
| 533 |
assert out == "" |
| 534 |
assert err == "Pause to stderr\n" |
| 535 |
|
| 536 |
|
| 537 |
def test_echo_with_capsys(capsys): |
| 538 |
click.echo("Capture me.") |
| 539 |
out, err = capsys.readouterr() |
| 540 |
assert out == "Capture me.\n" |
| 541 |
|
| 542 |
|
| 543 |
def 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()) |
| 549 |
|
| 550 |
click.echo("meep") |
| 551 |
|
| 552 |
with runner.isolated_filesystem(): |
| 553 |
with open("hello.txt", "w") as f: |
| 554 |
f.write("Cool stuff") |
| 555 |
|
| 556 |
result = runner.invoke(cli, ["hello.txt"]) |
| 557 |
assert result.exception is None |
| 558 |
assert result.output == "Cool stuff\nmeep\n" |
| 559 |
|
| 560 |
result = runner.invoke(cli, ["-"], input="foobar") |
| 561 |
assert result.exception is None |
| 562 |
assert result.output == "foobar\nmeep\n" |
| 563 |
|
| 564 |
|
| 565 |
def 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))) |
| 572 |
|
| 573 |
with click.open_file(filename) as f: |
| 574 |
click.echo(f.read()) |
| 575 |
|
| 576 |
result = runner.invoke(cli, ["-"], input="value") |
| 577 |
assert result.exception is None |
| 578 |
assert result.output == "pathlib.Path\nvalue\n" |
| 579 |
|
| 580 |
|
| 581 |
def 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()) |
| 587 |
|
| 588 |
result = runner.invoke(cli, ["-"], input=os.urandom(16)) |
| 589 |
assert result.exception is None |
| 590 |
|
| 591 |
|
| 592 |
def test_open_file_respects_ignore(runner): |
| 593 |
with runner.isolated_filesystem(): |
| 594 |
with open("test.txt", "w") as f: |
| 595 |
f.write("Hello world!") |
| 596 |
|
| 597 |
with click.open_file("test.txt", encoding="utf8", errors="ignore") as f: |
| 598 |
assert f.errors == "ignore" |
| 599 |
|
| 600 |
|
| 601 |
def 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") |
| 605 |
|
| 606 |
with click.open_file("test.txt", encoding="utf8", errors="ignore") as f: |
| 607 |
f.read() |
| 608 |
|
| 609 |
|
| 610 |
def 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)) |
| 614 |
|
| 615 |
with click.open_file("test.bin", errors="ignore") as f: |
| 616 |
f.read() |
| 617 |
|
| 618 |
|
| 619 |
@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.") |
| 620 |
@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644]) |
| 621 |
def 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) |
| 626 |
|
| 627 |
@click.command() |
| 628 |
@click.argument("filename") |
| 629 |
def cli(filename): |
| 630 |
click.open_file(filename, "w", atomic=True).close() |
| 631 |
|
| 632 |
result = runner.invoke(cli, ["existing.txt"]) |
| 633 |
assert result.exception is None |
| 634 |
assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions |
| 635 |
|
| 636 |
|
| 637 |
@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.") |
| 638 |
def test_open_file_atomic_permissions_new_file(runner): |
| 639 |
with runner.isolated_filesystem(): |
| 640 |
|
| 641 |
@click.command() |
| 642 |
@click.argument("filename") |
| 643 |
def cli(filename): |
| 644 |
click.open_file(filename, "w", atomic=True).close() |
| 645 |
|
| 646 |
# Create a test file to get the expected permissions for new files |
| 647 |
# according to the current umask. |
| 648 |
with open("test.txt", "w"): |
| 649 |
pass |
| 650 |
permissions = stat.S_IMODE(os.stat("test.txt").st_mode) |
| 651 |
|
| 652 |
result = runner.invoke(cli, ["new.txt"]) |
| 653 |
assert result.exception is None |
| 654 |
assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions |
| 655 |
|
| 656 |
|
| 657 |
def 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: |
| 662 |
for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False): |
| 663 |
assert e_line == a_line.strip() |
| 664 |
|
| 665 |
|
| 666 |
def 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: |
| 672 |
for e_line, a_line in zip(expected, lf, strict=False): |
| 673 |
assert e_line == a_line.strip() |
| 674 |
|
| 675 |
|
| 676 |
class MockMain: |
| 677 |
__slots__ = "__package__" |
| 678 |
|
| 679 |
def __init__(self, package_name): |
| 680 |
self.__package__ = package_name |
| 681 |
|
| 682 |
|
| 683 |
@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 |
) |
| 694 |
def test_detect_program_name(path, main, expected): |
| 695 |
assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected |
| 696 |
|
| 697 |
|
| 698 |
def 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"]) |
| 704 |
assert os.path.join("tests", "conftest.py") in click.utils._expand_args( |
| 705 |
["**/conftest.py"] |
| 706 |
) |
| 707 |
assert "*.not-found" in click.utils._expand_args(["*.not-found"]) |
| 708 |
# a bad glob pattern, such as a pytest identifier, should return itself |
| 709 |
assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad" |
| 710 |
|
| 711 |
|
| 712 |
@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 |
) |
| 738 |
def test_make_default_short_help(value, max_length, alter, expect): |
| 739 |
assert len(expect) <= max_length |
| 740 |
|
| 741 |
if alter: |
| 742 |
value = alter(value) |
| 743 |
|
| 744 |
out = click.utils.make_default_short_help(value, max_length) |
| 745 |
assert out == expect |