test_testing.py
This file
Path
tests/test_testing.py
430 lines · 10.8 KiB · Python
Last changed by
Merge stable into main (#2799)Rowlando13before adoptiond791537
History of this fileTake it
1import os2import sys3from io import BytesIO45import pytest67import click8from click.exceptions import ClickException9from click.testing import CliRunner101112def test_runner():13 @click.command()14 def test():15 i = click.get_binary_stream("stdin")16 o = click.get_binary_stream("stdout")17 while True:18 chunk = i.read(4096)19 if not chunk:20 break21 o.write(chunk)22 o.flush()2324 runner = CliRunner()25 result = runner.invoke(test, input="Hello World!\n")26 assert not result.exception27 assert result.output == "Hello World!\n"282930def test_echo_stdin_stream():31 @click.command()32 def test():33 i = click.get_binary_stream("stdin")34 o = click.get_binary_stream("stdout")35 while True:36 chunk = i.read(4096)37 if not chunk:38 break39 o.write(chunk)40 o.flush()4142 runner = CliRunner(echo_stdin=True)43 result = runner.invoke(test, input="Hello World!\n")44 assert not result.exception45 assert result.output == "Hello World!\nHello World!\n"464748def test_echo_stdin_prompts():49 @click.command()50 def test_python_input():51 foo = input("Foo: ")52 click.echo(f"foo={foo}")5354 runner = CliRunner(echo_stdin=True)55 result = runner.invoke(test_python_input, input="bar bar\n")56 assert not result.exception57 assert result.output == "Foo: bar bar\nfoo=bar bar\n"5859 @click.command()60 @click.option("--foo", prompt=True)61 def test_prompt(foo):62 click.echo(f"foo={foo}")6364 result = runner.invoke(test_prompt, input="bar bar\n")65 assert not result.exception66 assert result.output == "Foo: bar bar\nfoo=bar bar\n"6768 @click.command()69 @click.option("--foo", prompt=True, hide_input=True)70 def test_hidden_prompt(foo):71 click.echo(f"foo={foo}")7273 result = runner.invoke(test_hidden_prompt, input="bar bar\n")74 assert not result.exception75 assert result.output == "Foo: \nfoo=bar bar\n"7677 @click.command()78 @click.option("--foo", prompt=True)79 @click.option("--bar", prompt=True)80 def test_multiple_prompts(foo, bar):81 click.echo(f"foo={foo}, bar={bar}")8283 result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")84 assert not result.exception85 assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"868788def test_runner_with_stream():89 @click.command()90 def test():91 i = click.get_binary_stream("stdin")92 o = click.get_binary_stream("stdout")93 while True:94 chunk = i.read(4096)95 if not chunk:96 break97 o.write(chunk)98 o.flush()99100 runner = CliRunner()101 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))102 assert not result.exception103 assert result.output == "Hello World!\n"104105 runner = CliRunner(echo_stdin=True)106 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))107 assert not result.exception108 assert result.output == "Hello World!\nHello World!\n"109110111def test_prompts():112 @click.command()113 @click.option("--foo", prompt=True)114 def test(foo):115 click.echo(f"foo={foo}")116117 runner = CliRunner()118 result = runner.invoke(test, input="wau wau\n")119 assert not result.exception120 assert result.output == "Foo: wau wau\nfoo=wau wau\n"121122 @click.command()123 @click.option("--foo", prompt=True, hide_input=True)124 def test(foo):125 click.echo(f"foo={foo}")126127 runner = CliRunner()128 result = runner.invoke(test, input="wau wau\n")129 assert not result.exception130 assert result.output == "Foo: \nfoo=wau wau\n"131132133def test_getchar():134 @click.command()135 def continue_it():136 click.echo(click.getchar())137138 runner = CliRunner()139 result = runner.invoke(continue_it, input="y")140 assert not result.exception141 assert result.output == "y\n"142143 runner = CliRunner(echo_stdin=True)144 result = runner.invoke(continue_it, input="y")145 assert not result.exception146 assert result.output == "y\n"147148 @click.command()149 def getchar_echo():150 click.echo(click.getchar(echo=True))151152 runner = CliRunner()153 result = runner.invoke(getchar_echo, input="y")154 assert not result.exception155 assert result.output == "yy\n"156157 runner = CliRunner(echo_stdin=True)158 result = runner.invoke(getchar_echo, input="y")159 assert not result.exception160 assert result.output == "yy\n"161162163def test_catch_exceptions():164 class CustomError(Exception):165 pass166167 @click.command()168 def cli():169 raise CustomError(1)170171 runner = CliRunner()172173 result = runner.invoke(cli)174 assert isinstance(result.exception, CustomError)175 assert type(result.exc_info) is tuple176 assert len(result.exc_info) == 3177178 with pytest.raises(CustomError):179 runner.invoke(cli, catch_exceptions=False)180181 CustomError = SystemExit182183 result = runner.invoke(cli)184 assert result.exit_code == 1185186187def test_with_color():188 @click.command()189 def cli():190 click.secho("hello world", fg="blue")191192 runner = CliRunner()193194 result = runner.invoke(cli)195 assert result.output == "hello world\n"196 assert not result.exception197198 result = runner.invoke(cli, color=True)199 assert result.output == f"{click.style('hello world', fg='blue')}\n"200 assert not result.exception201202203def test_with_color_errors():204 class CLIError(ClickException):205 def format_message(self) -> str:206 return click.style(self.message, fg="red")207208 @click.command()209 def cli():210 raise CLIError("Red error")211212 runner = CliRunner()213214 result = runner.invoke(cli)215 assert result.output == "Error: Red error\n"216 assert result.exception217218 result = runner.invoke(cli, color=True)219 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"220 assert result.exception221222223def test_with_color_but_pause_not_blocking():224 @click.command()225 def cli():226 click.pause()227228 runner = CliRunner()229 result = runner.invoke(cli, color=True)230 assert not result.exception231 assert result.output == ""232233234def test_exit_code_and_output_from_sys_exit():235 # See issue #362236 @click.command()237 def cli_string():238 click.echo("hello world")239 sys.exit("error")240241 @click.command()242 @click.pass_context243 def cli_string_ctx_exit(ctx):244 click.echo("hello world")245 ctx.exit("error")246247 @click.command()248 def cli_int():249 click.echo("hello world")250 sys.exit(1)251252 @click.command()253 @click.pass_context254 def cli_int_ctx_exit(ctx):255 click.echo("hello world")256 ctx.exit(1)257258 @click.command()259 def cli_float():260 click.echo("hello world")261 sys.exit(1.0)262263 @click.command()264 @click.pass_context265 def cli_float_ctx_exit(ctx):266 click.echo("hello world")267 ctx.exit(1.0)268269 @click.command()270 def cli_no_error():271 click.echo("hello world")272273 runner = CliRunner()274275 result = runner.invoke(cli_string)276 assert result.exit_code == 1277 assert result.output == "hello world\nerror\n"278279 result = runner.invoke(cli_string_ctx_exit)280 assert result.exit_code == 1281 assert result.output == "hello world\nerror\n"282283 result = runner.invoke(cli_int)284 assert result.exit_code == 1285 assert result.output == "hello world\n"286287 result = runner.invoke(cli_int_ctx_exit)288 assert result.exit_code == 1289 assert result.output == "hello world\n"290291 result = runner.invoke(cli_float)292 assert result.exit_code == 1293 assert result.output == "hello world\n1.0\n"294295 result = runner.invoke(cli_float_ctx_exit)296 assert result.exit_code == 1297 assert result.output == "hello world\n1.0\n"298299 result = runner.invoke(cli_no_error)300 assert result.exit_code == 0301 assert result.output == "hello world\n"302303304def test_env():305 @click.command()306 def cli_env():307 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")308309 runner = CliRunner()310311 env_orig = dict(os.environ)312 env = dict(env_orig)313 assert "TEST_CLICK_ENV" not in env314 env["TEST_CLICK_ENV"] = "some_value"315 result = runner.invoke(cli_env, env=env)316 assert result.exit_code == 0317 assert result.output == "ENV=some_value\n"318319 assert os.environ == env_orig320321322def test_stderr():323 @click.command()324 def cli_stderr():325 click.echo("1 - stdout")326 click.echo("2 - stderr", err=True)327 click.echo("3 - stdout")328 click.echo("4 - stderr", err=True)329330 runner_mix = CliRunner()331 result_mix = runner_mix.invoke(cli_stderr)332333 assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"334 assert result_mix.stdout == "1 - stdout\n3 - stdout\n"335 assert result_mix.stderr == "2 - stderr\n4 - stderr\n"336337 @click.command()338 def cli_empty_stderr():339 click.echo("stdout")340341 runner = CliRunner()342 result = runner.invoke(cli_empty_stderr)343344 assert result.output == "stdout\n"345 assert result.stdout == "stdout\n"346 assert result.stderr == ""347348349@pytest.mark.parametrize(350 "args, expected_output",351 [352 (None, "bar\n"),353 ([], "bar\n"),354 ("", "bar\n"),355 (["--foo", "one two"], "one two\n"),356 ('--foo "one two"', "one two\n"),357 ],358)359def test_args(args, expected_output):360 @click.command()361 @click.option("--foo", default="bar")362 def cli_args(foo):363 click.echo(foo)364365 runner = CliRunner()366 result = runner.invoke(cli_args, args=args)367 assert result.exit_code == 0368 assert result.output == expected_output369370371def test_setting_prog_name_in_extra():372 @click.command()373 def cli():374 click.echo("ok")375376 runner = CliRunner()377 result = runner.invoke(cli, prog_name="foobar")378 assert not result.exception379 assert result.output == "ok\n"380381382def test_command_standalone_mode_returns_value():383 @click.command()384 def cli():385 click.echo("ok")386 return "Hello, World!"387388 runner = CliRunner()389 result = runner.invoke(cli, standalone_mode=False)390 assert result.output == "ok\n"391 assert result.return_value == "Hello, World!"392 assert result.exit_code == 0393394395def test_file_stdin_attrs(runner):396 @click.command()397 @click.argument("f", type=click.File())398 def cli(f):399 click.echo(f.name)400 click.echo(f.mode, nl=False)401402 result = runner.invoke(cli, ["-"])403 assert result.output == "<stdin>\nr"404405406def test_isolated_runner(runner):407 with runner.isolated_filesystem() as d:408 assert os.path.exists(d)409410 assert not os.path.exists(d)411412413def test_isolated_runner_custom_tempdir(runner, tmp_path):414 with runner.isolated_filesystem(temp_dir=tmp_path) as d:415 assert os.path.exists(d)416417 assert os.path.exists(d)418 os.rmdir(d)419420421def test_isolation_stderr_errors():422 """Writing to stderr should escape invalid characters instead of423 raising a UnicodeEncodeError.424 """425 runner = CliRunner()426427 with runner.isolation() as (_, err, _):428 click.echo("\udce2", err=True, nl=False)429430 assert err.getvalue() == b"\\udce2"