Make test echo file.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Edward G · committed by Edward G · parent df2e5ed · Browse files · 4 files·+435 added−430 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+435 added−430 removed
- tests:+435 added−430 removed
Provenance
- Commit
a391797- Tree
94db820- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent
df2e5ed
4 files changed+435 added−430 removed
added:tests/test_utils_2/__init__.py
added:tests/test_utils_2/test_echo_via_pager.py+259 added
1+import os2+import subprocess3+import sys4+from collections import namedtuple5+from contextlib import nullcontext6+from functools import partial7+from unittest.mock import patch8+9+import pytest10+11+import click12+from click._compat import WIN13+14+EchoViaPagerTest = namedtuple(15+ "EchoViaPagerTest",16+ (17+ "description",18+ "test_input",19+ "expected_pager",20+ "expected_stdout",21+ "expected_stderr",22+ "expected_error",23+ ),24+)25+26+27+def _test_gen_func():28+ yield "a"29+ yield "b"30+ yield "c"31+ yield "abc"32+33+34+def _test_gen_func_fails():35+ raise RuntimeError("This is a test.")36+ yield # unreachable, keeps this a generator function37+38+39+def _test_gen_func_yields_then_fails():40+ yield "test"41+ raise RuntimeError("This is a test.")42+43+44+def _test_gen_func_echo(file=None):45+ yield "test"46+ click.echo("hello", file=file)47+ yield "test"48+49+50+def _test_simulate_keyboard_interrupt(file=None):51+ yield "output_before_keyboard_interrupt"52+ raise KeyboardInterrupt()53+54+55+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")56+@pytest.mark.parametrize(57+ "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]58+)59+@pytest.mark.parametrize(60+ "test",61+ [62+ # We need to pass a parameter function instead of a plain param63+ # as pytest.mark.parametrize will reuse the parameters causing the64+ # generators to be used up so they will not yield anymore65+ EchoViaPagerTest(66+ description="Plain string argument",67+ test_input=lambda: "just text",68+ expected_pager="just text\n",69+ expected_stdout="",70+ expected_stderr="",71+ expected_error=None,72+ ),73+ EchoViaPagerTest(74+ description="Iterable argument",75+ test_input=lambda: ["itera", "ble"],76+ expected_pager="iterable\n",77+ expected_stdout="",78+ expected_stderr="",79+ expected_error=None,80+ ),81+ EchoViaPagerTest(82+ description="Generator function argument",83+ test_input=lambda: _test_gen_func,84+ expected_pager="abcabc\n",85+ expected_stdout="",86+ expected_stderr="",87+ expected_error=None,88+ ),89+ EchoViaPagerTest(90+ description="String generator argument",91+ test_input=lambda: _test_gen_func(),92+ expected_pager="abcabc\n",93+ expected_stdout="",94+ expected_stderr="",95+ expected_error=None,96+ ),97+ EchoViaPagerTest(98+ description="Number generator expression argument",99+ test_input=lambda: (c for c in range(6)),100+ expected_pager="012345\n",101+ expected_stdout="",102+ expected_stderr="",103+ expected_error=None,104+ ),105+ EchoViaPagerTest(106+ description="Exception in generator function argument",107+ test_input=lambda: _test_gen_func_fails,108+ # Because generator throws early on, the pager did not have109+ # a chance yet to write the file.110+ expected_pager="",111+ expected_stdout="",112+ expected_stderr="",113+ expected_error=RuntimeError,114+ ),115+ EchoViaPagerTest(116+ description="Exception in generator argument",117+ test_input=lambda: _test_gen_func_fails,118+ # Because generator throws early on, the pager did not have a119+ # chance yet to write the file.120+ expected_pager="",121+ expected_stdout="",122+ expected_stderr="",123+ expected_error=RuntimeError,124+ ),125+ EchoViaPagerTest(126+ description="Keyboard interrupt should not terminate the pager",127+ test_input=lambda: _test_simulate_keyboard_interrupt(),128+ # Due to the keyboard interrupt during pager execution, click program129+ # should abort, but the pager should stay open.130+ # This allows users to cancel the program and search in the pager131+ # output, before they decide to terminate the pager.132+ expected_pager="output_before_keyboard_interrupt",133+ expected_stdout="",134+ expected_stderr="",135+ expected_error=KeyboardInterrupt,136+ ),137+ EchoViaPagerTest(138+ description="Writing to stdout during generator execution",139+ test_input=lambda: _test_gen_func_echo(),140+ expected_pager="testtest\n",141+ expected_stdout="hello\n",142+ expected_stderr="",143+ expected_error=None,144+ ),145+ EchoViaPagerTest(146+ description="Writing to stderr during generator execution",147+ test_input=lambda: _test_gen_func_echo(file=sys.stderr),148+ expected_pager="testtest\n",149+ expected_stdout="",150+ expected_stderr="hello\n",151+ expected_error=None,152+ ),153+ ],154+)155+def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):156+ monkeypatch.setitem(os.environ, "PAGER", pager_cmd)157+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)158+159+ test_input = test.test_input()160+ expected_pager = test.expected_pager161+ expected_stdout = test.expected_stdout162+ expected_stderr = test.expected_stderr163+ expected_error = test.expected_error164+165+ check_raise = pytest.raises(expected_error) if expected_error else nullcontext()166+167+ pager_out_tmp = tmp_path / "pager_out.txt"168+ with pager_out_tmp.open("w") as f:169+ force_subprocess_stdout = patch.object(170+ subprocess,171+ "Popen",172+ partial(subprocess.Popen, stdout=f),173+ )174+ with force_subprocess_stdout:175+ with check_raise:176+ click.echo_via_pager(test_input)177+178+ out, err = capfd.readouterr()179+180+ pager = pager_out_tmp.read_text()181+182+ assert pager == expected_pager, (183+ f"Unexpected pager output in test case '{test.description}'"184+ )185+ assert out == expected_stdout, (186+ f"Unexpected stdout in test case '{test.description}'"187+ )188+ assert err == expected_stderr, (189+ f"Unexpected stderr in test case '{test.description}'"190+ )191+192+193+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")194+def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):195+ """A generator that yields then raises: click writes the partial output to196+ the pager stream before propagating the exception.197+198+ The pager file content is intentionally NOT asserted: pipe-drain timing199+ between click and the pager subprocess is outside click's control200+ (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent201+ to the pager, which is deterministic regardless of scheduling.202+ """203+ monkeypatch.setitem(os.environ, "PAGER", "cat")204+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)205+206+ writes: list[str] = []207+ real_write = click._termui_impl.MaybeStripAnsi.write208+209+ def spy(self, text):210+ writes.append(text)211+ return real_write(self, text)212+213+ monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)214+215+ pager_out_tmp = tmp_path / "pager_out.txt"216+ with (217+ pager_out_tmp.open("w") as f,218+ patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),219+ pytest.raises(RuntimeError, match="This is a test."),220+ ):221+ click.echo_via_pager(_test_gen_func_yields_then_fails())222+223+ assert "".join(writes) == "test", (224+ f"click should have written the yielded chunk before exception, got {writes!r}"225+ )226+227+228+@pytest.mark.stress229+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")230+@pytest.mark.parametrize("_", range(1000))231+def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):232+ """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.233+234+ Regression coverage for the cleanup path in ``_pipepager``'s exception235+ handler (issue #2899, PR #3470). Each iteration spawns a real pager236+ subprocess, raises before any data is written and check there is no leak.237+ """238+ monkeypatch.setitem(os.environ, "PAGER", "cat")239+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)240+241+ spawned: list[subprocess.Popen] = []242+ real_popen = subprocess.Popen243+244+ def tracking_popen(*args, **kwargs):245+ p = real_popen(*args, **kwargs)246+ spawned.append(p)247+ return p248+249+ pager_out_tmp = tmp_path / "pager_out.txt"250+ with (251+ pager_out_tmp.open("w") as f,252+ patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),253+ pytest.raises(RuntimeError),254+ ):255+ click.echo_via_pager(_test_gen_func_fails())256+257+ assert spawned, "pager subprocess was never started"258+ for p in spawned:259+ assert p.returncode is not None, "pager subprocess not reaped"added:tests/test_utils_2/test_echo.py+176 added
1+import sys2+from io import BytesIO3+from io import StringIO4+5+import pytest6+7+import click._termui_impl8+import click.utils9+from click._compat import WIN10+11+12+def test_echo(runner):13+ with runner.isolation() as outstreams:14+ click.echo("\N{SNOWMAN}")15+ click.echo(b"\x44\x44")16+ click.echo(42, nl=False)17+ click.echo(b"a", nl=False)18+ click.echo("\x1b[31mx\x1b[39m", nl=False)19+ bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")20+ assert bytes == b"\xe2\x98\x83\nDD\n42ax"21+22+ # if wrapped, we expect bytes to survive.23+ @click.command()24+ def cli():25+ click.echo(b"\xf6")26+27+ result = runner.invoke(cli, [])28+ assert result.stdout_bytes == b"\xf6\n"29+30+ # Ensure we do not strip for bytes.31+ with runner.isolation() as outstreams:32+ click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)33+ assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"34+35+36+def test_echo_custom_file():37+ f = StringIO()38+ click.echo("hello", file=f)39+ assert f.getvalue() == "hello\n"40+41+ b = BytesIO()42+ click.echo(b"", b)43+ assert b.getvalue() == b"\n"44+45+46+def test_echo_no_streams(monkeypatch, runner):47+ """echo should not fail when stdout and stderr are None with pythonw on Windows."""48+ with runner.isolation():49+ sys.stdout = None50+ sys.stderr = None51+ click.echo("test")52+ click.echo("test", err=True)53+54+55+def test_echo_with_capsys(capsys):56+ click.echo("Capture me.")57+ out, err = capsys.readouterr()58+ assert out == "Capture me.\n"59+60+61+def test_echo_color_flag(monkeypatch, capfd):62+ isatty = True63+ monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)64+65+ text = "foo"66+ styled_text = click.style(text, fg="red")67+ assert styled_text == "\x1b[31mfoo\x1b[0m"68+69+ click.echo(styled_text, color=False)70+ out, err = capfd.readouterr()71+ assert out == f"{text}\n"72+73+ click.echo(styled_text, color=True)74+ out, err = capfd.readouterr()75+ assert out == f"{styled_text}\n"76+77+ isatty = True78+ click.echo(styled_text)79+ out, err = capfd.readouterr()80+ assert out == f"{styled_text}\n"81+82+ isatty = False83+ # Faking isatty() is not enough on Windows;84+ # the implementation caches the colorama wrapped stream85+ # so we have to use a new stream for each test86+ stream = StringIO()87+ click.echo(styled_text, file=stream)88+ assert stream.getvalue() == f"{text}\n"89+90+ stream = StringIO()91+ click.echo(styled_text, file=stream, color=True)92+ assert stream.getvalue() == f"{styled_text}\n"93+94+95+@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")96+def test_echo_writing_to_standard_error(capfd, monkeypatch):97+ def emulate_input(text):98+ """Emulate keyboard input."""99+ monkeypatch.setattr(sys, "stdin", StringIO(text))100+101+ click.echo("Echo to standard output")102+ out, err = capfd.readouterr()103+ assert out == "Echo to standard output\n"104+ assert err == ""105+106+ click.echo("Echo to standard error", err=True)107+ out, err = capfd.readouterr()108+ assert out == ""109+ assert err == "Echo to standard error\n"110+111+ emulate_input("asdlkj\n")112+ click.prompt("Prompt to stdin")113+ out, err = capfd.readouterr()114+ assert out == "Prompt to stdin: "115+ assert err == ""116+117+ emulate_input("asdlkj\n")118+ click.prompt("Prompt to stdin with no suffix", prompt_suffix="")119+ out, err = capfd.readouterr()120+ assert out == "Prompt to stdin with no suffix"121+ assert err == ""122+123+ # On non-Windows the full prompt goes through redirect_stdout so124+ # nothing leaks to stdout when err=True.125+ # https://github.com/pallets/click/issues/2968126+ emulate_input("asdlkj\n")127+ click.prompt("Prompt to stderr", err=True)128+ out, err = capfd.readouterr()129+ assert out == ""130+ assert err == "Prompt to stderr: "131+132+ # https://github.com/pallets/click/issues/3019133+ emulate_input("asdlkj\n")134+ click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)135+ out, err = capfd.readouterr()136+ assert out == ""137+ assert err == "Prompt to stderr with no suffix"138+139+ emulate_input("y\n")140+ click.confirm("Prompt to stdin")141+ out, err = capfd.readouterr()142+ assert out == "Prompt to stdin [y/N]: "143+ assert err == ""144+145+ emulate_input("y\n")146+ click.confirm("Prompt to stdin with no suffix", prompt_suffix="")147+ out, err = capfd.readouterr()148+ assert out == "Prompt to stdin with no suffix [y/N]"149+ assert err == ""150+151+ # https://github.com/pallets/click/issues/2968152+ emulate_input("y\n")153+ click.confirm("Prompt to stderr", err=True)154+ out, err = capfd.readouterr()155+ assert out == ""156+ assert err == "Prompt to stderr [y/N]: "157+158+ # https://github.com/pallets/click/issues/3019159+ emulate_input("y\n")160+ click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)161+ out, err = capfd.readouterr()162+ assert out == ""163+ assert err == "Prompt to stderr with no suffix [y/N]"164+165+ monkeypatch.setattr(click.termui, "isatty", lambda x: True)166+ monkeypatch.setattr(click.termui, "getchar", lambda: " ")167+168+ click.pause("Pause to stdout")169+ out, err = capfd.readouterr()170+ assert out == "Pause to stdout\n"171+ assert err == ""172+173+ click.pause("Pause to stderr", err=True)174+ out, err = capfd.readouterr()175+ assert out == ""176+ assert err == "Pause to stderr\n"modified:tests/test_utils.py-430 removed
1 import os2 import pathlib3 import stat4-import subprocess5-import sys6-from collections import namedtuple7-from contextlib import nullcontext4 from decimal import Decimal5 from fractions import Fraction10-from functools import partial11-from io import BytesIO12-from io import StringIO13-from unittest.mock import patch6 7 import pytest8 9 import click._termui_impl49 unmodified lines59 60 assert value not in real_values61 62 71-def test_echo(runner):72- with runner.isolation() as outstreams:73- click.echo("\N{SNOWMAN}")74- click.echo(b"\x44\x44")75- click.echo(42, nl=False)76- click.echo(b"a", nl=False)77- click.echo("\x1b[31mx\x1b[39m", nl=False)78- bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")79- assert bytes == b"\xe2\x98\x83\nDD\n42ax"80-81- # if wrapped, we expect bytes to survive.82- @click.command()83- def cli():84- click.echo(b"\xf6")85-86- result = runner.invoke(cli, [])87- assert result.stdout_bytes == b"\xf6\n"88-89- # Ensure we do not strip for bytes.90- with runner.isolation() as outstreams:91- click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)92- assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"93-94-95-def test_echo_custom_file():96- f = StringIO()97- click.echo("hello", file=f)98- assert f.getvalue() == "hello\n"99-100- b = BytesIO()101- click.echo(b"", b)102- assert b.getvalue() == b"\n"103-104-105-def test_echo_no_streams(monkeypatch, runner):106- """echo should not fail when stdout and stderr are None with pythonw on Windows."""107- with runner.isolation():108- sys.stdout = None109- sys.stderr = None110- click.echo("test")111- click.echo("test", err=True)112-113-63 @pytest.mark.parametrize(64 ("styles", "ref"),65 [66 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),158 unmodified lines225 result = runner.invoke(echo, input="1\n2\n")226 assert result.exit_code == 1227 228 280-def _test_gen_func():281- yield "a"282- yield "b"283- yield "c"284- yield "abc"285-286-287-def _test_gen_func_fails():288- raise RuntimeError("This is a test.")289- yield # unreachable, keeps this a generator function290-291-292-def _test_gen_func_yields_then_fails():293- yield "test"294- raise RuntimeError("This is a test.")295-296-297-def _test_gen_func_echo(file=None):298- yield "test"299- click.echo("hello", file=file)300- yield "test"301-302-303-def _test_simulate_keyboard_interrupt(file=None):304- yield "output_before_keyboard_interrupt"305- raise KeyboardInterrupt()306-307-308-EchoViaPagerTest = namedtuple(309- "EchoViaPagerTest",310- (311- "description",312- "test_input",313- "expected_pager",314- "expected_stdout",315- "expected_stderr",316- "expected_error",317- ),318-)319-320-321-@pytest.mark.skipif(WIN, reason="Different behavior on windows.")322-@pytest.mark.parametrize(323- "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]324-)325-@pytest.mark.parametrize(326- "test",327- [328- # We need to pass a parameter function instead of a plain param329- # as pytest.mark.parametrize will reuse the parameters causing the330- # generators to be used up so they will not yield anymore331- EchoViaPagerTest(332- description="Plain string argument",333- test_input=lambda: "just text",334- expected_pager="just text\n",335- expected_stdout="",336- expected_stderr="",337- expected_error=None,338- ),339- EchoViaPagerTest(340- description="Iterable argument",341- test_input=lambda: ["itera", "ble"],342- expected_pager="iterable\n",343- expected_stdout="",344- expected_stderr="",345- expected_error=None,346- ),347- EchoViaPagerTest(348- description="Generator function argument",349- test_input=lambda: _test_gen_func,350- expected_pager="abcabc\n",351- expected_stdout="",352- expected_stderr="",353- expected_error=None,354- ),355- EchoViaPagerTest(356- description="String generator argument",357- test_input=lambda: _test_gen_func(),358- expected_pager="abcabc\n",359- expected_stdout="",360- expected_stderr="",361- expected_error=None,362- ),363- EchoViaPagerTest(364- description="Number generator expression argument",365- test_input=lambda: (c for c in range(6)),366- expected_pager="012345\n",367- expected_stdout="",368- expected_stderr="",369- expected_error=None,370- ),371- EchoViaPagerTest(372- description="Exception in generator function argument",373- test_input=lambda: _test_gen_func_fails,374- # Because generator throws early on, the pager did not have375- # a chance yet to write the file.376- expected_pager="",377- expected_stdout="",378- expected_stderr="",379- expected_error=RuntimeError,380- ),381- EchoViaPagerTest(382- description="Exception in generator argument",383- test_input=lambda: _test_gen_func_fails,384- # Because generator throws early on, the pager did not have a385- # chance yet to write the file.386- expected_pager="",387- expected_stdout="",388- expected_stderr="",389- expected_error=RuntimeError,390- ),391- EchoViaPagerTest(392- description="Keyboard interrupt should not terminate the pager",393- test_input=lambda: _test_simulate_keyboard_interrupt(),394- # Due to the keyboard interrupt during pager execution, click program395- # should abort, but the pager should stay open.396- # This allows users to cancel the program and search in the pager397- # output, before they decide to terminate the pager.398- expected_pager="output_before_keyboard_interrupt",399- expected_stdout="",400- expected_stderr="",401- expected_error=KeyboardInterrupt,402- ),403- EchoViaPagerTest(404- description="Writing to stdout during generator execution",405- test_input=lambda: _test_gen_func_echo(),406- expected_pager="testtest\n",407- expected_stdout="hello\n",408- expected_stderr="",409- expected_error=None,410- ),411- EchoViaPagerTest(412- description="Writing to stderr during generator execution",413- test_input=lambda: _test_gen_func_echo(file=sys.stderr),414- expected_pager="testtest\n",415- expected_stdout="",416- expected_stderr="hello\n",417- expected_error=None,418- ),419- ],420-)421-def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):422- monkeypatch.setitem(os.environ, "PAGER", pager_cmd)423- monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)424-425- test_input = test.test_input()426- expected_pager = test.expected_pager427- expected_stdout = test.expected_stdout428- expected_stderr = test.expected_stderr429- expected_error = test.expected_error430-431- check_raise = pytest.raises(expected_error) if expected_error else nullcontext()432-433- pager_out_tmp = tmp_path / "pager_out.txt"434- with pager_out_tmp.open("w") as f:435- force_subprocess_stdout = patch.object(436- subprocess,437- "Popen",438- partial(subprocess.Popen, stdout=f),439- )440- with force_subprocess_stdout:441- with check_raise:442- click.echo_via_pager(test_input)443-444- out, err = capfd.readouterr()445-446- pager = pager_out_tmp.read_text()447-448- assert pager == expected_pager, (449- f"Unexpected pager output in test case '{test.description}'"450- )451- assert out == expected_stdout, (452- f"Unexpected stdout in test case '{test.description}'"453- )454- assert err == expected_stderr, (455- f"Unexpected stderr in test case '{test.description}'"456- )457-458-459-@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460-def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):461- """A generator that yields then raises: click writes the partial output to462- the pager stream before propagating the exception.463-464- The pager file content is intentionally NOT asserted: pipe-drain timing465- between click and the pager subprocess is outside click's control466- (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent467- to the pager, which is deterministic regardless of scheduling.468- """469- monkeypatch.setitem(os.environ, "PAGER", "cat")470- monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)471-472- writes: list[str] = []473- real_write = click._termui_impl.MaybeStripAnsi.write474-475- def spy(self, text):476- writes.append(text)477- return real_write(self, text)478-479- monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480-481- pager_out_tmp = tmp_path / "pager_out.txt"482- with (483- pager_out_tmp.open("w") as f,484- patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),485- pytest.raises(RuntimeError, match="This is a test."),486- ):487- click.echo_via_pager(_test_gen_func_yields_then_fails())488-489- assert "".join(writes) == "test", (490- f"click should have written the yielded chunk before exception, got {writes!r}"491- )492-493-494-@pytest.mark.stress495-@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496-@pytest.mark.parametrize("_", range(1000))497-def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498- """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499-500- Regression coverage for the cleanup path in ``_pipepager``'s exception501- handler (issue #2899, PR #3470). Each iteration spawns a real pager502- subprocess, raises before any data is written and check there is no leak.503- """504- monkeypatch.setitem(os.environ, "PAGER", "cat")505- monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)506-507- spawned: list[subprocess.Popen] = []508- real_popen = subprocess.Popen509-510- def tracking_popen(*args, **kwargs):511- p = real_popen(*args, **kwargs)512- spawned.append(p)513- return p514-515- pager_out_tmp = tmp_path / "pager_out.txt"516- with (517- pager_out_tmp.open("w") as f,518- patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),519- pytest.raises(RuntimeError),520- ):521- click.echo_via_pager(_test_gen_func_fails())522-523- assert spawned, "pager subprocess was never started"524- for p in spawned:525- assert p.returncode is not None, "pager subprocess not reaped"526-527-528-def test_echo_color_flag(monkeypatch, capfd):529- isatty = True530- monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531-532- text = "foo"533- styled_text = click.style(text, fg="red")534- assert styled_text == "\x1b[31mfoo\x1b[0m"535-536- click.echo(styled_text, color=False)537- out, err = capfd.readouterr()538- assert out == f"{text}\n"539-540- click.echo(styled_text, color=True)541- out, err = capfd.readouterr()542- assert out == f"{styled_text}\n"543-544- isatty = True545- click.echo(styled_text)546- out, err = capfd.readouterr()547- assert out == f"{styled_text}\n"548-549- isatty = False550- # Faking isatty() is not enough on Windows;551- # the implementation caches the colorama wrapped stream552- # so we have to use a new stream for each test553- stream = StringIO()554- click.echo(styled_text, file=stream)555- assert stream.getvalue() == f"{text}\n"556-557- stream = StringIO()558- click.echo(styled_text, file=stream, color=True)559- assert stream.getvalue() == f"{styled_text}\n"560-561-562-def test_prompt_cast_default(capfd, monkeypatch):563- monkeypatch.setattr(sys, "stdin", StringIO("\n"))564- value = click.prompt("value", default="100", type=int)565- capfd.readouterr()566- assert isinstance(value, int)567-568-569-@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")570-def test_echo_writing_to_standard_error(capfd, monkeypatch):571- def emulate_input(text):572- """Emulate keyboard input."""573- monkeypatch.setattr(sys, "stdin", StringIO(text))574-575- click.echo("Echo to standard output")576- out, err = capfd.readouterr()577- assert out == "Echo to standard output\n"578- assert err == ""579-580- click.echo("Echo to standard error", err=True)581- out, err = capfd.readouterr()582- assert out == ""583- assert err == "Echo to standard error\n"584-585- emulate_input("asdlkj\n")586- click.prompt("Prompt to stdin")587- out, err = capfd.readouterr()588- assert out == "Prompt to stdin: "589- assert err == ""590-591- emulate_input("asdlkj\n")592- click.prompt("Prompt to stdin with no suffix", prompt_suffix="")593- out, err = capfd.readouterr()594- assert out == "Prompt to stdin with no suffix"595- assert err == ""596-597- # On non-Windows the full prompt goes through redirect_stdout so598- # nothing leaks to stdout when err=True.599- # https://github.com/pallets/click/issues/2968600- emulate_input("asdlkj\n")601- click.prompt("Prompt to stderr", err=True)602- out, err = capfd.readouterr()603- assert out == ""604- assert err == "Prompt to stderr: "605-606- # https://github.com/pallets/click/issues/3019607- emulate_input("asdlkj\n")608- click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)609- out, err = capfd.readouterr()610- assert out == ""611- assert err == "Prompt to stderr with no suffix"612-613- emulate_input("y\n")614- click.confirm("Prompt to stdin")615- out, err = capfd.readouterr()616- assert out == "Prompt to stdin [y/N]: "617- assert err == ""618-619- emulate_input("y\n")620- click.confirm("Prompt to stdin with no suffix", prompt_suffix="")621- out, err = capfd.readouterr()622- assert out == "Prompt to stdin with no suffix [y/N]"623- assert err == ""624-625- # https://github.com/pallets/click/issues/2968626- emulate_input("y\n")627- click.confirm("Prompt to stderr", err=True)628- out, err = capfd.readouterr()629- assert out == ""630- assert err == "Prompt to stderr [y/N]: "631-632- # https://github.com/pallets/click/issues/3019633- emulate_input("y\n")634- click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)635- out, err = capfd.readouterr()636- assert out == ""637- assert err == "Prompt to stderr with no suffix [y/N]"638-639- monkeypatch.setattr(click.termui, "isatty", lambda x: True)640- monkeypatch.setattr(click.termui, "getchar", lambda: " ")641-642- click.pause("Pause to stdout")643- out, err = capfd.readouterr()644- assert out == "Pause to stdout\n"645- assert err == ""646-647- click.pause("Pause to stderr", err=True)648- out, err = capfd.readouterr()649- assert out == ""650- assert err == "Pause to stderr\n"651-652-653-def test_echo_with_capsys(capsys):654- click.echo("Capture me.")655- out, err = capsys.readouterr()656- assert out == "Capture me.\n"657-658-229 def test_open_file(runner):230 @click.command()231 @click.argument("filename")232 def cli(filename):199 unmodified lines