Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

449 lines · 13.6 KiB · Python

Last changed by

Merge branch '8.1.x'David Lordbefore adoption7271763

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, **kwargs):22    progress = click.progressbar(tuple(range(length)))23    for key, value in kwargs.items():24        setattr(progress, key, value)25    return progress262728def test_progressbar_strip_regression(runner, monkeypatch):29    label = "    padded line"3031    @click.command()32    def cli():33        with _create_progress(label=label) as progress:34            for _ in progress:35                pass3637    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)38    assert (39        label40        in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output41    )424344def 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    @click.command()64    def cli():65        with click.progressbar(Hinted(10), label="test") as progress:66            for _ in progress:67                pass6869    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)70    result = runner.invoke(cli, [])71    assert result.exception is None727374def test_progressbar_hidden(runner, monkeypatch):75    @click.command()76    def cli():77        with _create_progress(label="working") as progress:78            for _ in progress:79                pass8081    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)82    assert runner.invoke(cli, []).output == "working\n"838485@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])86def test_progressbar_time_per_iteration(runner, avg, expected):87    with _create_progress(2, avg=avg) as progress:88        assert progress.time_per_iteration == expected899091@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])92def test_progressbar_eta(runner, finished, expected):93    with _create_progress(2, finished=finished, avg=[1, 4]) as progress:94        assert progress.eta == expected959697@pytest.mark.parametrize(98    "eta, expected",99    [100        (0, "00:00:00"),101        (30, "00:00:30"),102        (90, "00:01:30"),103        (900, "00:15:00"),104        (9000, "02:30:00"),105        (99999999999, "1157407d 09:46:39"),106        (None, ""),107    ],108)109def test_progressbar_format_eta(runner, eta, expected):110    with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:111        assert progress.format_eta() == expected112113114@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])115def test_progressbar_format_pos(runner, pos, length):116    with _create_progress(length, pos=pos) as progress:117        result = progress.format_pos()118        assert result == f"{pos}/{length}"119120121@pytest.mark.parametrize(122    "length, finished, pos, avg, expected",123    [124        (8, False, 7, 0, "#######-"),125        (0, True, 8, 0, "########"),126    ],127)128def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):129    with _create_progress(130        length, width=8, pos=pos, finished=finished, avg=[avg]131    ) as progress:132        assert progress.format_bar() == expected133134135@pytest.mark.parametrize(136    "length, show_percent, show_pos, pos, expected",137    [138        (0, True, True, 0, "  [--------]  0/0    0%"),139        (0, False, True, 0, "  [--------]  0/0"),140        (0, False, False, 0, "  [--------]"),141        (0, False, False, 0, "  [--------]"),142        (8, True, True, 8, "  [########]  8/8  100%"),143    ],144)145def test_progressbar_format_progress_line(146    runner, length, show_percent, show_pos, pos, expected147):148    with _create_progress(149        length,150        width=8,151        show_percent=show_percent,152        pos=pos,153        show_pos=show_pos,154    ) as progress:155        assert progress.format_progress_line() == expected156157158@pytest.mark.parametrize("test_item", ["test", None])159def test_progressbar_format_progress_line_with_show_func(runner, test_item):160    def item_show_func(item):161        return item162163    with _create_progress(164        item_show_func=item_show_func, current_item=test_item165    ) as progress:166        if test_item:167            assert progress.format_progress_line().endswith(test_item)168        else:169            assert progress.format_progress_line().endswith(progress.format_pct())170171172def test_progressbar_init_exceptions(runner):173    with pytest.raises(TypeError, match="iterable or length is required"):174        click.progressbar()175176177def test_progressbar_iter_outside_with_exceptions(runner):178    progress = click.progressbar(length=2)179180    with pytest.raises(RuntimeError, match="with block"):181        iter(progress)182183184def test_progressbar_is_iterator(runner, monkeypatch):185    @click.command()186    def cli():187        with click.progressbar(range(10), label="test") as progress:188            while True:189                try:190                    next(progress)191                except StopIteration:192                    break193194    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)195    result = runner.invoke(cli, [])196    assert result.exception is None197198199def test_choices_list_in_prompt(runner, monkeypatch):200    @click.command()201    @click.option(202        "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True203    )204    def cli_with_choices(g):205        pass206207    @click.command()208    @click.option(209        "-g",210        type=click.Choice(["none", "day", "week", "month"]),211        prompt=True,212        show_choices=False,213    )214    def cli_without_choices(g):215        pass216217    result = runner.invoke(cli_with_choices, [], input="none")218    assert "(none, day, week, month)" in result.output219220    result = runner.invoke(cli_without_choices, [], input="none")221    assert "(none, day, week, month)" not in result.output222223224@pytest.mark.parametrize(225    "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]226)227def test_file_prompt_default_format(runner, file_kwargs):228    @click.command()229    @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))230    def cli(f):231        click.echo(f.name)232233    result = runner.invoke(cli)234    assert result.output == f"file [{__file__}]: \n{__file__}\n"235236237def test_secho(runner):238    with runner.isolation() as outstreams:239        click.secho(None, nl=False)240        bytes = outstreams[0].getvalue()241        assert bytes == b""242243244@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")245@pytest.mark.parametrize(246    ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]247)248def test_secho_non_text(runner, value, expect):249    with runner.isolation() as (out, _):250        click.secho(value, nl=False, color=True, bg="magenta")251        result = out.getvalue()252        assert result == expect253254255def test_progressbar_yields_all_items(runner):256    with click.progressbar(range(3)) as progress:257        assert len(list(progress)) == 3258259260def test_progressbar_update(runner, monkeypatch):261    fake_clock = FakeClock()262263    @click.command()264    def cli():265        with click.progressbar(range(4)) as progress:266            for _ in progress:267                fake_clock.advance_time()268                print("")269270    monkeypatch.setattr(time, "time", fake_clock.time)271    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)272    output = runner.invoke(cli, []).output273274    lines = [line for line in output.split("\n") if "[" in line]275276    assert "  0%" in lines[0]277    assert " 25%  00:00:03" in lines[1]278    assert " 50%  00:00:02" in lines[2]279    assert " 75%  00:00:01" in lines[3]280    assert "100%          " in lines[4]281282283def test_progressbar_item_show_func(runner, monkeypatch):284    """item_show_func should show the current item being yielded."""285286    @click.command()287    def cli():288        with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:289            for item in progress:290                click.echo(f" item {item}")291292    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)293    lines = runner.invoke(cli).output.splitlines()294295    for i, line in enumerate(x for x in lines if "item" in x):296        assert f"{i}    item {i}" in line297298299def test_progressbar_update_with_item_show_func(runner, monkeypatch):300    @click.command()301    def cli():302        with click.progressbar(303            length=6, item_show_func=lambda x: f"Custom {x}"304        ) as progress:305            while not progress.finished:306                progress.update(2, progress.pos)307                click.echo()308309    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)310    output = runner.invoke(cli, []).output311312    lines = [line for line in output.split("\n") if "[" in line]313314    assert "Custom 0" in lines[0]315    assert "Custom 2" in lines[1]316    assert "Custom 4" in lines[2]317318319def test_progress_bar_update_min_steps(runner):320    bar = _create_progress(update_min_steps=5)321    bar.update(3)322    assert bar._completed_intervals == 3323    assert bar.pos == 0324    bar.update(2)325    assert bar._completed_intervals == 0326    assert bar.pos == 5327328329@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))330@pytest.mark.parametrize("echo", [True, False])331@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")332def test_getchar_windows(runner, monkeypatch, key_char, echo):333    monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)334    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)335    monkeypatch.setattr(click.termui, "_getchar", None)336    assert click.getchar(echo) == key_char337338339@pytest.mark.parametrize(340    "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]341)342@pytest.mark.skipif(343    not WIN, reason="Tests special character inputs using the msvcrt module."344)345def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):346    ordered_inputs = [key_char, special_key_char]347    monkeypatch.setattr(348        click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()349    )350    monkeypatch.setattr(click.termui, "_getchar", None)351    assert click.getchar() == f"{special_key_char}{key_char}"352353354@pytest.mark.parametrize(355    ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]356)357@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")358def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):359    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)360    monkeypatch.setattr(click.termui, "_getchar", None)361362    with pytest.raises(exc):363        click.getchar()364365366@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")367def test_fast_edit(runner):368    result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")369    assert result == "aTest\nbTest\n"370371372@pytest.mark.parametrize(373    ("prompt_required", "required", "args", "expect"),374    [375        (True, False, None, "prompt"),376        (True, False, ["-v"], "Option '-v' requires an argument."),377        (False, True, None, "prompt"),378        (False, True, ["-v"], "prompt"),379    ],380)381def test_prompt_required_with_required(runner, prompt_required, required, args, expect):382    @click.command()383    @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)384    def cli(v):385        click.echo(str(v))386387    result = runner.invoke(cli, args, input="prompt")388    assert expect in result.output389390391@pytest.mark.parametrize(392    ("args", "expect"),393    [394        # Flag not passed, don't prompt.395        pytest.param(None, None, id="no flag"),396        # Flag and value passed, don't prompt.397        pytest.param(["-v", "value"], "value", id="short sep value"),398        pytest.param(["--value", "value"], "value", id="long sep value"),399        pytest.param(["-vvalue"], "value", id="short join value"),400        pytest.param(["--value=value"], "value", id="long join value"),401        # Flag without value passed, prompt.402        pytest.param(["-v"], "prompt", id="short no value"),403        pytest.param(["--value"], "prompt", id="long no value"),404        # Don't use next option flag as value.405        pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),406    ],407)408def test_prompt_required_false(runner, args, expect):409    @click.command()410    @click.option("-v", "--value", prompt=True, prompt_required=False)411    @click.option("-o")412    def cli(value, o):413        if o is not None:414            return value, o415416        return value417418    result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)419    assert result.exception is None420    assert result.return_value == expect421422423@pytest.mark.parametrize(424    ("prompt", "input", "default", "expect"),425    [426        (True, "password\npassword", None, "password"),427        ("Confirm Password", "password\npassword\n", None, "password"),428        (True, "", "", ""),429        (False, None, None, None),430    ],431)432def test_confirmation_prompt(runner, prompt, input, default, expect):433    @click.command()434    @click.option(435        "--password",436        prompt=prompt,437        hide_input=True,438        default=default,439        confirmation_prompt=prompt,440    )441    def cli(password):442        return password443444    result = runner.invoke(cli, input=input, standalone_mode=False)445    assert result.exception is None446    assert result.return_value == expect447448    if prompt == "Confirm Password":449        assert "Confirm Password: " in result.output