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
The walk stopped after 200 commits: lines older than 8ae9f16 point at it.
Merge pull request #1146 from segevfiner/style-non-textDavid Lordbefore adoption77cb257
line 1why, one step back1import platformMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 2–9why, one step back2import time34import pytest56import click._termui_impl7from click._compat import WIN89Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 10why, one step back10class FakeClock:Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 11–20why, one step back11 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.now1920Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
line 21why, one step back21def _create_progress(length=10, **kwargs):Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 22–34why, one step back22 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:Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2
line 35why, one step back35 passMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 36–37why, one step back3637 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
lines 38–41why, one step back38 assert (39 label40 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output41 )Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 42–44why, one step back424344def test_progressbar_length_hint(runner, monkeypatch):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 45why, one step back45 class Hinted:Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 46–66why, one step back46 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:Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2
line 67why, one step back67 passMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 68–76why, one step back6869 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():Merge pull request #1142 from CounterPillow/progressbar-hidden-labelDavid Lordbefore adoption3018f57
line 77why, one step back77 with _create_progress(label="working") as progress:Merge branch '7.x'David Lordbefore adoption8ae9f16
line 78why, one step back78 for _ in progress:Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2
line 79why, one step back79 passMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 80–81why, one step back8081 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)Merge pull request #1142 from CounterPillow/progressbar-hidden-labelDavid Lordbefore adoption3018f57
line 82why, one step back82 assert runner.invoke(cli, []).output == "working\n"Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 83–115why, one step back838485@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):Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
line 116why, one step back116 with _create_progress(length, pos=pos) as progress:Merge branch '7.x'David Lordbefore adoption8ae9f16
line 117why, one step back117 result = progress.format_pos()Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
line 118why, one step back118 assert result == f"{pos}/{length}"Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 119–129why, one step back119120121@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(Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
line 130why, one step back130 length, width=8, pos=pos, finished=finished, avg=[avg]Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 131–135why, one step back131 ) as progress:132 assert progress.format_bar() == expected133134135@pytest.mark.parametrize(Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
line 136why, one step back136 "length, show_percent, show_pos, pos, expected",Merge branch '7.x'David Lordbefore adoption8ae9f16
line 137why, one step back137 [Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
lines 138–142why, one step back138 (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%"),Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 143–145why, one step back143 ],144)145def test_progressbar_format_progress_line(Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
line 146why, one step back146 runner, length, show_percent, show_pos, pos, expectedMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 147–232why, one step back147):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)Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 233why, one step back233 assert result.output == f"file [{__file__}]: \n{__file__}\n"Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 234–240why, one step back234235236def test_secho(runner):237 with runner.isolation() as outstreams:238 click.secho(None, nl=False)239 bytes = outstreams[0].getvalue()240 assert bytes == b""Merge pull request #1146 from segevfiner/style-non-textDavid Lordbefore adoption77cb257
lines 241–251why, one step back241242243@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 == expectMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 252–274why, one step back252253254def 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]274Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2
lines 275–279why, one step back275 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]Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 280–282why, one step back280281282def test_progressbar_item_show_func(runner, monkeypatch):Merge pull request #1354 from JoelEager/fix-progress-barDavid Lordbefore adoption1472e3d
lines 283–284why, one step back283 """item_show_func should show the current item being yielded."""284Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 285–286why, one step back285 @click.command()286 def cli():Merge pull request #1354 from JoelEager/fix-progress-barDavid Lordbefore adoption1472e3d
lines 287–289why, one step back287 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}")Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 290–291why, one step back290291 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)Merge pull request #1354 from JoelEager/fix-progress-barDavid Lordbefore adoption1472e3d
lines 292–295why, one step back292 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 lineMerge branch '7.x'David Lordbefore adoption8ae9f16
lines 296–301why, one step back296297298def test_progressbar_update_with_item_show_func(runner, monkeypatch):299 @click.command()300 def cli():301 with click.progressbar(Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 302why, one step back302 length=6, item_show_func=lambda x: f"Custom {x}"Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 303–305why, one step back303 ) as progress:304 while not progress.finished:305 progress.update(2, progress.pos)Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2
line 306why, one step back306 click.echo()Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 307–317why, one step back307308 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]316317skip frequent progress bar renders (#1698)Shakil Rafibefore adoptionacc91bc
lines 318–327why, one step back318def 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 == 5326327Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 328why, one step back328@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 329–338why, one step back329@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(Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 339why, one step back339 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 340–349why, one step back340)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)Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 350why, one step back350 assert click.getchar() == f"{special_key_char}{key_char}"Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 351–353why, one step back351352353@pytest.mark.parametrize(Merge pull request #1712 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptiona28048f
line 354why, one step back354 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]Merge branch '7.x'David Lordbefore adoption8ae9f16
lines 355–362why, one step back355)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()Merge pull request #1050 from giovannipizzi/fix-fast-editDavid Lordbefore adoption97fde8b
lines 363–368why, one step back363364365@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"Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348
lines 369–374why, one step back369370371@pytest.mark.parametrize(372 ("prompt_required", "required", "args", "expect"),373 [374 (True, False, None, "prompt"),Merge pull request #1829 from MLH-Fellowship/add-i18nDavid Lordbefore adoptionc454226
line 375why, one step back375 (True, False, ["-v"], "Option '-v' requires an argument."),Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348
lines 376–419why, one step back376 (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 == expectMerge pull request #1786 from MLH-Fellowship/custom-confirm-promptDavid Lordbefore adoption1b1578d
lines 420–443why, one step back420421422@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