Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

438 lines · 13.5 KiB · Python

Last changed by

add ability to provide non-flag option without valueAmybefore adoptiond314f45

History of this file

Take it

1import platform2import time34import pytest56import click._termui_impl7from click._compat import WIN8910class FakeClock:11    def __init__(self):12        self.now = time.time()1314    def advance_time(self, seconds=1):15        self.now += seconds1617    def time(self):18        return self.now192021def _create_progress(length=10, length_known=True, **kwargs):22    progress = click.progressbar(tuple(range(length)))23    for key, value in kwargs.items():24        setattr(progress, key, value)25    progress.length_known = length_known26    return progress272829def test_progressbar_strip_regression(runner, monkeypatch):30    fake_clock = FakeClock()31    label = "    padded line"3233    @click.command()34    def cli():35        with _create_progress(label=label) as progress:36            for _ in progress:37                fake_clock.advance_time()3839    monkeypatch.setattr(time, "time", fake_clock.time)40    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)41    assert label in runner.invoke(cli, []).output424344def test_progressbar_length_hint(runner, monkeypatch):45    class Hinted:46        def __init__(self, n):47            self.items = list(range(n))4849        def __length_hint__(self):50            return len(self.items)5152        def __iter__(self):53            return self5455        def __next__(self):56            if self.items:57                return self.items.pop()58            else:59                raise StopIteration6061        next = __next__6263    fake_clock = FakeClock()6465    @click.command()66    def cli():67        with click.progressbar(Hinted(10), label="test") as progress:68            for _ in progress:69                fake_clock.advance_time()7071    monkeypatch.setattr(time, "time", fake_clock.time)72    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)73    result = runner.invoke(cli, [])74    assert result.exception is None757677def test_progressbar_hidden(runner, monkeypatch):78    fake_clock = FakeClock()79    label = "whatever"8081    @click.command()82    def cli():83        with _create_progress(label=label) as progress:84            for _ in progress:85                fake_clock.advance_time()8687    monkeypatch.setattr(time, "time", fake_clock.time)88    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)89    assert runner.invoke(cli, []).output == ""909192@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])93def test_progressbar_time_per_iteration(runner, avg, expected):94    with _create_progress(2, avg=avg) as progress:95        assert progress.time_per_iteration == expected969798@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])99def test_progressbar_eta(runner, finished, expected):100    with _create_progress(2, finished=finished, avg=[1, 4]) as progress:101        assert progress.eta == expected102103104@pytest.mark.parametrize(105    "eta, expected",106    [107        (0, "00:00:00"),108        (30, "00:00:30"),109        (90, "00:01:30"),110        (900, "00:15:00"),111        (9000, "02:30:00"),112        (99999999999, "1157407d 09:46:39"),113        (None, ""),114    ],115)116def test_progressbar_format_eta(runner, eta, expected):117    with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:118        assert progress.format_eta() == expected119120121@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])122def test_progressbar_format_pos(runner, pos, length):123    with _create_progress(length, length_known=length != 0, pos=pos) as progress:124        result = progress.format_pos()125        if progress.length_known:126            assert result == f"{pos}/{length}"127        else:128            assert result == str(pos)129130131@pytest.mark.parametrize(132    "length, finished, pos, avg, expected",133    [134        (8, False, 7, 0, "#######-"),135        (0, True, 8, 0, "########"),136        (0, False, 8, 0, "--------"),137        (0, False, 5, 3, "#-------"),138    ],139)140def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):141    with _create_progress(142        length, length_known=length != 0, width=8, pos=pos, finished=finished, avg=[avg]143    ) as progress:144        assert progress.format_bar() == expected145146147@pytest.mark.parametrize(148    "length, length_known, show_percent, show_pos, pos, expected",149    [150        (0, True, True, True, 0, "  [--------]  0/0    0%"),151        (0, True, False, True, 0, "  [--------]  0/0"),152        (0, True, False, False, 0, "  [--------]"),153        (0, False, False, False, 0, "  [--------]"),154        (8, True, True, True, 8, "  [########]  8/8  100%"),155    ],156)157def test_progressbar_format_progress_line(158    runner, length, length_known, show_percent, show_pos, pos, expected159):160    with _create_progress(161        length,162        length_known,163        width=8,164        show_percent=show_percent,165        pos=pos,166        show_pos=show_pos,167    ) as progress:168        assert progress.format_progress_line() == expected169170171@pytest.mark.parametrize("test_item", ["test", None])172def test_progressbar_format_progress_line_with_show_func(runner, test_item):173    def item_show_func(item):174        return item175176    with _create_progress(177        item_show_func=item_show_func, current_item=test_item178    ) as progress:179        if test_item:180            assert progress.format_progress_line().endswith(test_item)181        else:182            assert progress.format_progress_line().endswith(progress.format_pct())183184185def test_progressbar_init_exceptions(runner):186    with pytest.raises(TypeError, match="iterable or length is required"):187        click.progressbar()188189190def test_progressbar_iter_outside_with_exceptions(runner):191    with pytest.raises(RuntimeError, match="with block"):192        progress = click.progressbar(length=2)193        iter(progress)194195196def test_progressbar_is_iterator(runner, monkeypatch):197    fake_clock = FakeClock()198199    @click.command()200    def cli():201        with click.progressbar(range(10), label="test") as progress:202            while True:203                try:204                    next(progress)205                    fake_clock.advance_time()206                except StopIteration:207                    break208209    monkeypatch.setattr(time, "time", fake_clock.time)210    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)211212    result = runner.invoke(cli, [])213    assert result.exception is None214215216def test_choices_list_in_prompt(runner, monkeypatch):217    @click.command()218    @click.option(219        "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True220    )221    def cli_with_choices(g):222        pass223224    @click.command()225    @click.option(226        "-g",227        type=click.Choice(["none", "day", "week", "month"]),228        prompt=True,229        show_choices=False,230    )231    def cli_without_choices(g):232        pass233234    result = runner.invoke(cli_with_choices, [], input="none")235    assert "(none, day, week, month)" in result.output236237    result = runner.invoke(cli_without_choices, [], input="none")238    assert "(none, day, week, month)" not in result.output239240241@pytest.mark.parametrize(242    "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]243)244def test_file_prompt_default_format(runner, file_kwargs):245    @click.command()246    @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))247    def cli(f):248        click.echo(f.name)249250    result = runner.invoke(cli)251    assert result.output == f"file [{__file__}]: \n{__file__}\n"252253254def test_secho(runner):255    with runner.isolation() as outstreams:256        click.secho(None, nl=False)257        bytes = outstreams[0].getvalue()258        assert bytes == b""259260261@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")262@pytest.mark.parametrize(263    ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]264)265def test_secho_non_text(runner, value, expect):266    with runner.isolation() as (out, _):267        click.secho(value, nl=False, color=True, bg="magenta")268        result = out.getvalue()269        assert result == expect270271272def test_progressbar_yields_all_items(runner):273    with click.progressbar(range(3)) as progress:274        assert len(list(progress)) == 3275276277def test_progressbar_update(runner, monkeypatch):278    fake_clock = FakeClock()279280    @click.command()281    def cli():282        with click.progressbar(range(4)) as progress:283            for _ in progress:284                fake_clock.advance_time()285                print("")286287    monkeypatch.setattr(time, "time", fake_clock.time)288    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)289    output = runner.invoke(cli, []).output290291    lines = [line for line in output.split("\n") if "[" in line]292293    assert " 25%  00:00:03" in lines[0]294    assert " 50%  00:00:02" in lines[1]295    assert " 75%  00:00:01" in lines[2]296    assert "100%          " in lines[3]297298299def test_progressbar_item_show_func(runner, monkeypatch):300    fake_clock = FakeClock()301302    @click.command()303    def cli():304        with click.progressbar(305            range(4), item_show_func=lambda x: f"Custom {x}"306        ) as progress:307            for _ in progress:308                fake_clock.advance_time()309                print("")310311    monkeypatch.setattr(time, "time", fake_clock.time)312    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)313    output = runner.invoke(cli, []).output314315    lines = [line for line in output.split("\n") if "[" in line]316317    assert "Custom 0" in lines[0]318    assert "Custom 1" in lines[1]319    assert "Custom 2" in lines[2]320    assert "Custom None" in lines[3]321322323def test_progressbar_update_with_item_show_func(runner, monkeypatch):324    fake_clock = FakeClock()325326    @click.command()327    def cli():328        with click.progressbar(329            length=6, item_show_func=lambda x: f"Custom {x}"330        ) as progress:331            while not progress.finished:332                fake_clock.advance_time()333                progress.update(2, progress.pos)334                print("")335336    monkeypatch.setattr(time, "time", fake_clock.time)337    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)338    output = runner.invoke(cli, []).output339340    lines = [line for line in output.split("\n") if "[" in line]341342    assert "Custom 0" in lines[0]343    assert "Custom 2" in lines[1]344    assert "Custom 4" in lines[2]345346347@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))348@pytest.mark.parametrize("echo", [True, False])349@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")350def test_getchar_windows(runner, monkeypatch, key_char, echo):351    monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)352    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)353    monkeypatch.setattr(click.termui, "_getchar", None)354    assert click.getchar(echo) == key_char355356357@pytest.mark.parametrize(358    "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]359)360@pytest.mark.skipif(361    not WIN, reason="Tests special character inputs using the msvcrt module."362)363def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):364    ordered_inputs = [key_char, special_key_char]365    monkeypatch.setattr(366        click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()367    )368    monkeypatch.setattr(click.termui, "_getchar", None)369    assert click.getchar() == f"{special_key_char}{key_char}"370371372@pytest.mark.parametrize(373    ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)],374)375@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")376def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):377    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)378    monkeypatch.setattr(click.termui, "_getchar", None)379380    with pytest.raises(exc):381        click.getchar()382383384@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")385def test_fast_edit(runner):386    result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")387    assert result == "aTest\nbTest\n"388389390@pytest.mark.parametrize(391    ("prompt_required", "required", "args", "expect"),392    [393        (True, False, None, "prompt"),394        (True, False, ["-v"], "-v option requires an argument"),395        (False, True, None, "prompt"),396        (False, True, ["-v"], "prompt"),397    ],398)399def test_prompt_required_with_required(runner, prompt_required, required, args, expect):400    @click.command()401    @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)402    def cli(v):403        click.echo(str(v))404405    result = runner.invoke(cli, args, input="prompt")406    assert expect in result.output407408409@pytest.mark.parametrize(410    ("args", "expect"),411    [412        # Flag not passed, don't prompt.413        pytest.param(None, None, id="no flag"),414        # Flag and value passed, don't prompt.415        pytest.param(["-v", "value"], "value", id="short sep value"),416        pytest.param(["--value", "value"], "value", id="long sep value"),417        pytest.param(["-vvalue"], "value", id="short join value"),418        pytest.param(["--value=value"], "value", id="long join value"),419        # Flag without value passed, prompt.420        pytest.param(["-v"], "prompt", id="short no value"),421        pytest.param(["--value"], "prompt", id="long no value"),422        # Don't use next option flag as value.423        pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),424    ],425)426def test_prompt_required_false(runner, args, expect):427    @click.command()428    @click.option("-v", "--value", prompt=True, prompt_required=False)429    @click.option("-o")430    def cli(value, o):431        if o is not None:432            return value, o433434        return value435436    result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)437    assert result.exception is None438    assert result.return_value == expect