Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

283 lines · 8.7 KiB · Python

Last changed by

Added two xfailsArmin Ronacherbefore adoptiondde42ed

History of this file

Take it

1import os2import sys34import pytest56import click7import click.utils8import click._termui_impl9from click._compat import WIN, PY2101112def test_echo(runner):13    with runner.isolation() as out:14        click.echo(u'\N{SNOWMAN}')15        click.echo(b'\x44\x44')16        click.echo(42, nl=False)17        click.echo(b'a', nl=False)18        click.echo('\x1b[31mx\x1b[39m', nl=False)19        bytes = out.getvalue().replace(b'\r\n', b'\n')20        assert bytes == b'\xe2\x98\x83\nDD\n42ax'2122    # If we are in Python 2, we expect that writing bytes into a string io23    # does not do anything crazy.  In Python 324    if sys.version_info[0] == 2:25        import StringIO26        sys.stdout = x = StringIO.StringIO()27        try:28            click.echo('\xf6')29        finally:30            sys.stdout = sys.__stdout__31        assert x.getvalue() == '\xf6\n'3233    # And in any case, if wrapped, we expect bytes to survive.34    @click.command()35    def cli():36        click.echo(b'\xf6')37    result = runner.invoke(cli, [])38    assert result.output_bytes == b'\xf6\n'3940    # Ensure we do not strip for bytes.41    with runner.isolation() as out:42        click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)43        assert out.getvalue() == b'\x1b[31mx\x1b[39m'444546def test_echo_custom_file():47    import io48    f = io.StringIO()49    click.echo(u'hello', file=f)50    assert f.getvalue() == u'hello\n'515253def test_styling():54    examples = [55        ('x', dict(fg='black'), '\x1b[30mx\x1b[0m'),56        ('x', dict(fg='red'), '\x1b[31mx\x1b[0m'),57        ('x', dict(fg='green'), '\x1b[32mx\x1b[0m'),58        ('x', dict(fg='yellow'), '\x1b[33mx\x1b[0m'),59        ('x', dict(fg='blue'), '\x1b[34mx\x1b[0m'),60        ('x', dict(fg='magenta'), '\x1b[35mx\x1b[0m'),61        ('x', dict(fg='cyan'), '\x1b[36mx\x1b[0m'),62        ('x', dict(fg='white'), '\x1b[37mx\x1b[0m'),63        ('x', dict(bg='black'), '\x1b[40mx\x1b[0m'),64        ('x', dict(bg='red'), '\x1b[41mx\x1b[0m'),65        ('x', dict(bg='green'), '\x1b[42mx\x1b[0m'),66        ('x', dict(bg='yellow'), '\x1b[43mx\x1b[0m'),67        ('x', dict(bg='blue'), '\x1b[44mx\x1b[0m'),68        ('x', dict(bg='magenta'), '\x1b[45mx\x1b[0m'),69        ('x', dict(bg='cyan'), '\x1b[46mx\x1b[0m'),70        ('x', dict(bg='white'), '\x1b[47mx\x1b[0m'),71        ('foo bar', dict(blink=True), '\x1b[5mfoo bar\x1b[0m'),72        ('foo bar', dict(underline=True), '\x1b[4mfoo bar\x1b[0m'),73        ('foo bar', dict(bold=True), '\x1b[1mfoo bar\x1b[0m'),74        ('foo bar', dict(dim=True), '\x1b[2mfoo bar\x1b[0m'),75    ]76    for text, styles, ref in examples:77        assert click.style(text, **styles) == ref78        assert click.unstyle(ref) == text798081def test_filename_formatting():82    assert click.format_filename(b'foo.txt') == 'foo.txt'83    assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'84    assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'85    assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt'8687    # filesystem encoding on windows permits this.88    if not WIN:89        assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \90            == u'foo\ufffd.txt'919293def test_prompts(runner):94    @click.command()95    def test():96        if click.confirm('Foo'):97            click.echo('yes!')98        else:99            click.echo('no :(')100101    result = runner.invoke(test, input='y\n')102    assert not result.exception103    assert result.output == 'Foo [y/N]: y\nyes!\n'104105    result = runner.invoke(test, input='\n')106    assert not result.exception107    assert result.output == 'Foo [y/N]: \nno :(\n'108109    result = runner.invoke(test, input='n\n')110    assert not result.exception111    assert result.output == 'Foo [y/N]: n\nno :(\n'112113    @click.command()114    def test_no():115        if click.confirm('Foo', default=True):116            click.echo('yes!')117        else:118            click.echo('no :(')119120    result = runner.invoke(test_no, input='y\n')121    assert not result.exception122    assert result.output == 'Foo [Y/n]: y\nyes!\n'123124    result = runner.invoke(test_no, input='\n')125    assert not result.exception126    assert result.output == 'Foo [Y/n]: \nyes!\n'127128    result = runner.invoke(test_no, input='n\n')129    assert not result.exception130    assert result.output == 'Foo [Y/n]: n\nno :(\n'131132133@pytest.mark.skipif(WIN, reason='Different behavior on windows.')134def test_prompts_abort(monkeypatch, capsys):135    def f(_):136        raise KeyboardInterrupt()137138    monkeypatch.setattr('click.termui.hidden_prompt_func', f)139140    try:141        click.prompt('Password', hide_input=True)142    except click.Abort:143        click.echo('Screw you.')144145    out, err = capsys.readouterr()146    assert out == 'Password: \nScrew you.\n'147148149@pytest.mark.skipif(WIN, reason='Different behavior on windows.')150@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])151def test_echo_via_pager(monkeypatch, capfd, cat):152    monkeypatch.setitem(os.environ, 'PAGER', cat)153    monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)154    click.echo_via_pager('haha')155    out, err = capfd.readouterr()156    assert out == 'haha\n'157158159@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')160def test_echo_color_flag(monkeypatch, capfd):161    isatty = True162    monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)163164    text = 'foo'165    styled_text = click.style(text, fg='red')166    assert styled_text == '\x1b[31mfoo\x1b[0m'167168    click.echo(styled_text, color=False)169    out, err = capfd.readouterr()170    assert out == text + '\n'171172    click.echo(styled_text, color=True)173    out, err = capfd.readouterr()174    assert out == styled_text + '\n'175176    isatty = True177    click.echo(styled_text)178    out, err = capfd.readouterr()179    assert out == styled_text + '\n'180181    isatty = False182    click.echo(styled_text)183    out, err = capfd.readouterr()184    assert out == text + '\n'185186187@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')188def test_echo_writing_to_standard_error(capfd, monkeypatch):189    def emulate_input(text):190        """Emulate keyboard input."""191        if sys.version_info[0] == 2:192            from StringIO import StringIO193        else:194            from io import StringIO195        monkeypatch.setattr(sys, 'stdin', StringIO(text))196197    click.echo('Echo to standard output')198    out, err = capfd.readouterr()199    assert out == 'Echo to standard output\n'200    assert err == ''201202    click.echo('Echo to standard error', err=True)203    out, err = capfd.readouterr()204    assert out == ''205    assert err == 'Echo to standard error\n'206207    emulate_input('asdlkj\n')208    click.prompt('Prompt to stdin')209    out, err = capfd.readouterr()210    assert out == 'Prompt to stdin: '211    assert err == ''212213    emulate_input('asdlkj\n')214    click.prompt('Prompt to stderr', err=True)215    out, err = capfd.readouterr()216    assert out == ''217    assert err == 'Prompt to stderr: '218219    emulate_input('y\n')220    click.confirm('Prompt to stdin')221    out, err = capfd.readouterr()222    assert out == 'Prompt to stdin [y/N]: '223    assert err == ''224225    emulate_input('y\n')226    click.confirm('Prompt to stderr', err=True)227    out, err = capfd.readouterr()228    assert out == ''229    assert err == 'Prompt to stderr [y/N]: '230231    monkeypatch.setattr(click.termui, 'isatty', lambda x: True)232    monkeypatch.setattr(click.termui, 'getchar', lambda: ' ')233234    click.pause('Pause to stdout')235    out, err = capfd.readouterr()236    assert out == 'Pause to stdout\n'237    assert err == ''238239    click.pause('Pause to stderr', err=True)240    out, err = capfd.readouterr()241    assert out == ''242    assert err == 'Pause to stderr\n'243244245def test_open_file(runner):246    with runner.isolated_filesystem():247        with open('hello.txt', 'w') as f:248            f.write('Cool stuff')249250        @click.command()251        @click.argument('filename')252        def cli(filename):253            with click.open_file(filename) as f:254                click.echo(f.read())255            click.echo('meep')256257        result = runner.invoke(cli, ['hello.txt'])258        assert result.exception is None259        assert result.output == 'Cool stuff\nmeep\n'260261        result = runner.invoke(cli, ['-'], input='foobar')262        assert result.exception is None263        assert result.output == 'foobar\nmeep\n'264265266@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')267def test_iter_keepopenfile(tmpdir):268    expected = list(map(str, range(10)))269    p = tmpdir.mkdir('testdir').join('testfile')270    p.write(os.linesep.join(expected))271    f = p.open()272    for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):273        assert e_line == a_line.strip()274275276@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')277def test_iter_lazyfile(tmpdir):278    expected = list(map(str, range(10)))279    p = tmpdir.mkdir('testdir').join('testfile')280    p.write(os.linesep.join(expected))281    f = p.open()282    for e_line, a_line in zip(expected, click.utils.LazyFile(f.name)):283        assert e_line == a_line.strip()