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

1import os2import stat3import sys45import pytest67import click8import click.utils9import click._termui_impl10from click._compat import WIN, PY2111213def test_echo(runner):14    with runner.isolation() as outstreams: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)20        bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')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, [])39    assert result.stdout_bytes == b'\xf6\n'4041    # Ensure we do not strip for bytes.42    with runner.isolation() as outstreams:43        click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)44        assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'454647def test_echo_custom_file():48    import io49    f = io.StringIO()50    click.echo(u'hello', file=f)51    assert f.getvalue() == u'hello\n'525354@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"),88    ]89)90def test_unstyle_other_ansi(text, expect):91    assert click.unstyle(text) == expect92939495def 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'161162163def _test_gen_func():164    yield 'a'165    yield 'b'166    yield 'c'167    yield 'abc'168169170@pytest.mark.skipif(WIN, reason='Different behavior on windows.')171@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])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):183    monkeypatch.setitem(os.environ, 'PAGER', cat)184    monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)185186    expected_output = test[0]187    test_input = test[1]()188189    click.echo_via_pager(test_input)190191    out, err = capfd.readouterr()192    assert out == expected_output193194195@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):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')289290    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'301302303def 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()339340341@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) == permissions381382383def test_iter_keepopenfile(tmpdir):384    expected = list(map(str, range(10)))385    p = tmpdir.mkdir('testdir').join('testfile')386    p.write("\n".join(expected))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()390391392def test_iter_lazyfile(tmpdir):393    expected = list(map(str, range(10)))394    p = tmpdir.mkdir('testdir').join('testfile')395    p.write("\n".join(expected))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()