Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

547 lines · 14.3 KiB · Python

Last changed by

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

History of this file

Take it

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

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 1why, one step back
1import faulthandler

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

line 2why, one step back
2import os

Allow debugger interactions in tests (#3235)Rowlando13before adoptionac2dd7a

line 3why, one step back
3import pdb

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 4–9why, one step back
4import sys
5from io import BytesIO67import pytest89import click

Merge stable into main (#2799)Rowlando13before adoptiond791537

line 10why, one step back
10from click.exceptions import ClickException

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 11–188why, one step back
11from click.testing import CliRunner
121314def test_runner():15 @click.command()16 def test():17 i = click.get_binary_stream("stdin")18 o = click.get_binary_stream("stdout")19 while True:20 chunk = i.read(4096)21 if not chunk:22 break23 o.write(chunk)24 o.flush()2526 runner = CliRunner()27 result = runner.invoke(test, input="Hello World!\n")28 assert not result.exception29 assert result.output == "Hello World!\n"303132def test_echo_stdin_stream():33 @click.command()34 def test():35 i = click.get_binary_stream("stdin")36 o = click.get_binary_stream("stdout")37 while True:38 chunk = i.read(4096)39 if not chunk:40 break41 o.write(chunk)42 o.flush()4344 runner = CliRunner(echo_stdin=True)45 result = runner.invoke(test, input="Hello World!\n")46 assert not result.exception47 assert result.output == "Hello World!\nHello World!\n"484950def test_echo_stdin_prompts():51 @click.command()52 def test_python_input():53 foo = input("Foo: ")54 click.echo(f"foo={foo}")5556 runner = CliRunner(echo_stdin=True)57 result = runner.invoke(test_python_input, input="bar bar\n")58 assert not result.exception59 assert result.output == "Foo: bar bar\nfoo=bar bar\n"6061 @click.command()62 @click.option("--foo", prompt=True)63 def test_prompt(foo):64 click.echo(f"foo={foo}")6566 result = runner.invoke(test_prompt, input="bar bar\n")67 assert not result.exception68 assert result.output == "Foo: bar bar\nfoo=bar bar\n"6970 @click.command()71 @click.option("--foo", prompt=True, hide_input=True)72 def test_hidden_prompt(foo):73 click.echo(f"foo={foo}")7475 result = runner.invoke(test_hidden_prompt, input="bar bar\n")76 assert not result.exception77 assert result.output == "Foo: \nfoo=bar bar\n"7879 @click.command()80 @click.option("--foo", prompt=True)81 @click.option("--bar", prompt=True)82 def test_multiple_prompts(foo, bar):83 click.echo(f"foo={foo}, bar={bar}")8485 result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")86 assert not result.exception87 assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"888990def test_runner_with_stream():91 @click.command()92 def test():93 i = click.get_binary_stream("stdin")94 o = click.get_binary_stream("stdout")95 while True:96 chunk = i.read(4096)97 if not chunk:98 break99 o.write(chunk)100 o.flush()101102 runner = CliRunner()103 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))104 assert not result.exception105 assert result.output == "Hello World!\n"106107 runner = CliRunner(echo_stdin=True)108 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))109 assert not result.exception110 assert result.output == "Hello World!\nHello World!\n"111112113def test_prompts():114 @click.command()115 @click.option("--foo", prompt=True)116 def test(foo):117 click.echo(f"foo={foo}")118119 runner = CliRunner()120 result = runner.invoke(test, input="wau wau\n")121 assert not result.exception122 assert result.output == "Foo: wau wau\nfoo=wau wau\n"123124 @click.command()125 @click.option("--foo", prompt=True, hide_input=True)126 def test(foo):127 click.echo(f"foo={foo}")128129 runner = CliRunner()130 result = runner.invoke(test, input="wau wau\n")131 assert not result.exception132 assert result.output == "Foo: \nfoo=wau wau\n"133134135def test_getchar():136 @click.command()137 def continue_it():138 click.echo(click.getchar())139140 runner = CliRunner()141 result = runner.invoke(continue_it, input="y")142 assert not result.exception143 assert result.output == "y\n"144145 runner = CliRunner(echo_stdin=True)146 result = runner.invoke(continue_it, input="y")147 assert not result.exception148 assert result.output == "y\n"149150 @click.command()151 def getchar_echo():152 click.echo(click.getchar(echo=True))153154 runner = CliRunner()155 result = runner.invoke(getchar_echo, input="y")156 assert not result.exception157 assert result.output == "yy\n"158159 runner = CliRunner(echo_stdin=True)160 result = runner.invoke(getchar_echo, input="y")161 assert not result.exception162 assert result.output == "yy\n"163164165def test_catch_exceptions():166 class CustomError(Exception):167 pass168169 @click.command()170 def cli():171 raise CustomError(1)172173 runner = CliRunner()174175 result = runner.invoke(cli)176 assert isinstance(result.exception, CustomError)177 assert type(result.exc_info) is tuple178 assert len(result.exc_info) == 3179180 with pytest.raises(CustomError):181 runner.invoke(cli, catch_exceptions=False)182183 CustomError = SystemExit184185 result = runner.invoke(cli)186 assert result.exit_code == 1187188

Add CliRunner default `catch_exceptions` parameter (#2818)Éloi Rivardbefore adoption88328fc

lines 189–210why, one step back
189def test_catch_exceptions_cli_runner():
190 """Test that invoke `catch_exceptions` takes the value from CliRunner if not set191 explicitly."""192193 class CustomError(Exception):194 pass195196 @click.command()197 def cli():198 raise CustomError(1)199200 runner = CliRunner(catch_exceptions=False)201202 result = runner.invoke(cli, catch_exceptions=True)203 assert isinstance(result.exception, CustomError)204 assert type(result.exc_info) is tuple205 assert len(result.exc_info) == 3206207 with pytest.raises(CustomError):208 runner.invoke(cli)209210

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 211–224why, one step back
211def test_with_color():
212 @click.command()213 def cli():214 click.secho("hello world", fg="blue")215216 runner = CliRunner()217218 result = runner.invoke(cli)219 assert result.output == "hello world\n"220 assert not result.exception221222 result = runner.invoke(cli, color=True)223 assert result.output == f"{click.style('hello world', fg='blue')}\n"224 assert not result.exception

Merge stable into main (#2799)Rowlando13before adoptiond791537

lines 225–244why, one step back
225
226227def test_with_color_errors():228 class CLIError(ClickException):229 def format_message(self) -> str:230 return click.style(self.message, fg="red")231232 @click.command()233 def cli():234 raise CLIError("Red error")235236 runner = CliRunner()237238 result = runner.invoke(cli)239 assert result.output == "Error: Red error\n"240 assert result.exception241242 result = runner.invoke(cli, color=True)243 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"244 assert result.exception

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 245–348why, one step back
245
246247def test_with_color_but_pause_not_blocking():248 @click.command()249 def cli():250 click.pause()251252 runner = CliRunner()253 result = runner.invoke(cli, color=True)254 assert not result.exception255 assert result.output == ""256257258def test_exit_code_and_output_from_sys_exit():259 # See issue #362260 @click.command()261 def cli_string():262 click.echo("hello world")263 sys.exit("error")264265 @click.command()266 @click.pass_context267 def cli_string_ctx_exit(ctx):268 click.echo("hello world")269 ctx.exit("error")270271 @click.command()272 def cli_int():273 click.echo("hello world")274 sys.exit(1)275276 @click.command()277 @click.pass_context278 def cli_int_ctx_exit(ctx):279 click.echo("hello world")280 ctx.exit(1)281282 @click.command()283 def cli_float():284 click.echo("hello world")285 sys.exit(1.0)286287 @click.command()288 @click.pass_context289 def cli_float_ctx_exit(ctx):290 click.echo("hello world")291 ctx.exit(1.0)292293 @click.command()294 def cli_no_error():295 click.echo("hello world")296297 runner = CliRunner()298299 result = runner.invoke(cli_string)300 assert result.exit_code == 1301 assert result.output == "hello world\nerror\n"302303 result = runner.invoke(cli_string_ctx_exit)304 assert result.exit_code == 1305 assert result.output == "hello world\nerror\n"306307 result = runner.invoke(cli_int)308 assert result.exit_code == 1309 assert result.output == "hello world\n"310311 result = runner.invoke(cli_int_ctx_exit)312 assert result.exit_code == 1313 assert result.output == "hello world\n"314315 result = runner.invoke(cli_float)316 assert result.exit_code == 1317 assert result.output == "hello world\n1.0\n"318319 result = runner.invoke(cli_float_ctx_exit)320 assert result.exit_code == 1321 assert result.output == "hello world\n1.0\n"322323 result = runner.invoke(cli_no_error)324 assert result.exit_code == 0325 assert result.output == "hello world\n"326327328def test_env():329 @click.command()330 def cli_env():331 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")332333 runner = CliRunner()334335 env_orig = dict(os.environ)336 env = dict(env_orig)337 assert "TEST_CLICK_ENV" not in env338 env["TEST_CLICK_ENV"] = "some_value"339 result = runner.invoke(cli_env, env=env)340 assert result.exit_code == 0341 assert result.output == "ENV=some_value\n"342343 assert os.environ == env_orig344345346def test_stderr():347 @click.command()348 def cli_stderr():

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

lines 349–352why, one step back
349 click.echo("1 - stdout")
350 click.echo("2 - stderr", err=True)351 click.echo("3 - stdout")352 click.echo("4 - stderr", err=True)

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

line 353why, one step back
353

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

line 354why, one step back
354 runner_mix = CliRunner()

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 355–356why, one step back
355 result_mix = runner_mix.invoke(cli_stderr)
356

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

lines 357–359why, one step back
357 assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"
358 assert result_mix.stdout == "1 - stdout\n3 - stdout\n"359 assert result_mix.stderr == "2 - stderr\n4 - stderr\n"

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 360–364why, one step back
360
361 @click.command()362 def cli_empty_stderr():363 click.echo("stdout")364

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

line 365why, one step back
365 runner = CliRunner()

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

lines 366–448why, one step back
366 result = runner.invoke(cli_empty_stderr)
367368 assert result.output == "stdout\n"369 assert result.stdout == "stdout\n"370 assert result.stderr == ""371372373@pytest.mark.parametrize(374 "args, expected_output",375 [376 (None, "bar\n"),377 ([], "bar\n"),378 ("", "bar\n"),379 (["--foo", "one two"], "one two\n"),380 ('--foo "one two"', "one two\n"),381 ],382)383def test_args(args, expected_output):384 @click.command()385 @click.option("--foo", default="bar")386 def cli_args(foo):387 click.echo(foo)388389 runner = CliRunner()390 result = runner.invoke(cli_args, args=args)391 assert result.exit_code == 0392 assert result.output == expected_output393394395def test_setting_prog_name_in_extra():396 @click.command()397 def cli():398 click.echo("ok")399400 runner = CliRunner()401 result = runner.invoke(cli, prog_name="foobar")402 assert not result.exception403 assert result.output == "ok\n"404405406def test_command_standalone_mode_returns_value():407 @click.command()408 def cli():409 click.echo("ok")410 return "Hello, World!"411412 runner = CliRunner()413 result = runner.invoke(cli, standalone_mode=False)414 assert result.output == "ok\n"415 assert result.return_value == "Hello, World!"416 assert result.exit_code == 0417418419def test_file_stdin_attrs(runner):420 @click.command()421 @click.argument("f", type=click.File())422 def cli(f):423 click.echo(f.name)424 click.echo(f.mode, nl=False)425426 result = runner.invoke(cli, ["-"])427 assert result.output == "<stdin>\nr"428429430def test_isolated_runner(runner):431 with runner.isolated_filesystem() as d:432 assert os.path.exists(d)433434 assert not os.path.exists(d)435436437def test_isolated_runner_custom_tempdir(runner, tmp_path):438 with runner.isolated_filesystem(temp_dir=tmp_path) as d:439 assert os.path.exists(d)440441 assert os.path.exists(d)442 os.rmdir(d)443444445def test_isolation_stderr_errors():446 """Writing to stderr should escape invalid characters instead of447 raising a UnicodeEncodeError.448 """

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

line 449why, one step back
449 runner = CliRunner()

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

line 450why, one step back
450

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

line 451why, one step back
451 with runner.isolation() as (_, err, _):

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

line 452why, one step back
452 click.echo("\udce2", err=True, nl=False)

fix a race in `click.testing.StreamMixer`'s finalization, seen in a multi-threaded context (#2991)Rowlando13before adoption737bfbd

line 453why, one step back
453 assert err.getvalue() == b"\\udce2"

Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#2579)David Lordbefore adoptioned0d3e7

line 454why, one step back
454

Flush sys.stderr when CliRunner finalizes (#2933)David Lordbefore adoptioncfa6f4a

lines 455–463why, one step back
455
456def test_isolation_flushes_unflushed_stderr():457 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up458 flushed by the runner at end of invocation.459 """460 runner = CliRunner()461462 with runner.isolation() as (_, err, _):463 click.echo("\udce2", err=True, nl=False)

fix a race in `click.testing.StreamMixer`'s finalization, seen in a multi-threaded context (#2991)Rowlando13before adoption737bfbd

line 464why, one step back
464 assert err.getvalue() == b"\\udce2"

Flush sys.stderr when CliRunner finalizes (#2933)David Lordbefore adoptioncfa6f4a

lines 465–473why, one step back
465
466 @click.command()467 def cli():468 # set end="", flush=False so that it's totally clear that we won't get any469 # auto-flush behaviors470 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)471472 result = runner.invoke(cli)473 assert result.stderr == "gyarados gyarados gyarados"

Allow debugger interactions in tests (#3235)Rowlando13before adoptionac2dd7a

lines 474–522why, one step back
474
475476def test_pdb_uses_real_streams():477 """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams478 so that interactive debuggers work instead of reading from the479 captured ``BytesIO`` stdin.480 """481482 @click.command()483 def cli():484 debugger = pdb.Pdb()485 assert debugger.stdin is sys.__stdin__486 assert debugger.stdout is sys.__stdout__487 click.echo("after debugger")488489 runner = CliRunner()490 result = runner.invoke(cli, catch_exceptions=False)491 assert result.output == "after debugger\n"492493494def test_pdb_explicit_streams_honored():495 """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not496 overridden by the ``CliRunner`` patch.497 """498499 @click.command()500 def cli():501 custom_in = sys.stdin502 custom_out = sys.stdout503 debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)504 assert debugger.stdin is custom_in505 assert debugger.stdout is custom_out506507 runner = CliRunner()508 runner.invoke(cli, catch_exceptions=False)509510511def test_pdb_init_restored_after_invoke():512 """``pdb.Pdb.__init__`` is restored to its original after invoke."""513 original = pdb.Pdb.__init__514515 @click.command()516 def cli():517 pass518519 runner = CliRunner()520 runner.invoke(cli)521522 assert pdb.Pdb.__init__ is original

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

lines 523–547why, one step back
523
524525def test_faulthandler_enable(runner):526 """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527 ``io.UnsupportedOperation: fileno``.528529 ``faulthandler.enable()`` needs a real OS file descriptor to register530 its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531 ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.532533 Reproduce:https://github.com/pallets/click/issues/2865534 """535536 @click.command()537 @click.option("--flag", type=bool, default=True)538 def cli(flag):539 click.echo("Executing main function...")540 if flag:541 click.echo("Registering faulthandler")542 faulthandler.enable()543 click.echo("Finished executing main function.")544545 result = runner.invoke(cli, ["--flag", True])546 assert result.exit_code == 0, result.output547 assert "Finished executing main function." in result.output