Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

369 lines · 11.1 KiB · Python

Last changed by

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

History of this file

Take it

1import time23import pytest45import click._termui_impl6from click._compat import WIN789class FakeClock:10    def __init__(self):11        self.now = time.time()1213    def advance_time(self, seconds=1):14        self.now += seconds1516    def time(self):17        return self.now181920def _create_progress(length=10, length_known=True, **kwargs):21    progress = click.progressbar(tuple(range(length)))22    for key, value in kwargs.items():23        setattr(progress, key, value)24    progress.length_known = length_known25    return progress262728def test_progressbar_strip_regression(runner, monkeypatch):29    fake_clock = FakeClock()30    label = "    padded line"3132    @click.command()33    def cli():34        with _create_progress(label=label) as progress:35            for _ in progress:36                fake_clock.advance_time()3738    monkeypatch.setattr(time, "time", fake_clock.time)39    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)40    assert label in runner.invoke(cli, []).output414243def test_progressbar_length_hint(runner, monkeypatch):44    class Hinted:45        def __init__(self, n):46            self.items = list(range(n))4748        def __length_hint__(self):49            return len(self.items)5051        def __iter__(self):52            return self5354        def __next__(self):55            if self.items:56                return self.items.pop()57            else:58                raise StopIteration5960        next = __next__6162    fake_clock = FakeClock()6364    @click.command()65    def cli():66        with click.progressbar(Hinted(10), label="test") as progress:67            for _ in progress:68                fake_clock.advance_time()6970    monkeypatch.setattr(time, "time", fake_clock.time)71    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)72    result = runner.invoke(cli, [])73    assert result.exception is None747576def test_progressbar_hidden(runner, monkeypatch):77    fake_clock = FakeClock()78    label = "whatever"7980    @click.command()81    def cli():82        with _create_progress(label=label) as progress:83            for _ in progress:84                fake_clock.advance_time()8586    monkeypatch.setattr(time, "time", fake_clock.time)87    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)88    assert runner.invoke(cli, []).output == ""899091@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])92def test_progressbar_time_per_iteration(runner, avg, expected):93    with _create_progress(2, avg=avg) as progress:94        assert progress.time_per_iteration == expected959697@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])98def test_progressbar_eta(runner, finished, expected):99    with _create_progress(2, finished=finished, avg=[1, 4]) as progress:100        assert progress.eta == expected101102103@pytest.mark.parametrize(104    "eta, expected",105    [106        (0, "00:00:00"),107        (30, "00:00:30"),108        (90, "00:01:30"),109        (900, "00:15:00"),110        (9000, "02:30:00"),111        (99999999999, "1157407d 09:46:39"),112        (None, ""),113    ],114)115def test_progressbar_format_eta(runner, eta, expected):116    with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:117        assert progress.format_eta() == expected118119120@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])121def test_progressbar_format_pos(runner, pos, length):122    with _create_progress(length, length_known=length != 0, pos=pos) as progress:123        result = progress.format_pos()124        if progress.length_known:125            assert result == f"{pos}/{length}"126        else:127            assert result == str(pos)128129130@pytest.mark.parametrize(131    "length, finished, pos, avg, expected",132    [133        (8, False, 7, 0, "#######-"),134        (0, True, 8, 0, "########"),135        (0, False, 8, 0, "--------"),136        (0, False, 5, 3, "#-------"),137    ],138)139def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):140    with _create_progress(141        length, length_known=length != 0, width=8, pos=pos, finished=finished, avg=[avg]142    ) as progress:143        assert progress.format_bar() == expected144145146@pytest.mark.parametrize(147    "length, length_known, show_percent, show_pos, pos, expected",148    [149        (0, True, True, True, 0, "  [--------]  0/0    0%"),150        (0, True, False, True, 0, "  [--------]  0/0"),151        (0, True, False, False, 0, "  [--------]"),152        (0, False, False, False, 0, "  [--------]"),153        (8, True, True, True, 8, "  [########]  8/8  100%"),154    ],155)156def test_progressbar_format_progress_line(157    runner, length, length_known, show_percent, show_pos, pos, expected158):159    with _create_progress(160        length,161        length_known,162        width=8,163        show_percent=show_percent,164        pos=pos,165        show_pos=show_pos,166    ) as progress:167        assert progress.format_progress_line() == expected168169170@pytest.mark.parametrize("test_item", ["test", None])171def test_progressbar_format_progress_line_with_show_func(runner, test_item):172    def item_show_func(item):173        return item174175    with _create_progress(176        item_show_func=item_show_func, current_item=test_item177    ) as progress:178        if test_item:179            assert progress.format_progress_line().endswith(test_item)180        else:181            assert progress.format_progress_line().endswith(progress.format_pct())182183184def test_progressbar_init_exceptions(runner):185    with pytest.raises(TypeError, match="iterable or length is required"):186        click.progressbar()187188189def test_progressbar_iter_outside_with_exceptions(runner):190    with pytest.raises(RuntimeError, match="with block"):191        progress = click.progressbar(length=2)192        iter(progress)193194195def test_progressbar_is_iterator(runner, monkeypatch):196    fake_clock = FakeClock()197198    @click.command()199    def cli():200        with click.progressbar(range(10), label="test") as progress:201            while True:202                try:203                    next(progress)204                    fake_clock.advance_time()205                except StopIteration:206                    break207208    monkeypatch.setattr(time, "time", fake_clock.time)209    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)210211    result = runner.invoke(cli, [])212    assert result.exception is None213214215def test_choices_list_in_prompt(runner, monkeypatch):216    @click.command()217    @click.option(218        "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True219    )220    def cli_with_choices(g):221        pass222223    @click.command()224    @click.option(225        "-g",226        type=click.Choice(["none", "day", "week", "month"]),227        prompt=True,228        show_choices=False,229    )230    def cli_without_choices(g):231        pass232233    result = runner.invoke(cli_with_choices, [], input="none")234    assert "(none, day, week, month)" in result.output235236    result = runner.invoke(cli_without_choices, [], input="none")237    assert "(none, day, week, month)" not in result.output238239240@pytest.mark.parametrize(241    "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]242)243def test_file_prompt_default_format(runner, file_kwargs):244    @click.command()245    @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))246    def cli(f):247        click.echo(f.name)248249    result = runner.invoke(cli)250    assert result.output == f"file [{__file__}]: \n{__file__}\n"251252253def test_secho(runner):254    with runner.isolation() as outstreams:255        click.secho(None, nl=False)256        bytes = outstreams[0].getvalue()257        assert bytes == b""258259260def test_progressbar_yields_all_items(runner):261    with click.progressbar(range(3)) as progress:262        assert len(list(progress)) == 3263264265def test_progressbar_update(runner, monkeypatch):266    fake_clock = FakeClock()267268    @click.command()269    def cli():270        with click.progressbar(range(4)) as progress:271            for _ in progress:272                fake_clock.advance_time()273                print("")274275    monkeypatch.setattr(time, "time", fake_clock.time)276    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)277    output = runner.invoke(cli, []).output278279    lines = [line for line in output.split("\n") if "[" in line]280281    assert " 25%  00:00:03" in lines[0]282    assert " 50%  00:00:02" in lines[1]283    assert " 75%  00:00:01" in lines[2]284    assert "100%          " in lines[3]285286287def test_progressbar_item_show_func(runner, monkeypatch):288    fake_clock = FakeClock()289290    @click.command()291    def cli():292        with click.progressbar(293            range(4), item_show_func=lambda x: f"Custom {x}"294        ) as progress:295            for _ in progress:296                fake_clock.advance_time()297                print("")298299    monkeypatch.setattr(time, "time", fake_clock.time)300    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)301    output = runner.invoke(cli, []).output302303    lines = [line for line in output.split("\n") if "[" in line]304305    assert "Custom 0" in lines[0]306    assert "Custom 1" in lines[1]307    assert "Custom 2" in lines[2]308    assert "Custom None" in lines[3]309310311def test_progressbar_update_with_item_show_func(runner, monkeypatch):312    fake_clock = FakeClock()313314    @click.command()315    def cli():316        with click.progressbar(317            length=6, item_show_func=lambda x: f"Custom {x}"318        ) as progress:319            while not progress.finished:320                fake_clock.advance_time()321                progress.update(2, progress.pos)322                print("")323324    monkeypatch.setattr(time, "time", fake_clock.time)325    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)326    output = runner.invoke(cli, []).output327328    lines = [line for line in output.split("\n") if "[" in line]329330    assert "Custom 0" in lines[0]331    assert "Custom 2" in lines[1]332    assert "Custom 4" in lines[2]333334335@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))336@pytest.mark.parametrize("echo", [True, False])337@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")338def test_getchar_windows(runner, monkeypatch, key_char, echo):339    monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)340    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)341    monkeypatch.setattr(click.termui, "_getchar", None)342    assert click.getchar(echo) == key_char343344345@pytest.mark.parametrize(346    "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]347)348@pytest.mark.skipif(349    not WIN, reason="Tests special character inputs using the msvcrt module."350)351def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):352    ordered_inputs = [key_char, special_key_char]353    monkeypatch.setattr(354        click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()355    )356    monkeypatch.setattr(click.termui, "_getchar", None)357    assert click.getchar() == f"{special_key_char}{key_char}"358359360@pytest.mark.parametrize(361    ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)],362)363@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")364def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):365    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)366    monkeypatch.setattr(click.termui, "_getchar", None)367368    with pytest.raises(exc):369        click.getchar()