Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

487 lines · 14.9 KiB · Python

Last changed by

Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c

History of this file

Take it

1import platform2import tempfile3import time45import pytest67import click._termui_impl8from click._compat import WIN91011class FakeClock: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, **kwargs):23    progress = click.progressbar(tuple(range(length)))24    for key, value in kwargs.items():25        setattr(progress, key, value)26    return progress272829def test_progressbar_strip_regression(runner, monkeypatch):30    label = "    padded line"3132    @click.command()33    def cli():34        with _create_progress(label=label) as progress:35            for _ in progress:36                pass3738    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)39    assert (40        label41        in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output42    )434445def test_progressbar_length_hint(runner, monkeypatch):46    class Hinted: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    @click.command()65    def cli():66        with click.progressbar(Hinted(10), label="test") as progress:67            for _ in progress:68                pass6970    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)71    result = runner.invoke(cli, [])72    assert result.exception is None737475def test_progressbar_no_tty(runner, monkeypatch):76    @click.command()77    def cli():78        with _create_progress(label="working") as progress:79            for _ in progress:80                pass8182    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)83    assert runner.invoke(cli, []).output == "working\n"848586def test_progressbar_hidden_manual(runner, monkeypatch):87    @click.command()88    def cli():89        with _create_progress(label="see nothing", hidden=True) as progress:90            for _ in progress:91                pass9293    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)94    assert runner.invoke(cli, []).output == ""959697@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])98def test_progressbar_time_per_iteration(runner, avg, expected):99    with _create_progress(2, avg=avg) as progress:100        assert progress.time_per_iteration == expected101102103@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])104def test_progressbar_eta(runner, finished, expected):105    with _create_progress(2, finished=finished, avg=[1, 4]) as progress:106        assert progress.eta == expected107108109@pytest.mark.parametrize(110    "eta, expected",111    [112        (0, "00:00:00"),113        (30, "00:00:30"),114        (90, "00:01:30"),115        (900, "00:15:00"),116        (9000, "02:30:00"),117        (99999999999, "1157407d 09:46:39"),118        (None, ""),119    ],120)121def test_progressbar_format_eta(runner, eta, expected):122    with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:123        assert progress.format_eta() == expected124125126@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])127def test_progressbar_format_pos(runner, pos, length):128    with _create_progress(length, pos=pos) as progress:129        result = progress.format_pos()130        assert result == f"{pos}/{length}"131132133@pytest.mark.parametrize(134    "length, finished, pos, avg, expected",135    [136        (8, False, 7, 0, "#######-"),137        (0, True, 8, 0, "########"),138    ],139)140def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):141    with _create_progress(142        length, width=8, pos=pos, finished=finished, avg=[avg]143    ) as progress:144        assert progress.format_bar() == expected145146147@pytest.mark.parametrize(148    "length, show_percent, show_pos, pos, expected",149    [150        (0, True, True, 0, "  [--------]  0/0    0%"),151        (0, False, True, 0, "  [--------]  0/0"),152        (0, False, False, 0, "  [--------]"),153        (0, False, False, 0, "  [--------]"),154        (8, True, True, 8, "  [########]  8/8  100%"),155    ],156)157def test_progressbar_format_progress_line(158    runner, length, show_percent, show_pos, pos, expected159):160    with _create_progress(161        length,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    progress = click.progressbar(length=2)191192    with pytest.raises(RuntimeError, match="with block"):193        iter(progress)194195196def test_progressbar_is_iterator(runner, monkeypatch):197    @click.command()198    def cli():199        with click.progressbar(range(10), label="test") as progress:200            while True:201                try:202                    next(progress)203                except StopIteration:204                    break205206    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)207    result = runner.invoke(cli, [])208    assert result.exception is None209210211def test_choices_list_in_prompt(runner, monkeypatch):212    @click.command()213    @click.option(214        "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True215    )216    def cli_with_choices(g):217        pass218219    @click.command()220    @click.option(221        "-g",222        type=click.Choice(["none", "day", "week", "month"]),223        prompt=True,224        show_choices=False,225    )226    def cli_without_choices(g):227        pass228229    result = runner.invoke(cli_with_choices, [], input="none")230    assert "(none, day, week, month)" in result.output231232    result = runner.invoke(cli_without_choices, [], input="none")233    assert "(none, day, week, month)" not in result.output234235236@pytest.mark.parametrize(237    "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]238)239def test_file_prompt_default_format(runner, file_kwargs):240    @click.command()241    @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))242    def cli(f):243        click.echo(f.name)244245    result = runner.invoke(cli)246    assert result.output == f"file [{__file__}]: \n{__file__}\n"247248249def test_secho(runner):250    with runner.isolation() as outstreams:251        click.secho(None, nl=False)252        bytes = outstreams[0].getvalue()253        assert bytes == b""254255256@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")257@pytest.mark.parametrize(258    ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]259)260def test_secho_non_text(runner, value, expect):261    with runner.isolation() as (out, _, _):262        click.secho(value, nl=False, color=True, bg="magenta")263        result = out.getvalue()264        assert result == expect265266267def test_progressbar_yields_all_items(runner):268    with click.progressbar(range(3)) as progress:269        assert len(list(progress)) == 3270271272def test_progressbar_update(runner, monkeypatch):273    fake_clock = FakeClock()274275    @click.command()276    def cli():277        with click.progressbar(range(4)) as progress:278            for _ in progress:279                fake_clock.advance_time()280                print("")281282    monkeypatch.setattr(time, "time", fake_clock.time)283    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)284    output = runner.invoke(cli, []).output285286    lines = [line for line in output.split("\n") if "[" in line]287288    assert "  0%" in lines[0]289    assert " 25%  00:00:03" in lines[1]290    assert " 50%  00:00:02" in lines[2]291    assert " 75%  00:00:01" in lines[3]292    assert "100%          " in lines[4]293294295def test_progressbar_item_show_func(runner, monkeypatch):296    """item_show_func should show the current item being yielded."""297298    @click.command()299    def cli():300        with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:301            for item in progress:302                click.echo(f" item {item}")303304    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)305    lines = runner.invoke(cli).output.splitlines()306307    for i, line in enumerate(x for x in lines if "item" in x):308        assert f"{i}    item {i}" in line309310311def test_progressbar_update_with_item_show_func(runner, monkeypatch):312    @click.command()313    def cli():314        with click.progressbar(315            length=6, item_show_func=lambda x: f"Custom {x}"316        ) as progress:317            while not progress.finished:318                progress.update(2, progress.pos)319                click.echo()320321    monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)322    output = runner.invoke(cli, []).output323324    lines = [line for line in output.split("\n") if "[" in line]325326    assert "Custom 0" in lines[0]327    assert "Custom 2" in lines[1]328    assert "Custom 4" in lines[2]329330331def test_progress_bar_update_min_steps(runner):332    bar = _create_progress(update_min_steps=5)333    bar.update(3)334    assert bar._completed_intervals == 3335    assert bar.pos == 0336    bar.update(2)337    assert bar._completed_intervals == 0338    assert bar.pos == 5339340341@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))342@pytest.mark.parametrize("echo", [True, False])343@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")344def test_getchar_windows(runner, monkeypatch, key_char, echo):345    monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)346    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)347    monkeypatch.setattr(click.termui, "_getchar", None)348    assert click.getchar(echo) == key_char349350351@pytest.mark.parametrize(352    "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]353)354@pytest.mark.skipif(355    not WIN, reason="Tests special character inputs using the msvcrt module."356)357def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):358    ordered_inputs = [key_char, special_key_char]359    monkeypatch.setattr(360        click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()361    )362    monkeypatch.setattr(click.termui, "_getchar", None)363    assert click.getchar() == f"{special_key_char}{key_char}"364365366@pytest.mark.parametrize(367    ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]368)369@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")370def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):371    monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)372    monkeypatch.setattr(click.termui, "_getchar", None)373374    with pytest.raises(exc):375        click.getchar()376377378@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")379def test_fast_edit(runner):380    result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")381    assert result == "aTest\nbTest\n"382383384@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")385def test_edit(runner):386    with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:387        named_tempfile.write("a\nb")388        named_tempfile.flush()389390        result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")391        assert result is None392393        # We need ot reopen the file as it becomes unreadable after the edit.394        with open(named_tempfile.name) as reopened_file:395            assert reopened_file.read() == "aTest\nbTest"396397398@pytest.mark.parametrize(399    ("prompt_required", "required", "args", "expect"),400    [401        (True, False, None, "prompt"),402        (True, False, ["-v"], "Option '-v' requires an argument."),403        (False, True, None, "prompt"),404        (False, True, ["-v"], "prompt"),405    ],406)407def test_prompt_required_with_required(runner, prompt_required, required, args, expect):408    @click.command()409    @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)410    def cli(v):411        click.echo(str(v))412413    result = runner.invoke(cli, args, input="prompt")414    assert expect in result.output415416417@pytest.mark.parametrize(418    ("args", "expect"),419    [420        # Flag not passed, don't prompt.421        pytest.param(None, None, id="no flag"),422        # Flag and value passed, don't prompt.423        pytest.param(["-v", "value"], "value", id="short sep value"),424        pytest.param(["--value", "value"], "value", id="long sep value"),425        pytest.param(["-vvalue"], "value", id="short join value"),426        pytest.param(["--value=value"], "value", id="long join value"),427        # Flag without value passed, prompt.428        pytest.param(["-v"], "prompt", id="short no value"),429        pytest.param(["--value"], "prompt", id="long no value"),430        # Don't use next option flag as value.431        pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),432    ],433)434def test_prompt_required_false(runner, args, expect):435    @click.command()436    @click.option("-v", "--value", prompt=True, prompt_required=False)437    @click.option("-o")438    def cli(value, o):439        if o is not None:440            return value, o441442        return value443444    result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)445    assert result.exception is None446    assert result.return_value == expect447448449@pytest.mark.parametrize(450    ("prompt", "input", "default", "expect"),451    [452        (True, "password\npassword", None, "password"),453        ("Confirm Password", "password\npassword\n", None, "password"),454        (True, "", "", ""),455        (False, None, None, None),456    ],457)458def test_confirmation_prompt(runner, prompt, input, default, expect):459    @click.command()460    @click.option(461        "--password",462        prompt=prompt,463        hide_input=True,464        default=default,465        confirmation_prompt=prompt,466    )467    def cli(password):468        return password469470    result = runner.invoke(cli, input=input, standalone_mode=False)471    assert result.exception is None472    assert result.return_value == expect473474    if prompt == "Confirm Password":475        assert "Confirm Password: " in result.output476477478def test_false_show_default_cause_no_default_display_in_prompt(runner):479    @click.command()480    @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")481    def cmd(arg1):482        pass483484    # Confirm that the default value is not included in the output when `show_default`485    # is False486    result = runner.invoke(cmd, input="my-input", standalone_mode=False)487    assert "my-default-value" not in result.output