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

The walk stopped after 200 commits: lines older than 829f383 point at it.

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 1–20why, one step back
1import platform
2import 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.now1920

Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba

line 21why, one step back
21def _create_progress(length=10, **kwargs):

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 22–34why, one step back
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:

Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2

line 35why, one step back
35 pass

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 36–37why, one step back
36
37 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)

Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba

lines 38–41why, one step back
38 assert (
39 label40 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output41 )

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 42–66why, one step back
42
4344def 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:

Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2

line 67why, one step back
67 pass

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 68–76why, one step back
68
69 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 back
77 with _create_progress(label="working") as progress:

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

line 78why, one step back
78 for _ in progress:

Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2

line 79why, one step back
79 pass

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 80–81why, one step back
80
81 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)

Merge pull request #1142 from CounterPillow/progressbar-hidden-labelDavid Lordbefore adoption3018f57

line 82why, one step back
82 assert runner.invoke(cli, []).output == "working\n"

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 83–115why, one step back
83
8485@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 back
116 with _create_progress(length, pos=pos) as progress:

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

line 117why, one step back
117 result = progress.format_pos()

Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba

line 118why, one step back
118 assert result == f"{pos}/{length}"

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 119–129why, one step back
119
120121@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 back
130 length, width=8, pos=pos, finished=finished, avg=[avg]

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 131–135why, one step back
131 ) as progress:
132 assert progress.format_bar() == expected133134135@pytest.mark.parametrize(

Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba

line 136why, one step back
136 "length, show_percent, show_pos, pos, expected",

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

line 137why, one step back
137 [

Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba

lines 138–142why, one step back
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%"),

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 143–145why, one step back
143 ],
144)145def test_progressbar_format_progress_line(

Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba

line 146why, one step back
146 runner, length, show_percent, show_pos, pos, expected

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 147–177why, one step back
147):
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):

Merge branch '8.1.x'David Lordbefore adoption7271763

lines 178–179why, one step back
178 progress = click.progressbar(length=2)
179

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 180–275why, one step back
180 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]275

Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2

lines 276–280why, one step back
276 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]

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 281–283why, one step back
281
282283def test_progressbar_item_show_func(runner, monkeypatch):

Merge pull request #1354 from JoelEager/fix-progress-barDavid Lordbefore adoption1472e3d

lines 284–285why, one step back
284 """item_show_func should show the current item being yielded."""
285

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 286–287why, one step back
286 @click.command()
287 def cli():

Merge pull request #1354 from JoelEager/fix-progress-barDavid Lordbefore adoption1472e3d

lines 288–290why, one step back
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}")

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 291–292why, one step back
291
292 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)

Merge pull request #1354 from JoelEager/fix-progress-barDavid Lordbefore adoption1472e3d

lines 293–296why, one step back
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 line

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 297–306why, one step back
297
298299def 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)

Merge pull request #1803 from pallets/progress-showDavid Lordbefore adoptionaf584b2

line 307why, one step back
307 click.echo()

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 308–354why, one step back
308
309 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(

Merge pull request #1712 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptiona28048f

line 355why, one step back
355 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 356–375why, one step back
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"),

Merge pull request #1829 from MLH-Fellowship/add-i18nDavid Lordbefore adoptionc454226

line 376why, one step back
376 (True, False, ["-v"], "Option '-v' requires an argument."),

add FloatRange to API docs (#1719)Elias Rosendahl Jensenbefore adoption829f383

lines 377–420why, one step back
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 == expect

Merge pull request #1786 from MLH-Fellowship/custom-confirm-promptDavid Lordbefore adoption1b1578d

lines 421–423why, one step back
421
422423@pytest.mark.parametrize(

Merge pull request #2158 from unparalleled-js/fix/allow-empty-when-confirmation-requiredDavid Lordbefore adoptiondeb1f0e

line 424why, one step back
424 ("prompt", "input", "default", "expect"),

Merge pull request #1786 from MLH-Fellowship/custom-confirm-promptDavid Lordbefore adoption1b1578d

line 425why, one step back
425 [

Merge pull request #2158 from unparalleled-js/fix/allow-empty-when-confirmation-requiredDavid Lordbefore adoptiondeb1f0e

lines 426–429why, one step back
426 (True, "password\npassword", None, "password"),
427 ("Confirm Password", "password\npassword\n", None, "password"),428 (True, "", "", ""),429 (False, None, None, None),

Merge pull request #1786 from MLH-Fellowship/custom-confirm-promptDavid Lordbefore adoption1b1578d

lines 430–431why, one step back
430 ],
431)

Merge pull request #2158 from unparalleled-js/fix/allow-empty-when-confirmation-requiredDavid Lordbefore adoptiondeb1f0e

line 432why, one step back
432def test_confirmation_prompt(runner, prompt, input, default, expect):

Merge pull request #1786 from MLH-Fellowship/custom-confirm-promptDavid Lordbefore adoption1b1578d

lines 433–434why, one step back
433 @click.command()
434 @click.option(

Merge pull request #2158 from unparalleled-js/fix/allow-empty-when-confirmation-requiredDavid Lordbefore adoptiondeb1f0e

lines 435–439why, one step back
435 "--password",
436 prompt=prompt,437 hide_input=True,438 default=default,439 confirmation_prompt=prompt,

Merge pull request #1786 from MLH-Fellowship/custom-confirm-promptDavid Lordbefore adoption1b1578d

lines 440–449why, one step back
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