Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

840 lines · 23.7 KiB · Python

Last changed by

Merge main into stable (#3800)Rowlando13before adoption420c8fb

History of this file

Take it

1import faulthandler2import io3import os4import pdb5import sys6from io import BytesIO78import pytest910import click11from click.exceptions import ClickException12from click.testing import CliRunner13from click.utils import _get_binary_stream141516def test_runner():17    @click.command()18    def test():19        i = _get_binary_stream("stdin")20        o = _get_binary_stream("stdout")21        while True:22            chunk = i.read(4096)23            if not chunk:24                break25            o.write(chunk)26            o.flush()2728    runner = CliRunner()29    result = runner.invoke(test, input="Hello World!\n")30    assert not result.exception31    assert result.output == "Hello World!\n"323334def test_echo_stdin_stream():35    @click.command()36    def test():37        i = _get_binary_stream("stdin")38        o = _get_binary_stream("stdout")39        while True:40            chunk = i.read(4096)41            if not chunk:42                break43            o.write(chunk)44            o.flush()4546    runner = CliRunner(echo_stdin=True)47    result = runner.invoke(test, input="Hello World!\n")48    assert not result.exception49    assert result.output == "Hello World!\nHello World!\n"505152def test_echo_stdin_prompts():53    @click.command()54    def test_python_input():55        foo = input("Foo: ")56        click.echo(f"foo={foo}")5758    runner = CliRunner(echo_stdin=True)59    result = runner.invoke(test_python_input, input="bar bar\n")60    assert not result.exception61    assert result.output == "Foo: bar bar\nfoo=bar bar\n"6263    @click.command()64    @click.option("--foo", prompt=True)65    def test_prompt(foo):66        click.echo(f"foo={foo}")6768    result = runner.invoke(test_prompt, input="bar bar\n")69    assert not result.exception70    assert result.output == "Foo: bar bar\nfoo=bar bar\n"7172    @click.command()73    @click.option("--foo", prompt=True, hide_input=True)74    def test_hidden_prompt(foo):75        click.echo(f"foo={foo}")7677    result = runner.invoke(test_hidden_prompt, input="bar bar\n")78    assert not result.exception79    assert result.output == "Foo: \nfoo=bar bar\n"8081    @click.command()82    @click.option("--foo", prompt=True)83    @click.option("--bar", prompt=True)84    def test_multiple_prompts(foo, bar):85        click.echo(f"foo={foo}, bar={bar}")8687    result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")88    assert not result.exception89    assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"909192def test_runner_with_stream():93    @click.command()94    def test():95        i = _get_binary_stream("stdin")96        o = _get_binary_stream("stdout")97        while True:98            chunk = i.read(4096)99            if not chunk:100                break101            o.write(chunk)102            o.flush()103104    runner = CliRunner()105    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))106    assert not result.exception107    assert result.output == "Hello World!\n"108109    runner = CliRunner(echo_stdin=True)110    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))111    assert not result.exception112    assert result.output == "Hello World!\nHello World!\n"113114115def test_prompts():116    @click.command()117    @click.option("--foo", prompt=True)118    def test(foo):119        click.echo(f"foo={foo}")120121    runner = CliRunner()122    result = runner.invoke(test, input="wau wau\n")123    assert not result.exception124    assert result.output == "Foo: wau wau\nfoo=wau wau\n"125126    @click.command()127    @click.option("--foo", prompt=True, hide_input=True)128    def test(foo):129        click.echo(f"foo={foo}")130131    runner = CliRunner()132    result = runner.invoke(test, input="wau wau\n")133    assert not result.exception134    assert result.output == "Foo: \nfoo=wau wau\n"135136137def test_getchar():138    @click.command()139    def continue_it():140        click.echo(click.getchar())141142    runner = CliRunner()143    result = runner.invoke(continue_it, input="y")144    assert not result.exception145    assert result.output == "y\n"146147    runner = CliRunner(echo_stdin=True)148    result = runner.invoke(continue_it, input="y")149    assert not result.exception150    assert result.output == "y\n"151152    @click.command()153    def getchar_echo():154        click.echo(click.getchar(echo=True))155156    runner = CliRunner()157    result = runner.invoke(getchar_echo, input="y")158    assert not result.exception159    assert result.output == "yy\n"160161    runner = CliRunner(echo_stdin=True)162    result = runner.invoke(getchar_echo, input="y")163    assert not result.exception164    assert result.output == "yy\n"165166167def test_catch_exceptions():168    class CustomError(Exception):169        pass170171    @click.command()172    def cli():173        raise CustomError(1)174175    runner = CliRunner()176177    result = runner.invoke(cli)178    assert isinstance(result.exception, CustomError)179    assert type(result.exc_info) is tuple180    assert len(result.exc_info) == 3181182    with pytest.raises(CustomError):183        runner.invoke(cli, catch_exceptions=False)184185    CustomError = SystemExit186187    result = runner.invoke(cli)188    assert result.exit_code == 1189190191def test_catch_exceptions_cli_runner():192    """Test that invoke `catch_exceptions` takes the value from CliRunner if not set193    explicitly."""194195    class CustomError(Exception):196        pass197198    @click.command()199    def cli():200        raise CustomError(1)201202    runner = CliRunner(catch_exceptions=False)203204    result = runner.invoke(cli, catch_exceptions=True)205    assert isinstance(result.exception, CustomError)206    assert type(result.exc_info) is tuple207    assert len(result.exc_info) == 3208209    with pytest.raises(CustomError):210        runner.invoke(cli)211212213def test_with_color():214    @click.command()215    def cli():216        click.secho("hello world", fg="blue")217218    runner = CliRunner()219220    result = runner.invoke(cli)221    assert result.output == "hello world\n"222    assert not result.exception223224    result = runner.invoke(cli, color=True)225    assert result.output == f"{click.style('hello world', fg='blue')}\n"226    assert not result.exception227228229def test_with_color_errors():230    class CLIError(ClickException):231        def format_message(self) -> str:232            return click.style(self.message, fg="red")233234    @click.command()235    def cli():236        raise CLIError("Red error")237238    runner = CliRunner()239240    result = runner.invoke(cli)241    assert result.output == "Error: Red error\n"242    assert result.exception243244    result = runner.invoke(cli, color=True)245    assert result.output == f"Error: {click.style('Red error', fg='red')}\n"246    assert result.exception247248249def test_with_color_but_pause_not_blocking():250    @click.command()251    def cli():252        click.pause()253254    runner = CliRunner()255    result = runner.invoke(cli, color=True)256    assert not result.exception257    assert result.output == ""258259260def test_with_echo_via_pager():261    @click.command()262    def cli():263        click.echo_via_pager("Hello, Click!")264265    runner = CliRunner()266    result = runner.invoke(cli)267    assert not result.exception268    assert result.output == "Hello, Click!\n"269270271def test_exit_code_and_output_from_sys_exit():272    # See issue #362273    @click.command()274    def cli_string():275        click.echo("hello world")276        sys.exit("error")277278    @click.command()279    @click.pass_context280    def cli_string_ctx_exit(ctx):281        click.echo("hello world")282        ctx.exit("error")283284    @click.command()285    def cli_int():286        click.echo("hello world")287        sys.exit(1)288289    @click.command()290    @click.pass_context291    def cli_int_ctx_exit(ctx):292        click.echo("hello world")293        ctx.exit(1)294295    @click.command()296    def cli_float():297        click.echo("hello world")298        sys.exit(1.0)299300    @click.command()301    @click.pass_context302    def cli_float_ctx_exit(ctx):303        click.echo("hello world")304        ctx.exit(1.0)305306    @click.command()307    def cli_no_error():308        click.echo("hello world")309310    runner = CliRunner()311312    result = runner.invoke(cli_string)313    assert result.exit_code == 1314    assert result.output == "hello world\nerror\n"315316    result = runner.invoke(cli_string_ctx_exit)317    assert result.exit_code == 1318    assert result.output == "hello world\nerror\n"319320    result = runner.invoke(cli_int)321    assert result.exit_code == 1322    assert result.output == "hello world\n"323324    result = runner.invoke(cli_int_ctx_exit)325    assert result.exit_code == 1326    assert result.output == "hello world\n"327328    result = runner.invoke(cli_float)329    assert result.exit_code == 1330    assert result.output == "hello world\n1.0\n"331332    result = runner.invoke(cli_float_ctx_exit)333    assert result.exit_code == 1334    assert result.output == "hello world\n1.0\n"335336    result = runner.invoke(cli_no_error)337    assert result.exit_code == 0338    assert result.output == "hello world\n"339340341def test_env():342    @click.command()343    def cli_env():344        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")345346    runner = CliRunner()347348    env_orig = dict(os.environ)349    env = dict(env_orig)350    assert "TEST_CLICK_ENV" not in env351    env["TEST_CLICK_ENV"] = "some_value"352    result = runner.invoke(cli_env, env=env)353    assert result.exit_code == 0354    assert result.output == "ENV=some_value\n"355356    assert os.environ == env_orig357358359def test_stderr():360    @click.command()361    def cli_stderr():362        click.echo("1 - stdout")363        click.echo("2 - stderr", err=True)364        click.echo("3 - stdout")365        click.echo("4 - stderr", err=True)366367    runner_mix = CliRunner()368    result_mix = runner_mix.invoke(cli_stderr)369370    assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"371    assert result_mix.stdout == "1 - stdout\n3 - stdout\n"372    assert result_mix.stderr == "2 - stderr\n4 - stderr\n"373374    @click.command()375    def cli_empty_stderr():376        click.echo("stdout")377378    runner = CliRunner()379    result = runner.invoke(cli_empty_stderr)380381    assert result.output == "stdout\n"382    assert result.stdout == "stdout\n"383    assert result.stderr == ""384385386@pytest.mark.parametrize(387    "args, expected_output",388    [389        (None, "bar\n"),390        ([], "bar\n"),391        ("", "bar\n"),392        (["--foo", "one two"], "one two\n"),393        ('--foo "one two"', "one two\n"),394    ],395)396def test_args(args, expected_output):397    @click.command()398    @click.option("--foo", default="bar")399    def cli_args(foo):400        click.echo(foo)401402    runner = CliRunner()403    result = runner.invoke(cli_args, args=args)404    assert result.exit_code == 0405    assert result.output == expected_output406407408def test_setting_prog_name_in_extra():409    @click.command()410    def cli():411        click.echo("ok")412413    runner = CliRunner()414    result = runner.invoke(cli, prog_name="foobar")415    assert not result.exception416    assert result.output == "ok\n"417418419def test_command_standalone_mode_returns_value():420    @click.command()421    def cli():422        click.echo("ok")423        return "Hello, World!"424425    runner = CliRunner()426    result = runner.invoke(cli, standalone_mode=False)427    assert result.output == "ok\n"428    assert result.return_value == "Hello, World!"429    assert result.exit_code == 0430431432def test_file_stdin_attrs(runner):433    @click.command()434    @click.argument("f", type=click.File())435    def cli(f):436        click.echo(f.name)437        click.echo(f.mode, nl=False)438439    result = runner.invoke(cli, ["-"])440    assert result.output == "<stdin>\nr"441442443@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")444def test_isolated_runner(runner):445    with runner.isolated_filesystem() as d:446        assert os.path.exists(d)447448    assert not os.path.exists(d)449450451@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")452def test_isolated_runner_custom_tempdir(runner, tmp_path):453    with runner.isolated_filesystem(temp_dir=tmp_path) as d:454        assert os.path.exists(d)455456    assert os.path.exists(d)457    os.rmdir(d)458459460def test_tempdir_replacement_pattern(runner, tmp_path):461    """The replacement for ``isolated_filesystem()``: a temp dir and absolute paths.462463    Rather than changing the working directory, create a directory (here with464    pytest's ``tmp_path``; ``tempfile.TemporaryDirectory`` works the same) and465    pass absolute paths to the command.466    """467468    @click.command()469    @click.argument("path", type=click.Path())470    def write_marker(path):471        with open(path, "w") as f:472            f.write("written")473474    target = tmp_path / "marker.txt"475    result = runner.invoke(write_marker, [str(target)])476477    assert result.exit_code == 0478    assert target.read_text() == "written"479480481def test_tempdir_isolation_is_thread_safe():482    """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``.483484    Each thread owns a ``tempfile.TemporaryDirectory`` and works through485    absolute paths, so there is no ``os.chdir`` and no process-global CWD race486    (the reason ``isolated_filesystem()`` is not thread-safe, issue #3501).487488    ``invoke()`` is deliberately not called concurrently here: it redirects the489    process-global standard streams, so parallel invocations in one process490    corrupt each other regardless of the filesystem. To run commands in491    parallel, use separate processes (like pytest-xdist), not threads.492    """493    import tempfile494    import threading495496    workers = 8497    cwd_before = os.path.realpath(os.getcwd())498    results: list[tuple[str, str, str]] = []499    barrier = threading.Barrier(workers)500    lock = threading.Lock()501502    def worker(index):503        with tempfile.TemporaryDirectory() as d:504            target = os.path.join(d, "data.txt")505            # Release every thread at once to maximize contention.506            barrier.wait(timeout=10)507            with open(target, "w") as f:508                f.write(f"payload-{index}")509            with open(target) as f:510                content = f.read()511            with lock:512                results.append(513                    (514                        os.path.realpath(d),515                        os.path.realpath(os.getcwd()),516                        content,517                    )518                )519520    threads = [threading.Thread(target=worker, args=(i,)) for i in range(workers)]521    for t in threads:522        t.start()523    for t in threads:524        t.join(timeout=10)525526    assert len(results) == workers527    # Every thread had its own distinct directory.528    assert len({d for d, _, _ in results}) == workers529    # No thread mutated the process-global working directory.530    assert {cwd for _, cwd, _ in results} == {cwd_before}531    # Each thread read back exactly the payload it wrote, with no cross-talk.532    assert sorted(content for _, _, content in results) == sorted(533        f"payload-{i}" for i in range(workers)534    )535536537def test_isolation_stderr_errors():538    """Writing to stderr should escape invalid characters instead of539    raising a UnicodeEncodeError.540    """541    runner = CliRunner()542543    with runner.isolation() as (_, err, _):544        click.echo("\udce2", err=True, nl=False)545        assert err.getvalue() == b"\\udce2"546547548def test_isolation_flushes_unflushed_stderr():549    """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up550    flushed by the runner at end of invocation.551    """552    runner = CliRunner()553554    with runner.isolation() as (_, err, _):555        click.echo("\udce2", err=True, nl=False)556        assert err.getvalue() == b"\\udce2"557558    @click.command()559    def cli():560        # set end="", flush=False so that it's totally clear that we won't get any561        # auto-flush behaviors562        print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)563564    result = runner.invoke(cli)565    assert result.stderr == "gyarados gyarados gyarados"566567568def test_pdb_uses_real_streams():569    """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams570    so that interactive debuggers work instead of reading from the571    captured ``BytesIO`` stdin.572    """573574    @click.command()575    def cli():576        debugger = pdb.Pdb()577        assert debugger.stdin is sys.__stdin__578        assert debugger.stdout is sys.__stdout__579        click.echo("after debugger")580581    runner = CliRunner()582    result = runner.invoke(cli, catch_exceptions=False)583    assert result.output == "after debugger\n"584585586def test_pdb_explicit_streams_honored():587    """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not588    overridden by the ``CliRunner`` patch.589    """590591    @click.command()592    def cli():593        custom_in = sys.stdin594        custom_out = sys.stdout595        debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)596        assert debugger.stdin is custom_in597        assert debugger.stdout is custom_out598599    runner = CliRunner()600    runner.invoke(cli, catch_exceptions=False)601602603def test_pdb_init_restored_after_invoke():604    """``pdb.Pdb.__init__`` is restored to its original after invoke."""605    original = pdb.Pdb.__init__606607    @click.command()608    def cli():609        pass610611    runner = CliRunner()612    runner.invoke(cli)613614    assert pdb.Pdb.__init__ is original615616617needs_fd_capture = pytest.mark.skipif(618    sys.platform == "win32",619    reason="fd capture not supported on Windows",620)621622623def test_capture_invalid_mode():624    """Invalid capture mode raises ValueError."""625    with pytest.raises(ValueError, match="capture"):626        CliRunner(capture="invalid")  # type: ignore[arg-type]627628629@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")630def test_capture_fd_windows_error():631    """fd capture raises ValueError on Windows."""632    with pytest.raises(ValueError, match="not supported on Windows"):633        CliRunner(capture="fd")634635636@needs_fd_capture637def test_capture_fd_os_write():638    """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""639640    @click.command()641    def cli():642        click.echo("python stdout")643        os.write(1, b"fd stdout\n")644        os.write(2, b"fd stderr\n")645646    runner = CliRunner(capture="fd")647    result = runner.invoke(cli)648    assert "python stdout" in result.stdout649    assert "fd stdout" in result.stdout650    assert "fd stderr" in result.stderr651652653@needs_fd_capture654def test_capture_fd_stale_reference():655    """capture='fd' captures writes from stale stdout references (issue #2874).656657    Simulates ``from sys import stdout`` at import time, which grabs658    the real stdout connected to fd 1.  The stale object's underlying659    FileIO uses fd 1, so redirecting fd 1 captures its writes.660    """661    # open(1, ..., closefd=False) creates a writer whose underlying662    # FileIO uses fd 1 directly. This mirrors the real scenario:663    # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->664    # FileIO(fd=1).665    stale_stdout = open(1, "w", closefd=False)  # noqa: SIM115666667    @click.command()668    def cli():669        stale_stdout.write("stale write\n")670        stale_stdout.flush()671        click.echo("normal write")672673    runner = CliRunner(capture="fd")674    result = runner.invoke(cli)675    assert "normal write" in result.stdout676    assert "stale write" in result.stdout677678679@needs_fd_capture680def test_capture_fd_logging_handler(tmp_path):681    """capture='fd' captures logging output from a handler holding a stale682    stderr reference (issue #2827).683684    stdlib logging.StreamHandler grabs sys.stderr at configuration time.685    Under normal CliRunner (sys-level capture), the handler still writes686    to the original stream object and output is lost. fd-level capture687    redirects the underlying file descriptor, so the writes are captured.688    """689    import logging690691    # Create a writer backed by the real fd 2, simulating a handler692    # configured at import time before pytest or CliRunner replaced693    # sys.stderr. open(2, closefd=False) mirrors the real scenario:694    # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->695    # FileIO(fd=2).696    stale_stderr = open(2, "w", closefd=False)  # noqa: SIM115697    handler = logging.StreamHandler(stale_stderr)698    handler.setFormatter(logging.Formatter("%(message)s"))699700    logger = logging.getLogger(f"click_test_{tmp_path.name}")701    logger.addHandler(handler)702    logger.setLevel(logging.INFO)703    logger.propagate = False704705    @click.command()706    def cli():707        logger.info("log from stale handler")708        click.echo("normal echo")709710    # sys-level capture misses the log line (it bypasses sys.stderr).711    runner_sys = CliRunner(capture="sys")712    result_sys = runner_sys.invoke(cli)713    assert "normal echo" in result_sys.output714    assert "log from stale handler" not in result_sys.output715716    # fd-level capture catches it by redirecting fd 2.717    runner_fd = CliRunner(capture="fd")718    result_fd = runner_fd.invoke(cli)719    assert "normal echo" in result_fd.output720    assert "log from stale handler" in result_fd.output721722    logger.removeHandler(handler)723724725@needs_fd_capture726def test_capture_fd_faulthandler():727    """faulthandler.enable() works with capture='fd' (issue #2865)."""728729    @click.command()730    def cli():731        faulthandler.enable()732        click.echo("after faulthandler")733734    runner = CliRunner(capture="fd")735    result = runner.invoke(cli)736    assert result.exit_code == 0737    assert "after faulthandler" in result.output738739740def test_capture_sys_fileno_raises():741    """capture='sys' leaves fileno() raising UnsupportedOperation, so user742    code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host743    runner's stdout (issue #3384).744    """745746    @click.command()747    def cli():748        with pytest.raises(io.UnsupportedOperation):749            sys.stdout.fileno()750        with pytest.raises(io.UnsupportedOperation):751            sys.stderr.fileno()752        click.echo("ok")753754    runner = CliRunner(capture="sys")755    result = runner.invoke(cli)756    assert result.exit_code == 0, result.output757    assert "ok" in result.stdout758759760@needs_fd_capture761def test_capture_fd_stderr_separation():762    """capture='fd' properly separates fd-level stdout and stderr."""763764    @click.command()765    def cli():766        click.echo("py-out")767        click.echo("py-err", err=True)768        os.write(1, b"fd-out\n")769        os.write(2, b"fd-err\n")770771    runner = CliRunner(capture="fd")772    result = runner.invoke(cli)773    assert "py-out" in result.stdout774    assert "fd-out" in result.stdout775    assert "py-err" in result.stderr776    assert "fd-err" in result.stderr777    # Mixed output has all of them778    assert "py-out" in result.output779    assert "py-err" in result.output780    assert "fd-out" in result.output781    assert "fd-err" in result.output782783784@needs_fd_capture785def test_capture_fd_nesting():786    """Nested CliRunner.invoke() with fd capture works correctly."""787788    @click.command("inner")789    def inner_cli():790        click.echo("inner")791792    @click.command("outer")793    def outer_cli():794        click.echo("outer")795        os.write(1, b"outer fd\n")796        inner_runner = CliRunner(capture="fd")797        inner_result = inner_runner.invoke(inner_cli)798        click.echo(f"inner captured: {inner_result.stdout.strip()}")799800    runner = CliRunner(capture="fd")801    result = runner.invoke(outer_cli)802    assert "outer" in result.stdout803    assert "outer fd" in result.stdout804    assert "inner captured: inner" in result.stdout805806807@needs_fd_capture808@pytest.mark.parametrize("runner_capture", ["sys", "fd"])809@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])810def test_capture_pytest_matrix(811    request: pytest.FixtureRequest,812    runner_capture: str,813    pytest_fixture: str,814) -> None:815    """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""816    pytest_cap = request.getfixturevalue(pytest_fixture)817818    @click.command()819    def cli() -> None:820        click.echo("inside-stdout")821        click.echo("inside-stderr", err=True)822823    runner = CliRunner(capture=runner_capture)824    result = runner.invoke(cli)825826    # CliRunner sees Click's output.827    assert result.exit_code == 0828    assert "inside-stdout" in result.stdout829    assert "inside-stderr" in result.stderr830831    # Pytest capture machinery is still working after invoke().832    print("post-invoke-stdout")833    print("post-invoke-stderr", file=sys.stderr)834    captured = pytest_cap.readouterr()835    assert "post-invoke-stdout" in captured.out836    assert "post-invoke-stderr" in captured.err837838    # Click output is not leaking into Pytest.839    assert "inside-stdout" not in captured.out840    assert "inside-stderr" not in captured.err