test_termui.py
This file
Path
tests/test_termui.py
443 lines · 13.5 KiB · Python
Last changed by
Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
History of this fileTake 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 with pytest.raises(RuntimeError, match="with block"):179 progress = click.progressbar(length=2)180 iter(progress)181182183def test_progressbar_is_iterator(runner, monkeypatch):184 @click.command()185 def cli():186 with click.progressbar(range(10), label="test") as progress:187 while True:188 try:189 next(progress)190 except StopIteration:191 break192193 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)194 result = runner.invoke(cli, [])195 assert result.exception is None196197198def test_choices_list_in_prompt(runner, monkeypatch):199 @click.command()200 @click.option(201 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True202 )203 def cli_with_choices(g):204 pass205206 @click.command()207 @click.option(208 "-g",209 type=click.Choice(["none", "day", "week", "month"]),210 prompt=True,211 show_choices=False,212 )213 def cli_without_choices(g):214 pass215216 result = runner.invoke(cli_with_choices, [], input="none")217 assert "(none, day, week, month)" in result.output218219 result = runner.invoke(cli_without_choices, [], input="none")220 assert "(none, day, week, month)" not in result.output221222223@pytest.mark.parametrize(224 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]225)226def test_file_prompt_default_format(runner, file_kwargs):227 @click.command()228 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))229 def cli(f):230 click.echo(f.name)231232 result = runner.invoke(cli)233 assert result.output == f"file [{__file__}]: \n{__file__}\n"234235236def test_secho(runner):237 with runner.isolation() as outstreams:238 click.secho(None, nl=False)239 bytes = outstreams[0].getvalue()240 assert bytes == b""241242243@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")244@pytest.mark.parametrize(245 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]246)247def test_secho_non_text(runner, value, expect):248 with runner.isolation() as (out, _):249 click.secho(value, nl=False, color=True, bg="magenta")250 result = out.getvalue()251 assert result == expect252253254def test_progressbar_yields_all_items(runner):255 with click.progressbar(range(3)) as progress:256 assert len(list(progress)) == 3257258259def test_progressbar_update(runner, monkeypatch):260 fake_clock = FakeClock()261262 @click.command()263 def cli():264 with click.progressbar(range(4)) as progress:265 for _ in progress:266 fake_clock.advance_time()267 print("")268269 monkeypatch.setattr(time, "time", fake_clock.time)270 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)271 output = runner.invoke(cli, []).output272273 lines = [line for line in output.split("\n") if "[" in line]274275 assert " 0%" in lines[0]276 assert " 25% 00:00:03" in lines[1]277 assert " 50% 00:00:02" in lines[2]278 assert " 75% 00:00:01" in lines[3]279 assert "100% " in lines[4]280281282def test_progressbar_item_show_func(runner, monkeypatch):283 """item_show_func should show the current item being yielded."""284285 @click.command()286 def cli():287 with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:288 for item in progress:289 click.echo(f" item {item}")290291 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)292 lines = runner.invoke(cli).output.splitlines()293294 for i, line in enumerate(x for x in lines if "item" in x):295 assert f"{i} item {i}" in line296297298def test_progressbar_update_with_item_show_func(runner, monkeypatch):299 @click.command()300 def cli():301 with click.progressbar(302 length=6, item_show_func=lambda x: f"Custom {x}"303 ) as progress:304 while not progress.finished:305 progress.update(2, progress.pos)306 click.echo()307308 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)309 output = runner.invoke(cli, []).output310311 lines = [line for line in output.split("\n") if "[" in line]312313 assert "Custom 0" in lines[0]314 assert "Custom 2" in lines[1]315 assert "Custom 4" in lines[2]316317318def test_progress_bar_update_min_steps(runner):319 bar = _create_progress(update_min_steps=5)320 bar.update(3)321 assert bar._completed_intervals == 3322 assert bar.pos == 0323 bar.update(2)324 assert bar._completed_intervals == 0325 assert bar.pos == 5326327328@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))329@pytest.mark.parametrize("echo", [True, False])330@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")331def test_getchar_windows(runner, monkeypatch, key_char, echo):332 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)333 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)334 monkeypatch.setattr(click.termui, "_getchar", None)335 assert click.getchar(echo) == key_char336337338@pytest.mark.parametrize(339 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]340)341@pytest.mark.skipif(342 not WIN, reason="Tests special character inputs using the msvcrt module."343)344def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):345 ordered_inputs = [key_char, special_key_char]346 monkeypatch.setattr(347 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()348 )349 monkeypatch.setattr(click.termui, "_getchar", None)350 assert click.getchar() == f"{special_key_char}{key_char}"351352353@pytest.mark.parametrize(354 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]355)356@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")357def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):358 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)359 monkeypatch.setattr(click.termui, "_getchar", None)360361 with pytest.raises(exc):362 click.getchar()363364365@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")366def test_fast_edit(runner):367 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")368 assert result == "aTest\nbTest\n"369370371@pytest.mark.parametrize(372 ("prompt_required", "required", "args", "expect"),373 [374 (True, False, None, "prompt"),375 (True, False, ["-v"], "Option '-v' requires an argument."),376 (False, True, None, "prompt"),377 (False, True, ["-v"], "prompt"),378 ],379)380def test_prompt_required_with_required(runner, prompt_required, required, args, expect):381 @click.command()382 @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)383 def cli(v):384 click.echo(str(v))385386 result = runner.invoke(cli, args, input="prompt")387 assert expect in result.output388389390@pytest.mark.parametrize(391 ("args", "expect"),392 [393 # Flag not passed, don't prompt.394 pytest.param(None, None, id="no flag"),395 # Flag and value passed, don't prompt.396 pytest.param(["-v", "value"], "value", id="short sep value"),397 pytest.param(["--value", "value"], "value", id="long sep value"),398 pytest.param(["-vvalue"], "value", id="short join value"),399 pytest.param(["--value=value"], "value", id="long join value"),400 # Flag without value passed, prompt.401 pytest.param(["-v"], "prompt", id="short no value"),402 pytest.param(["--value"], "prompt", id="long no value"),403 # Don't use next option flag as value.404 pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),405 ],406)407def test_prompt_required_false(runner, args, expect):408 @click.command()409 @click.option("-v", "--value", prompt=True, prompt_required=False)410 @click.option("-o")411 def cli(value, o):412 if o is not None:413 return value, o414415 return value416417 result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)418 assert result.exception is None419 assert result.return_value == expect420421422@pytest.mark.parametrize(423 ("prompt", "input", "expect"),424 [425 (True, "password\npassword", "password"),426 ("Confirm Password", "password\npassword\n", "password"),427 (False, None, None),428 ],429)430def test_confirmation_prompt(runner, prompt, input, expect):431 @click.command()432 @click.option(433 "--password", prompt=prompt, hide_input=True, confirmation_prompt=prompt434 )435 def cli(password):436 return password437438 result = runner.invoke(cli, input=input, standalone_mode=False)439 assert result.exception is None440 assert result.return_value == expect441442 if prompt == "Confirm Password":443 assert "Confirm Password: " in result.output