python-click/tests/test_utils.py

396 lines
12 KiB
Python
Raw Normal View History

2014-10-16 20:40:34 +02:00
import os
2020-07-21 08:23:42 +02:00
import stat
2014-10-16 20:40:34 +02:00
import sys
2015-08-23 03:10:31 +02:00
import pytest
2014-10-16 20:40:34 +02:00
import click._termui_impl
2020-07-21 08:23:42 +02:00
import click.utils
from click._compat import WIN
2014-10-16 20:40:34 +02:00
def test_echo(runner):
2018-09-06 20:55:10 +02:00
with runner.isolation() as outstreams:
2020-07-21 08:23:42 +02:00
click.echo(u"\N{SNOWMAN}")
click.echo(b"\x44\x44")
2014-10-16 20:40:34 +02:00
click.echo(42, nl=False)
2020-07-21 08:23:42 +02:00
click.echo(b"a", nl=False)
click.echo("\x1b[31mx\x1b[39m", nl=False)
bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")
assert bytes == b"\xe2\x98\x83\nDD\n42ax"
2014-10-16 20:40:34 +02:00
# If we are in Python 2, we expect that writing bytes into a string io
# does not do anything crazy. In Python 3
if sys.version_info[0] == 2:
import StringIO
2020-07-21 08:23:42 +02:00
2014-10-16 20:40:34 +02:00
sys.stdout = x = StringIO.StringIO()
try:
2020-07-21 08:23:42 +02:00
click.echo("\xf6")
2014-10-16 20:40:34 +02:00
finally:
sys.stdout = sys.__stdout__
2020-07-21 08:23:42 +02:00
assert x.getvalue() == "\xf6\n"
2014-10-16 20:40:34 +02:00
# And in any case, if wrapped, we expect bytes to survive.
@click.command()
def cli():
2020-07-21 08:23:42 +02:00
click.echo(b"\xf6")
2014-10-16 20:40:34 +02:00
result = runner.invoke(cli, [])
2020-07-21 08:23:42 +02:00
assert result.stdout_bytes == b"\xf6\n"
2014-10-16 20:40:34 +02:00
# Ensure we do not strip for bytes.
2018-09-06 20:55:10 +02:00
with runner.isolation() as outstreams:
2020-07-21 08:23:42 +02:00
click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)
assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"
2014-10-16 20:40:34 +02:00
2015-07-16 14:26:14 +02:00
def test_echo_custom_file():
import io
2020-07-21 08:23:42 +02:00
2015-07-16 14:26:14 +02:00
f = io.StringIO()
2020-07-21 08:23:42 +02:00
click.echo(u"hello", file=f)
assert f.getvalue() == u"hello\n"
@pytest.mark.parametrize(
("styles", "ref"),
[
({"fg": "black"}, "\x1b[30mx y\x1b[0m"),
({"fg": "red"}, "\x1b[31mx y\x1b[0m"),
({"fg": "green"}, "\x1b[32mx y\x1b[0m"),
({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),
({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),
({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),
({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),
({"fg": "white"}, "\x1b[37mx y\x1b[0m"),
({"bg": "black"}, "\x1b[40mx y\x1b[0m"),
({"bg": "red"}, "\x1b[41mx y\x1b[0m"),
({"bg": "green"}, "\x1b[42mx y\x1b[0m"),
({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),
({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),
({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),
({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),
({"bg": "white"}, "\x1b[47mx y\x1b[0m"),
({"blink": True}, "\x1b[5mx y\x1b[0m"),
({"underline": True}, "\x1b[4mx y\x1b[0m"),
({"bold": True}, "\x1b[1mx y\x1b[0m"),
({"dim": True}, "\x1b[2mx y\x1b[0m"),
],
)
def test_styling(styles, ref):
assert click.style("x y", **styles) == ref
assert click.unstyle(ref) == "x y"
@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])
def test_unstyle_other_ansi(text, expect):
assert click.unstyle(text) == expect
2014-10-16 20:40:34 +02:00
def test_filename_formatting():
2020-07-21 08:23:42 +02:00
assert click.format_filename(b"foo.txt") == "foo.txt"
assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"
assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"
assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt"
2015-12-04 16:51:02 +01:00
# filesystem encoding on windows permits this.
if not WIN:
2020-07-21 08:23:42 +02:00
assert (
click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"
)
2014-10-16 20:40:34 +02:00
def test_prompts(runner):
@click.command()
def test():
2020-07-21 08:23:42 +02:00
if click.confirm("Foo"):
click.echo("yes!")
2014-10-16 20:40:34 +02:00
else:
2020-07-21 08:23:42 +02:00
click.echo("no :(")
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(test, input="y\n")
2014-10-16 20:40:34 +02:00
assert not result.exception
2020-07-21 08:23:42 +02:00
assert result.output == "Foo [y/N]: y\nyes!\n"
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(test, input="\n")
2014-10-16 20:40:34 +02:00
assert not result.exception
2020-07-21 08:23:42 +02:00
assert result.output == "Foo [y/N]: \nno :(\n"
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(test, input="n\n")
2014-10-16 20:40:34 +02:00
assert not result.exception
2020-07-21 08:23:42 +02:00
assert result.output == "Foo [y/N]: n\nno :(\n"
2014-10-16 20:40:34 +02:00
@click.command()
def test_no():
2020-07-21 08:23:42 +02:00
if click.confirm("Foo", default=True):
click.echo("yes!")
2014-10-16 20:40:34 +02:00
else:
2020-07-21 08:23:42 +02:00
click.echo("no :(")
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(test_no, input="y\n")
2014-10-16 20:40:34 +02:00
assert not result.exception
2020-07-21 08:23:42 +02:00
assert result.output == "Foo [Y/n]: y\nyes!\n"
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(test_no, input="\n")
2014-10-16 20:40:34 +02:00
assert not result.exception
2020-07-21 08:23:42 +02:00
assert result.output == "Foo [Y/n]: \nyes!\n"
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(test_no, input="n\n")
2014-10-16 20:40:34 +02:00
assert not result.exception
2020-07-21 08:23:42 +02:00
assert result.output == "Foo [Y/n]: n\nno :(\n"
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
@pytest.mark.skipif(WIN, reason="Different behavior on windows.")
2015-08-23 03:10:31 +02:00
def test_prompts_abort(monkeypatch, capsys):
def f(_):
raise KeyboardInterrupt()
2020-07-21 08:23:42 +02:00
monkeypatch.setattr("click.termui.hidden_prompt_func", f)
2015-08-23 03:10:31 +02:00
try:
2020-07-21 08:23:42 +02:00
click.prompt("Password", hide_input=True)
2015-08-23 03:10:31 +02:00
except click.Abort:
2020-07-21 08:23:42 +02:00
click.echo("Screw you.")
2015-08-23 03:10:31 +02:00
out, err = capsys.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "Password: \nScrew you.\n"
2015-08-23 03:10:31 +02:00
2018-09-06 20:55:10 +02:00
def _test_gen_func():
2020-07-21 08:23:42 +02:00
yield "a"
yield "b"
yield "c"
yield "abc"
@pytest.mark.skipif(WIN, reason="Different behavior on windows.")
@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])
@pytest.mark.parametrize(
"test",
[
# We need lambda here, because pytest will
# reuse the parameters, and then the generators
# are already used and will not yield anymore
("just text\n", lambda: "just text"),
("iterable\n", lambda: ["itera", "ble"]),
("abcabc\n", lambda: _test_gen_func),
("abcabc\n", lambda: _test_gen_func()),
("012345\n", lambda: (c for c in range(6))),
],
)
2018-09-06 20:55:10 +02:00
def test_echo_via_pager(monkeypatch, capfd, cat, test):
2020-07-21 08:23:42 +02:00
monkeypatch.setitem(os.environ, "PAGER", cat)
monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)
2018-09-06 20:55:10 +02:00
expected_output = test[0]
test_input = test[1]()
click.echo_via_pager(test_input)
2014-10-16 20:40:34 +02:00
out, err = capfd.readouterr()
2018-09-06 20:55:10 +02:00
assert out == expected_output
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")
2015-07-16 14:26:14 +02:00
def test_echo_color_flag(monkeypatch, capfd):
isatty = True
2020-07-21 08:23:42 +02:00
monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
text = "foo"
styled_text = click.style(text, fg="red")
assert styled_text == "\x1b[31mfoo\x1b[0m"
2015-07-16 14:26:14 +02:00
click.echo(styled_text, color=False)
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "{}\n".format(text)
2015-07-16 14:26:14 +02:00
click.echo(styled_text, color=True)
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "{}\n".format(styled_text)
2015-07-16 14:26:14 +02:00
isatty = True
click.echo(styled_text)
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "{}\n".format(styled_text)
2015-07-16 14:26:14 +02:00
isatty = False
click.echo(styled_text)
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "{}\n".format(text)
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")
2015-07-16 14:26:14 +02:00
def test_echo_writing_to_standard_error(capfd, monkeypatch):
def emulate_input(text):
"""Emulate keyboard input."""
if sys.version_info[0] == 2:
from StringIO import StringIO
else:
from io import StringIO
2020-07-21 08:23:42 +02:00
monkeypatch.setattr(sys, "stdin", StringIO(text))
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
click.echo("Echo to standard output")
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "Echo to standard output\n"
assert err == ""
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
click.echo("Echo to standard error", err=True)
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == ""
assert err == "Echo to standard error\n"
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
emulate_input("asdlkj\n")
click.prompt("Prompt to stdin")
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "Prompt to stdin: "
assert err == ""
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
emulate_input("asdlkj\n")
click.prompt("Prompt to stderr", err=True)
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == ""
assert err == "Prompt to stderr: "
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
emulate_input("y\n")
click.confirm("Prompt to stdin")
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "Prompt to stdin [y/N]: "
assert err == ""
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
emulate_input("y\n")
click.confirm("Prompt to stderr", err=True)
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == ""
assert err == "Prompt to stderr [y/N]: "
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
monkeypatch.setattr(click.termui, "isatty", lambda x: True)
monkeypatch.setattr(click.termui, "getchar", lambda: " ")
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
click.pause("Pause to stdout")
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == "Pause to stdout\n"
assert err == ""
2015-07-16 14:26:14 +02:00
2020-07-21 08:23:42 +02:00
click.pause("Pause to stderr", err=True)
2015-07-16 14:26:14 +02:00
out, err = capfd.readouterr()
2020-07-21 08:23:42 +02:00
assert out == ""
assert err == "Pause to stderr\n"
2015-07-16 14:26:14 +02:00
2014-10-16 20:40:34 +02:00
def test_open_file(runner):
2020-07-21 08:23:42 +02:00
@click.command()
@click.argument("filename")
def cli(filename):
with click.open_file(filename) as f:
click.echo(f.read())
click.echo("meep")
with runner.isolated_filesystem():
with open("hello.txt", "w") as f:
f.write("Cool stuff")
result = runner.invoke(cli, ["hello.txt"])
assert result.exception is None
assert result.output == "Cool stuff\nmeep\n"
result = runner.invoke(cli, ["-"], input="foobar")
assert result.exception is None
assert result.output == "foobar\nmeep\n"
def test_open_file_ignore_errors_stdin(runner):
@click.command()
@click.argument("filename")
def cli(filename):
with click.open_file(filename, errors="ignore") as f:
click.echo(f.read())
result = runner.invoke(cli, ["-"], input=os.urandom(16))
assert result.exception is None
def test_open_file_respects_ignore(runner):
2014-10-16 20:40:34 +02:00
with runner.isolated_filesystem():
2020-07-21 08:23:42 +02:00
with open("test.txt", "w") as f:
f.write("Hello world!")
with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:
assert f.errors == "ignore"
def test_open_file_ignore_invalid_utf8(runner):
with runner.isolated_filesystem():
with open("test.txt", "wb") as f:
f.write(b"\xe2\x28\xa1")
with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:
f.read()
def test_open_file_ignore_no_encoding(runner):
with runner.isolated_filesystem():
with open("test.bin", "wb") as f:
f.write(os.urandom(16))
with click.open_file("test.bin", errors="ignore") as f:
f.read()
@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")
@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])
def test_open_file_atomic_permissions_existing_file(runner, permissions):
with runner.isolated_filesystem():
with open("existing.txt", "w") as f:
f.write("content")
os.chmod("existing.txt", permissions)
2014-10-16 20:40:34 +02:00
@click.command()
2020-07-21 08:23:42 +02:00
@click.argument("filename")
2014-10-16 20:40:34 +02:00
def cli(filename):
2020-07-21 08:23:42 +02:00
click.open_file(filename, "w", atomic=True).close()
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(cli, ["existing.txt"])
2014-10-16 20:40:34 +02:00
assert result.exception is None
2020-07-21 08:23:42 +02:00
assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions
@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")
def test_open_file_atomic_permissions_new_file(runner):
with runner.isolated_filesystem():
@click.command()
@click.argument("filename")
def cli(filename):
click.open_file(filename, "w", atomic=True).close()
# Create a test file to get the expected permissions for new files
# according to the current umask.
with open("test.txt", "w"):
pass
permissions = stat.S_IMODE(os.stat("test.txt").st_mode)
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
result = runner.invoke(cli, ["new.txt"])
2014-10-16 20:40:34 +02:00
assert result.exception is None
2020-07-21 08:23:42 +02:00
assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions
2015-08-23 03:10:31 +02:00
def test_iter_keepopenfile(tmpdir):
expected = list(map(str, range(10)))
2020-07-21 08:23:42 +02:00
p = tmpdir.mkdir("testdir").join("testfile")
p.write("\n".join(expected))
2018-09-06 20:55:10 +02:00
with p.open() as f:
for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):
assert e_line == a_line.strip()
2015-08-23 03:10:31 +02:00
def test_iter_lazyfile(tmpdir):
expected = list(map(str, range(10)))
2020-07-21 08:23:42 +02:00
p = tmpdir.mkdir("testdir").join("testfile")
p.write("\n".join(expected))
2018-09-06 20:55:10 +02:00
with p.open() as f:
with click.utils.LazyFile(f.name) as lf:
for e_line, a_line in zip(expected, lf):
assert e_line == a_line.strip()