Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

399 lines · 11.8 KiB · Python

Last changed by

Merge pull request #1298 from joewledger/fix_958David Lordbefore adoption9ea9666

History of this file

Take it

The walk stopped after 200 commits: lines older than 430c50a point at it.

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

line 1why, one step back
1import os

Merge pull request #1400 from andersk/atomic-open-permissionsDavid Lordbefore adoptione0ad5a6

line 2why, one step back
2import stat

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 3–13why, one step back
3import sys
45import pytest67import click8import click.utils9import click._termui_impl10from click._compat import WIN, PY2111213def test_echo(runner):

CliRunner: add stdout / stderr, allow separating standard streams (#868)Dave Carlsonbefore adoptionfdceb39

line 14why, one step back
14 with runner.isolation() as outstreams:

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 15–19why, one step back
15 click.echo(u'\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)

CliRunner: add stdout / stderr, allow separating standard streams (#868)Dave Carlsonbefore adoptionfdceb39

line 20why, one step back
20 bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 21–38why, one step back
21 assert bytes == b'\xe2\x98\x83\nDD\n42ax'
2223 # If we are in Python 2, we expect that writing bytes into a string io24 # does not do anything crazy. In Python 325 if sys.version_info[0] == 2:26 import StringIO27 sys.stdout = x = StringIO.StringIO()28 try:29 click.echo('\xf6')30 finally:31 sys.stdout = sys.__stdout__32 assert x.getvalue() == '\xf6\n'3334 # And in any case, if wrapped, we expect bytes to survive.35 @click.command()36 def cli():37 click.echo(b'\xf6')38 result = runner.invoke(cli, [])

CliRunner: add stdout / stderr, allow separating standard streams (#868)Dave Carlsonbefore adoptionfdceb39

line 39why, one step back
39 assert result.stdout_bytes == b'\xf6\n'

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 40–41why, one step back
40
41 # Ensure we do not strip for bytes.

CliRunner: add stdout / stderr, allow separating standard streams (#868)Dave Carlsonbefore adoptionfdceb39

line 42why, one step back
42 with runner.isolation() as outstreams:

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

line 43why, one step back
43 click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)

CliRunner: add stdout / stderr, allow separating standard streams (#868)Dave Carlsonbefore adoptionfdceb39

line 44why, one step back
44 assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 45–53why, one step back
45
4647def test_echo_custom_file():48 import io49 f = io.StringIO()50 click.echo(u'hello', file=f)51 assert f.getvalue() == u'hello\n'5253

Merge pull request #1299 from sekenned/7.xDavid Lordbefore adoption278a054

lines 54–87why, one step back
54@pytest.mark.parametrize(
55 ("styles", "ref"),56 [57 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),58 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),59 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),60 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),61 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),62 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),63 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),64 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),65 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),66 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),67 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),68 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),69 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),70 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),71 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),72 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),73 ({"blink": True}, "\x1b[5mx y\x1b[0m"),74 ({"underline": True}, "\x1b[4mx y\x1b[0m"),75 ({"bold": True}, "\x1b[1mx y\x1b[0m"),76 ({"dim": True}, "\x1b[2mx y\x1b[0m"),77 ],78)79def test_styling(styles, ref):80 assert click.style("x y", **styles) == ref81 assert click.unstyle(ref) == "x y"828384@pytest.mark.parametrize(85 ("text", "expect"),86 [87 ("\x1b[?25lx y\x1b[?25h", "x y"),

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

line 88why, one step back
88 ]

Merge pull request #1299 from sekenned/7.xDavid Lordbefore adoption278a054

lines 89–92why, one step back
89)
90def test_unstyle_other_ansi(text, expect):91 assert click.unstyle(text) == expect92

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 93–162why, one step back
93
9495def test_filename_formatting():96 assert click.format_filename(b'foo.txt') == 'foo.txt'97 assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'98 assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'99 assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt'100101 # filesystem encoding on windows permits this.102 if not WIN:103 assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \104 == u'foo\ufffd.txt'105106107def test_prompts(runner):108 @click.command()109 def test():110 if click.confirm('Foo'):111 click.echo('yes!')112 else:113 click.echo('no :(')114115 result = runner.invoke(test, input='y\n')116 assert not result.exception117 assert result.output == 'Foo [y/N]: y\nyes!\n'118119 result = runner.invoke(test, input='\n')120 assert not result.exception121 assert result.output == 'Foo [y/N]: \nno :(\n'122123 result = runner.invoke(test, input='n\n')124 assert not result.exception125 assert result.output == 'Foo [y/N]: n\nno :(\n'126127 @click.command()128 def test_no():129 if click.confirm('Foo', default=True):130 click.echo('yes!')131 else:132 click.echo('no :(')133134 result = runner.invoke(test_no, input='y\n')135 assert not result.exception136 assert result.output == 'Foo [Y/n]: y\nyes!\n'137138 result = runner.invoke(test_no, input='\n')139 assert not result.exception140 assert result.output == 'Foo [Y/n]: \nyes!\n'141142 result = runner.invoke(test_no, input='n\n')143 assert not result.exception144 assert result.output == 'Foo [Y/n]: n\nno :(\n'145146147@pytest.mark.skipif(WIN, reason='Different behavior on windows.')148def test_prompts_abort(monkeypatch, capsys):149 def f(_):150 raise KeyboardInterrupt()151152 monkeypatch.setattr('click.termui.hidden_prompt_func', f)153154 try:155 click.prompt('Password', hide_input=True)156 except click.Abort:157 click.echo('Screw you.')158159 out, err = capsys.readouterr()160 assert out == 'Password: \nScrew you.\n'161162

Merge pull request #889 from stefreak/masterDan Sullybefore adoptionb1b4449

lines 163–169why, one step back
163def _test_gen_func():
164 yield 'a'165 yield 'b'166 yield 'c'167 yield 'abc'168169

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 170–171why, one step back
170@pytest.mark.skipif(WIN, reason='Different behavior on windows.')
171@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])

Merge pull request #889 from stefreak/masterDan Sullybefore adoptionb1b4449

lines 172–182why, one step back
172@pytest.mark.parametrize('test', [
173 # We need lambda here, because pytest will174 # reuse the parameters, and then the generators175 # are already used and will not yield anymore176 ('just text\n', lambda: 'just text'),177 ('iterable\n', lambda: ["itera", "ble"]),178 ('abcabc\n', lambda: _test_gen_func),179 ('abcabc\n', lambda: _test_gen_func()),180 ('012345\n', lambda: (c for c in range(6))),181])182def test_echo_via_pager(monkeypatch, capfd, cat, test):

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 183–184why, one step back
183 monkeypatch.setitem(os.environ, 'PAGER', cat)
184 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)

Merge pull request #889 from stefreak/masterDan Sullybefore adoptionb1b4449

lines 185–190why, one step back
185
186 expected_output = test[0]187 test_input = test[1]()188189 click.echo_via_pager(test_input)190

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

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

Merge pull request #889 from stefreak/masterDan Sullybefore adoptionb1b4449

line 192why, one step back
192 assert out == expected_output

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 193–281why, one step back
193
194195@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')196def test_echo_color_flag(monkeypatch, capfd):197 isatty = True198 monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)199200 text = 'foo'201 styled_text = click.style(text, fg='red')202 assert styled_text == '\x1b[31mfoo\x1b[0m'203204 click.echo(styled_text, color=False)205 out, err = capfd.readouterr()206 assert out == text + '\n'207208 click.echo(styled_text, color=True)209 out, err = capfd.readouterr()210 assert out == styled_text + '\n'211212 isatty = True213 click.echo(styled_text)214 out, err = capfd.readouterr()215 assert out == styled_text + '\n'216217 isatty = False218 click.echo(styled_text)219 out, err = capfd.readouterr()220 assert out == text + '\n'221222223@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')224def test_echo_writing_to_standard_error(capfd, monkeypatch):225 def emulate_input(text):226 """Emulate keyboard input."""227 if sys.version_info[0] == 2:228 from StringIO import StringIO229 else:230 from io import StringIO231 monkeypatch.setattr(sys, 'stdin', StringIO(text))232233 click.echo('Echo to standard output')234 out, err = capfd.readouterr()235 assert out == 'Echo to standard output\n'236 assert err == ''237238 click.echo('Echo to standard error', err=True)239 out, err = capfd.readouterr()240 assert out == ''241 assert err == 'Echo to standard error\n'242243 emulate_input('asdlkj\n')244 click.prompt('Prompt to stdin')245 out, err = capfd.readouterr()246 assert out == 'Prompt to stdin: '247 assert err == ''248249 emulate_input('asdlkj\n')250 click.prompt('Prompt to stderr', err=True)251 out, err = capfd.readouterr()252 assert out == ''253 assert err == 'Prompt to stderr: '254255 emulate_input('y\n')256 click.confirm('Prompt to stdin')257 out, err = capfd.readouterr()258 assert out == 'Prompt to stdin [y/N]: '259 assert err == ''260261 emulate_input('y\n')262 click.confirm('Prompt to stderr', err=True)263 out, err = capfd.readouterr()264 assert out == ''265 assert err == 'Prompt to stderr [y/N]: '266267 monkeypatch.setattr(click.termui, 'isatty', lambda x: True)268 monkeypatch.setattr(click.termui, 'getchar', lambda: ' ')269270 click.pause('Pause to stdout')271 out, err = capfd.readouterr()272 assert out == 'Pause to stdout\n'273 assert err == ''274275 click.pause('Pause to stderr', err=True)276 out, err = capfd.readouterr()277 assert out == ''278 assert err == 'Pause to stderr\n'279280281def test_open_file(runner):

Merge pull request #1298 from joewledger/fix_958David Lordbefore adoption9ea9666

lines 282–289why, one step back
282 @click.command()
283 @click.argument('filename')284 def cli(filename):285 with click.open_file(filename) as f:286 click.echo(f.read())287288 click.echo('meep')289

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 290–300why, one step back
290 with runner.isolated_filesystem():
291 with open('hello.txt', 'w') as f:292 f.write('Cool stuff')293294 result = runner.invoke(cli, ['hello.txt'])295 assert result.exception is None296 assert result.output == 'Cool stuff\nmeep\n'297298 result = runner.invoke(cli, ['-'], input='foobar')299 assert result.exception is None300 assert result.output == 'foobar\nmeep\n'

Merge pull request #1400 from andersk/atomic-open-permissionsDavid Lordbefore adoptione0ad5a6

lines 301–302why, one step back
301
302

Merge pull request #1298 from joewledger/fix_958David Lordbefore adoption9ea9666

lines 303–340why, one step back
303def test_open_file_ignore_errors_stdin(runner):
304 @click.command()305 @click.argument("filename")306 def cli(filename):307 with click.open_file(filename, errors="ignore") as f:308 click.echo(f.read())309310 result = runner.invoke(cli, ["-"], input=os.urandom(16))311 assert result.exception is None312313314def test_open_file_respects_ignore(runner):315 with runner.isolated_filesystem():316 with open("test.txt", "w") as f:317 f.write("Hello world!")318319 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:320 assert f.errors == "ignore"321322323def test_open_file_ignore_invalid_utf8(runner):324 with runner.isolated_filesystem():325 with open("test.txt", "wb") as f:326 f.write(b"\xe2\x28\xa1")327328 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:329 f.read()330331332def test_open_file_ignore_no_encoding(runner):333 with runner.isolated_filesystem():334 with open("test.bin", "wb") as f:335 f.write(os.urandom(16))336337 with click.open_file("test.bin", errors="ignore") as f:338 f.read()339340

Merge pull request #1400 from andersk/atomic-open-permissionsDavid Lordbefore adoptione0ad5a6

lines 341–380why, one step back
341@pytest.mark.skipif(WIN, reason='os.chmod() is not fully supported on Windows.')
342@pytest.mark.parametrize('permissions', [343 0o400,344 0o444,345 0o600,346 0o644,347 ])348def test_open_file_atomic_permissions_existing_file(runner, permissions):349 with runner.isolated_filesystem():350 with open('existing.txt', 'w') as f:351 f.write('content')352 os.chmod('existing.txt', permissions)353354 @click.command()355 @click.argument('filename')356 def cli(filename):357 click.open_file(filename, 'w', atomic=True).close()358359 result = runner.invoke(cli, ['existing.txt'])360 assert result.exception is None361 assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions362363364@pytest.mark.skipif(WIN, reason='os.stat() is not fully supported on Windows.')365def test_open_file_atomic_permissions_new_file(runner):366 with runner.isolated_filesystem():367 @click.command()368 @click.argument('filename')369 def cli(filename):370 click.open_file(filename, 'w', atomic=True).close()371372 # Create a test file to get the expected permissions for new files373 # according to the current umask.374 with open('test.txt', 'w'):375 pass376 permissions = stat.S_IMODE(os.stat('test.txt').st_mode)377378 result = runner.invoke(cli, ['new.txt'])379 assert result.exception is None380 assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 381–385why, one step back
381
382383def test_iter_keepopenfile(tmpdir):384 expected = list(map(str, range(10)))385 p = tmpdir.mkdir('testdir').join('testfile')

Merge pull request #1298 from joewledger/fix_958David Lordbefore adoption9ea9666

line 386why, one step back
386 p.write("\n".join(expected))

Merge pull request #878 from jdufresne/resource-warningZachery Birbefore adoption3f66498

lines 387–389why, one step back
387 with p.open() as f:
388 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):389 assert e_line == a_line.strip()

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 390–394why, one step back
390
391392def test_iter_lazyfile(tmpdir):393 expected = list(map(str, range(10)))394 p = tmpdir.mkdir('testdir').join('testfile')

Merge pull request #1298 from joewledger/fix_958David Lordbefore adoption9ea9666

line 395why, one step back
395 p.write("\n".join(expected))

Merge pull request #878 from jdufresne/resource-warningZachery Birbefore adoption3f66498

lines 396–399why, one step back
396 with p.open() as f:
397 with click.utils.LazyFile(f.name) as lf:398 for e_line, a_line in zip(expected, lf):399 assert e_line == a_line.strip()