test_utils.py
This file
Path
tests/test_utils.py
384 lines · 11.5 KiB · Python
Last changed by
Merge pull request #1591 from andy-maier/andy/fix-unsupportedoperationDavid Lordbefore adoption090ff26
History of this fileTake it
1import os2import stat3import sys4from io import StringIO56import pytest78import click._termui_impl9import click.utils10from click._compat import WIN111213def test_echo(runner):14 with runner.isolation() as outstreams:15 click.echo("\N{SNOWMAN}")16 click.echo(b"\x44\x44")17 click.echo(42, nl=False)18 click.echo(b"a", nl=False)19 click.echo("\x1b[31mx\x1b[39m", nl=False)20 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")21 assert bytes == b"\xe2\x98\x83\nDD\n42ax"2223 # if wrapped, we expect bytes to survive.24 @click.command()25 def cli():26 click.echo(b"\xf6")2728 result = runner.invoke(cli, [])29 assert result.stdout_bytes == b"\xf6\n"3031 # Ensure we do not strip for bytes.32 with runner.isolation() as outstreams:33 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)34 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"353637def test_echo_custom_file():38 import io3940 f = io.StringIO()41 click.echo("hello", file=f)42 assert f.getvalue() == "hello\n"434445@pytest.mark.parametrize(46 ("styles", "ref"),47 [48 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),49 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),50 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),51 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),52 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),53 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),54 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),55 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),56 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),57 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),58 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),59 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),60 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),61 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),62 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),63 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),64 ({"blink": True}, "\x1b[5mx y\x1b[0m"),65 ({"underline": True}, "\x1b[4mx y\x1b[0m"),66 ({"bold": True}, "\x1b[1mx y\x1b[0m"),67 ({"dim": True}, "\x1b[2mx y\x1b[0m"),68 ],69)70def test_styling(styles, ref):71 assert click.style("x y", **styles) == ref72 assert click.unstyle(ref) == "x y"737475@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])76def test_unstyle_other_ansi(text, expect):77 assert click.unstyle(text) == expect787980def test_filename_formatting():81 assert click.format_filename(b"foo.txt") == "foo.txt"82 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"83 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"84 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"8586 # filesystem encoding on windows permits this.87 if not WIN:88 assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\ufffd.txt"899091def test_prompts(runner):92 @click.command()93 def test():94 if click.confirm("Foo"):95 click.echo("yes!")96 else:97 click.echo("no :(")9899 result = runner.invoke(test, input="y\n")100 assert not result.exception101 assert result.output == "Foo [y/N]: y\nyes!\n"102103 result = runner.invoke(test, input="\n")104 assert not result.exception105 assert result.output == "Foo [y/N]: \nno :(\n"106107 result = runner.invoke(test, input="n\n")108 assert not result.exception109 assert result.output == "Foo [y/N]: n\nno :(\n"110111 @click.command()112 def test_no():113 if click.confirm("Foo", default=True):114 click.echo("yes!")115 else:116 click.echo("no :(")117118 result = runner.invoke(test_no, input="y\n")119 assert not result.exception120 assert result.output == "Foo [Y/n]: y\nyes!\n"121122 result = runner.invoke(test_no, input="\n")123 assert not result.exception124 assert result.output == "Foo [Y/n]: \nyes!\n"125126 result = runner.invoke(test_no, input="n\n")127 assert not result.exception128 assert result.output == "Foo [Y/n]: n\nno :(\n"129130131@pytest.mark.skipif(WIN, reason="Different behavior on windows.")132def test_prompts_abort(monkeypatch, capsys):133 def f(_):134 raise KeyboardInterrupt()135136 monkeypatch.setattr("click.termui.hidden_prompt_func", f)137138 try:139 click.prompt("Password", hide_input=True)140 except click.Abort:141 click.echo("Screw you.")142143 out, err = capsys.readouterr()144 assert out == "Password: \nScrew you.\n"145146147def _test_gen_func():148 yield "a"149 yield "b"150 yield "c"151 yield "abc"152153154@pytest.mark.skipif(WIN, reason="Different behavior on windows.")155@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])156@pytest.mark.parametrize(157 "test",158 [159 # We need lambda here, because pytest will160 # reuse the parameters, and then the generators161 # are already used and will not yield anymore162 ("just text\n", lambda: "just text"),163 ("iterable\n", lambda: ["itera", "ble"]),164 ("abcabc\n", lambda: _test_gen_func),165 ("abcabc\n", lambda: _test_gen_func()),166 ("012345\n", lambda: (c for c in range(6))),167 ],168)169def test_echo_via_pager(monkeypatch, capfd, cat, test):170 monkeypatch.setitem(os.environ, "PAGER", cat)171 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)172173 expected_output = test[0]174 test_input = test[1]()175176 click.echo_via_pager(test_input)177178 out, err = capfd.readouterr()179 assert out == expected_output180181182@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")183def test_echo_color_flag(monkeypatch, capfd):184 isatty = True185 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)186187 text = "foo"188 styled_text = click.style(text, fg="red")189 assert styled_text == "\x1b[31mfoo\x1b[0m"190191 click.echo(styled_text, color=False)192 out, err = capfd.readouterr()193 assert out == f"{text}\n"194195 click.echo(styled_text, color=True)196 out, err = capfd.readouterr()197 assert out == f"{styled_text}\n"198199 isatty = True200 click.echo(styled_text)201 out, err = capfd.readouterr()202 assert out == f"{styled_text}\n"203204 isatty = False205 click.echo(styled_text)206 out, err = capfd.readouterr()207 assert out == f"{text}\n"208209210@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")211def test_echo_writing_to_standard_error(capfd, monkeypatch):212 def emulate_input(text):213 """Emulate keyboard input."""214 monkeypatch.setattr(sys, "stdin", StringIO(text))215216 click.echo("Echo to standard output")217 out, err = capfd.readouterr()218 assert out == "Echo to standard output\n"219 assert err == ""220221 click.echo("Echo to standard error", err=True)222 out, err = capfd.readouterr()223 assert out == ""224 assert err == "Echo to standard error\n"225226 emulate_input("asdlkj\n")227 click.prompt("Prompt to stdin")228 out, err = capfd.readouterr()229 assert out == "Prompt to stdin: "230 assert err == ""231232 emulate_input("asdlkj\n")233 click.prompt("Prompt to stderr", err=True)234 out, err = capfd.readouterr()235 assert out == ""236 assert err == "Prompt to stderr: "237238 emulate_input("y\n")239 click.confirm("Prompt to stdin")240 out, err = capfd.readouterr()241 assert out == "Prompt to stdin [y/N]: "242 assert err == ""243244 emulate_input("y\n")245 click.confirm("Prompt to stderr", err=True)246 out, err = capfd.readouterr()247 assert out == ""248 assert err == "Prompt to stderr [y/N]: "249250 monkeypatch.setattr(click.termui, "isatty", lambda x: True)251 monkeypatch.setattr(click.termui, "getchar", lambda: " ")252253 click.pause("Pause to stdout")254 out, err = capfd.readouterr()255 assert out == "Pause to stdout\n"256 assert err == ""257258 click.pause("Pause to stderr", err=True)259 out, err = capfd.readouterr()260 assert out == ""261 assert err == "Pause to stderr\n"262263264def test_echo_with_capsys(capsys):265 click.echo("Capture me.")266 out, err = capsys.readouterr()267 assert out == "Capture me.\n"268269270def test_open_file(runner):271 @click.command()272 @click.argument("filename")273 def cli(filename):274 with click.open_file(filename) as f:275 click.echo(f.read())276277 click.echo("meep")278279 with runner.isolated_filesystem():280 with open("hello.txt", "w") as f:281 f.write("Cool stuff")282283 result = runner.invoke(cli, ["hello.txt"])284 assert result.exception is None285 assert result.output == "Cool stuff\nmeep\n"286287 result = runner.invoke(cli, ["-"], input="foobar")288 assert result.exception is None289 assert result.output == "foobar\nmeep\n"290291292def test_open_file_ignore_errors_stdin(runner):293 @click.command()294 @click.argument("filename")295 def cli(filename):296 with click.open_file(filename, errors="ignore") as f:297 click.echo(f.read())298299 result = runner.invoke(cli, ["-"], input=os.urandom(16))300 assert result.exception is None301302303def test_open_file_respects_ignore(runner):304 with runner.isolated_filesystem():305 with open("test.txt", "w") as f:306 f.write("Hello world!")307308 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:309 assert f.errors == "ignore"310311312def test_open_file_ignore_invalid_utf8(runner):313 with runner.isolated_filesystem():314 with open("test.txt", "wb") as f:315 f.write(b"\xe2\x28\xa1")316317 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:318 f.read()319320321def test_open_file_ignore_no_encoding(runner):322 with runner.isolated_filesystem():323 with open("test.bin", "wb") as f:324 f.write(os.urandom(16))325326 with click.open_file("test.bin", errors="ignore") as f:327 f.read()328329330@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")331@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])332def test_open_file_atomic_permissions_existing_file(runner, permissions):333 with runner.isolated_filesystem():334 with open("existing.txt", "w") as f:335 f.write("content")336 os.chmod("existing.txt", permissions)337338 @click.command()339 @click.argument("filename")340 def cli(filename):341 click.open_file(filename, "w", atomic=True).close()342343 result = runner.invoke(cli, ["existing.txt"])344 assert result.exception is None345 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions346347348@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")349def test_open_file_atomic_permissions_new_file(runner):350 with runner.isolated_filesystem():351352 @click.command()353 @click.argument("filename")354 def cli(filename):355 click.open_file(filename, "w", atomic=True).close()356357 # Create a test file to get the expected permissions for new files358 # according to the current umask.359 with open("test.txt", "w"):360 pass361 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)362363 result = runner.invoke(cli, ["new.txt"])364 assert result.exception is None365 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions366367368def test_iter_keepopenfile(tmpdir):369 expected = list(map(str, range(10)))370 p = tmpdir.mkdir("testdir").join("testfile")371 p.write("\n".join(expected))372 with p.open() as f:373 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):374 assert e_line == a_line.strip()375376377def test_iter_lazyfile(tmpdir):378 expected = list(map(str, range(10)))379 p = tmpdir.mkdir("testdir").join("testfile")380 p.write("\n".join(expected))381 with p.open() as f:382 with click.utils.LazyFile(f.name) as lf:383 for e_line, a_line in zip(expected, lf):384 assert e_line == a_line.strip()