Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

313 lines · 10.4 KiB · Python

Last changed by

Merge pull request #1309 from icreatedanaccount/masterDavid Lordbefore adoption93d947c

History of this file

Take it

1# -*- coding: utf-8 -*-2import pytest34import click5import time67import click._termui_impl8from click._compat import WIN91011class FakeClock(object):12    def __init__(self):13        self.now = time.time()1415    def advance_time(self, seconds=1):16        self.now += seconds1718    def time(self):19        return self.now202122def _create_progress(length=10, length_known=True, **kwargs):23    progress = click.progressbar(tuple(range(length)))24    for key, value in kwargs.items():25        setattr(progress, key, value)26    progress.length_known = length_known27    return progress282930def test_progressbar_strip_regression(runner, monkeypatch):31    fake_clock = FakeClock()32    label = '    padded line'3334    @click.command()35    def cli():36        with _create_progress(label=label) as progress:37            for thing in progress:38                fake_clock.advance_time()3940    monkeypatch.setattr(time, 'time', fake_clock.time)41    monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)42    assert label in runner.invoke(cli, []).output434445def test_progressbar_length_hint(runner, monkeypatch):46    class Hinted(object):47        def __init__(self, n):48            self.items = list(range(n))4950        def __length_hint__(self):51            return len(self.items)5253        def __iter__(self):54            return self5556        def __next__(self):57            if self.items:58                return self.items.pop()59            else:60                raise StopIteration6162        next = __next__6364    fake_clock = FakeClock()6566    @click.command()67    def cli():68        with click.progressbar(Hinted(10), label='test') as progress:69            for thing in progress:70                fake_clock.advance_time()7172    monkeypatch.setattr(time, 'time', fake_clock.time)73    monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)74    result = runner.invoke(cli, [])75    assert result.exception is None767778def test_progressbar_hidden(runner, monkeypatch):79    fake_clock = FakeClock()80    label = 'whatever'8182    @click.command()83    def cli():84        with _create_progress(label=label) as progress:85            for thing in progress:86                fake_clock.advance_time()8788    monkeypatch.setattr(time, 'time', fake_clock.time)89    monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)90    assert runner.invoke(cli, []).output == ''919293@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])94def test_progressbar_time_per_iteration(runner, avg, expected):95    with _create_progress(2, avg=avg) as progress:96        assert progress.time_per_iteration == expected979899@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])100def test_progressbar_eta(runner, finished, expected):101    with _create_progress(2, finished=finished, avg=[1, 4]) as progress:102        assert progress.eta == expected103104105@pytest.mark.parametrize('eta, expected',106                         [(0, '00:00:00'), (30, '00:00:30'), (90, '00:01:30'), (900, '00:15:00'),107                          (9000, '02:30:00'), (99999999999, '1157407d 09:46:39'), (None, '')])108def test_progressbar_format_eta(runner, eta, expected):109    with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:110        assert progress.format_eta() == expected111112113@pytest.mark.parametrize('pos, length', [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])114def test_progressbar_format_pos(runner, pos, length):115    with _create_progress(length, length_known=length != 0, pos=pos) as progress:116        result = progress.format_pos()117        if progress.length_known:118            assert result == '%s/%s' % (pos, length)119        else:120            assert result == str(pos)121122123@pytest.mark.parametrize('length, finished, pos, avg, expected',124                         [(8, False, 7, 0, '#######-'),125                          (0, True, 8, 0, '########'),126                          (0, False, 8, 0, '--------'),127                          (0, False, 5, 3, '#-------')128                          ])129def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):130    with _create_progress(length,131                          length_known=length != 0,132                          width=8,133                          pos=pos,134                          finished=finished,135                          avg=[avg]) as progress:136        assert progress.format_bar() == expected137138139@pytest.mark.parametrize('length, length_known, show_percent, show_pos, pos, expected',140                         [(0, True, True, True, 0, '  [--------]  0/0    0%'),141                          (0, True, False, True, 0, '  [--------]  0/0'),142                          (0, True, False, False, 0, '  [--------]'),143                          (0, False, False, False, 0, '  [--------]'),144                          (8, True, True, True, 8, '  [########]  8/8  100%')145                          ])146def test_progressbar_format_progress_line(runner, length, length_known, show_percent, show_pos, pos, expected):147    with _create_progress(length,148                          length_known,149                          width=8,150                          show_percent=show_percent,151                          pos=pos,152                          show_pos=show_pos) as progress:153        assert progress.format_progress_line() == expected154155156@pytest.mark.parametrize('test_item', ['test', None])157def test_progressbar_format_progress_line_with_show_func(runner, test_item):158159    def item_show_func(item):160        return item161162    with _create_progress(item_show_func=item_show_func, current_item=test_item) as progress:163        if test_item:164            assert progress.format_progress_line().endswith(test_item)165        else:166            assert progress.format_progress_line().endswith(progress.format_pct())167168169def test_progressbar_init_exceptions(runner):170    try:171        click.progressbar()172    except TypeError as e:173        assert str(e) == 'iterable or length is required'174    else:175        assert False, 'Expected an exception because unspecified arguments'176177178def test_progressbar_iter_outside_with_exceptions(runner):179    try:180        progress = click.progressbar(length=2)181        iter(progress)182    except RuntimeError as e:183        assert str(e) == 'You need to use progress bars in a with block.'184    else:185        assert False, 'Expected an exception because of abort-related inputs.'186187188def test_progressbar_is_iterator(runner, monkeypatch):189    fake_clock = FakeClock()190191    @click.command()192    def cli():193        with click.progressbar(range(10), label='test') as progress:194            while True:195                try:196                    next(progress)197                    fake_clock.advance_time()198                except StopIteration:199                    break200201    monkeypatch.setattr(time, 'time', fake_clock.time)202    monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)203204    result = runner.invoke(cli, [])205    assert result.exception is None206207208def test_choices_list_in_prompt(runner, monkeypatch):209    @click.command()210    @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),211                  prompt=True)212    def cli_with_choices(g):213        pass214215    @click.command()216    @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),217                  prompt=True, show_choices=False)218    def cli_without_choices(g):219        pass220221    result = runner.invoke(cli_with_choices, [], input='none')222    assert '(none, day, week, month)' in result.output223224    result = runner.invoke(cli_without_choices, [], input='none')225    assert '(none, day, week, month)' not in result.output226227228@pytest.mark.parametrize(229    "file_kwargs",230    [231        {"mode": "rt"},232        {"mode": "rb"},233        {"lazy": True},234    ]235)236def test_file_prompt_default_format(runner, file_kwargs):237    @click.command()238    @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))239    def cli(f):240        click.echo(f.name)241242    result = runner.invoke(cli)243    assert result.output == "file [{0}]: \n{0}\n".format(__file__)244245246def test_secho(runner):247    with runner.isolation() as outstreams:248        click.secho(None, nl=False)249        bytes = outstreams[0].getvalue()250        assert bytes == b''251252253def test_progressbar_yields_all_items(runner):254    with click.progressbar(range(3)) as progress:255        assert len(list(progress)) == 3256257258def test_progressbar_update(runner, monkeypatch):259    fake_clock = FakeClock()260261    @click.command()262    def cli():263        with click.progressbar(range(4)) as progress:264            for _ in progress:265                fake_clock.advance_time()266                print("")267268    monkeypatch.setattr(time, 'time', fake_clock.time)269    monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)270    output = runner.invoke(cli, []).output271272    lines = [line for line in output.split('\n') if '[' in line]273274    assert ' 25%  00:00:03' in lines[0]275    assert ' 50%  00:00:02' in lines[1]276    assert ' 75%  00:00:01' in lines[2]277    assert '100%          ' in lines[3]278279280@pytest.mark.parametrize(281    'key_char', (u'h', u'H', u'é', u'À', u' ', u'字', u'àH', u'àR')282)283@pytest.mark.parametrize('echo', [True, False])284@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')285def test_getchar_windows(runner, monkeypatch, key_char, echo):286    monkeypatch.setattr(click._termui_impl.msvcrt, 'getwche', lambda: key_char)287    monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)288    monkeypatch.setattr(click.termui, '_getchar', None)289    assert click.getchar(echo) == key_char290291292@pytest.mark.parametrize('special_key_char, key_char', [(u'\x00', 'a'), (u'\x00', 'b'), (u'\xe0', 'c')])293@pytest.mark.skipif(not WIN, reason='Tests special character inputs using the msvcrt module.')294def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):295    ordered_inputs = [key_char, special_key_char]296    monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: ordered_inputs.pop())297    monkeypatch.setattr(click.termui, '_getchar', None)298    assert click.getchar() == special_key_char + key_char299300301@pytest.mark.parametrize('key_char', [u'\x03', u'\x1a'])302@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')303def test_getchar_windows_exceptions(runner, monkeypatch, key_char):304    monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)305    monkeypatch.setattr(click.termui, '_getchar', None)306    try:307        click.getchar()308    except KeyboardInterrupt:309        assert key_char == u'\x03'310    except EOFError:311        assert key_char == u'\x1a'312    else:313        assert False, 'Expected an exception because of abort-specific inputs.'