test_testing.py
This file
Path
tests/test_testing.py
471 lines · 12.1 KiB · Python
Last changed by
fix a race in `click.testing.StreamMixer`'s finalization, seen in a multi-threaded context (#2991)Rowlando13before adoption737bfbd
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_catch_exceptions_cli_runner():188 """Test that invoke `catch_exceptions` takes the value from CliRunner if not set189 explicitly."""190191 class CustomError(Exception):192 pass193194 @click.command()195 def cli():196 raise CustomError(1)197198 runner = CliRunner(catch_exceptions=False)199200 result = runner.invoke(cli, catch_exceptions=True)201 assert isinstance(result.exception, CustomError)202 assert type(result.exc_info) is tuple203 assert len(result.exc_info) == 3204205 with pytest.raises(CustomError):206 runner.invoke(cli)207208209def test_with_color():210 @click.command()211 def cli():212 click.secho("hello world", fg="blue")213214 runner = CliRunner()215216 result = runner.invoke(cli)217 assert result.output == "hello world\n"218 assert not result.exception219220 result = runner.invoke(cli, color=True)221 assert result.output == f"{click.style('hello world', fg='blue')}\n"222 assert not result.exception223224225def test_with_color_errors():226 class CLIError(ClickException):227 def format_message(self) -> str:228 return click.style(self.message, fg="red")229230 @click.command()231 def cli():232 raise CLIError("Red error")233234 runner = CliRunner()235236 result = runner.invoke(cli)237 assert result.output == "Error: Red error\n"238 assert result.exception239240 result = runner.invoke(cli, color=True)241 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"242 assert result.exception243244245def test_with_color_but_pause_not_blocking():246 @click.command()247 def cli():248 click.pause()249250 runner = CliRunner()251 result = runner.invoke(cli, color=True)252 assert not result.exception253 assert result.output == ""254255256def test_exit_code_and_output_from_sys_exit():257 # See issue #362258 @click.command()259 def cli_string():260 click.echo("hello world")261 sys.exit("error")262263 @click.command()264 @click.pass_context265 def cli_string_ctx_exit(ctx):266 click.echo("hello world")267 ctx.exit("error")268269 @click.command()270 def cli_int():271 click.echo("hello world")272 sys.exit(1)273274 @click.command()275 @click.pass_context276 def cli_int_ctx_exit(ctx):277 click.echo("hello world")278 ctx.exit(1)279280 @click.command()281 def cli_float():282 click.echo("hello world")283 sys.exit(1.0)284285 @click.command()286 @click.pass_context287 def cli_float_ctx_exit(ctx):288 click.echo("hello world")289 ctx.exit(1.0)290291 @click.command()292 def cli_no_error():293 click.echo("hello world")294295 runner = CliRunner()296297 result = runner.invoke(cli_string)298 assert result.exit_code == 1299 assert result.output == "hello world\nerror\n"300301 result = runner.invoke(cli_string_ctx_exit)302 assert result.exit_code == 1303 assert result.output == "hello world\nerror\n"304305 result = runner.invoke(cli_int)306 assert result.exit_code == 1307 assert result.output == "hello world\n"308309 result = runner.invoke(cli_int_ctx_exit)310 assert result.exit_code == 1311 assert result.output == "hello world\n"312313 result = runner.invoke(cli_float)314 assert result.exit_code == 1315 assert result.output == "hello world\n1.0\n"316317 result = runner.invoke(cli_float_ctx_exit)318 assert result.exit_code == 1319 assert result.output == "hello world\n1.0\n"320321 result = runner.invoke(cli_no_error)322 assert result.exit_code == 0323 assert result.output == "hello world\n"324325326def test_env():327 @click.command()328 def cli_env():329 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")330331 runner = CliRunner()332333 env_orig = dict(os.environ)334 env = dict(env_orig)335 assert "TEST_CLICK_ENV" not in env336 env["TEST_CLICK_ENV"] = "some_value"337 result = runner.invoke(cli_env, env=env)338 assert result.exit_code == 0339 assert result.output == "ENV=some_value\n"340341 assert os.environ == env_orig342343344def test_stderr():345 @click.command()346 def cli_stderr():347 click.echo("1 - stdout")348 click.echo("2 - stderr", err=True)349 click.echo("3 - stdout")350 click.echo("4 - stderr", err=True)351352 runner_mix = CliRunner()353 result_mix = runner_mix.invoke(cli_stderr)354355 assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"356 assert result_mix.stdout == "1 - stdout\n3 - stdout\n"357 assert result_mix.stderr == "2 - stderr\n4 - stderr\n"358359 @click.command()360 def cli_empty_stderr():361 click.echo("stdout")362363 runner = CliRunner()364 result = runner.invoke(cli_empty_stderr)365366 assert result.output == "stdout\n"367 assert result.stdout == "stdout\n"368 assert result.stderr == ""369370371@pytest.mark.parametrize(372 "args, expected_output",373 [374 (None, "bar\n"),375 ([], "bar\n"),376 ("", "bar\n"),377 (["--foo", "one two"], "one two\n"),378 ('--foo "one two"', "one two\n"),379 ],380)381def test_args(args, expected_output):382 @click.command()383 @click.option("--foo", default="bar")384 def cli_args(foo):385 click.echo(foo)386387 runner = CliRunner()388 result = runner.invoke(cli_args, args=args)389 assert result.exit_code == 0390 assert result.output == expected_output391392393def test_setting_prog_name_in_extra():394 @click.command()395 def cli():396 click.echo("ok")397398 runner = CliRunner()399 result = runner.invoke(cli, prog_name="foobar")400 assert not result.exception401 assert result.output == "ok\n"402403404def test_command_standalone_mode_returns_value():405 @click.command()406 def cli():407 click.echo("ok")408 return "Hello, World!"409410 runner = CliRunner()411 result = runner.invoke(cli, standalone_mode=False)412 assert result.output == "ok\n"413 assert result.return_value == "Hello, World!"414 assert result.exit_code == 0415416417def test_file_stdin_attrs(runner):418 @click.command()419 @click.argument("f", type=click.File())420 def cli(f):421 click.echo(f.name)422 click.echo(f.mode, nl=False)423424 result = runner.invoke(cli, ["-"])425 assert result.output == "<stdin>\nr"426427428def test_isolated_runner(runner):429 with runner.isolated_filesystem() as d:430 assert os.path.exists(d)431432 assert not os.path.exists(d)433434435def test_isolated_runner_custom_tempdir(runner, tmp_path):436 with runner.isolated_filesystem(temp_dir=tmp_path) as d:437 assert os.path.exists(d)438439 assert os.path.exists(d)440 os.rmdir(d)441442443def test_isolation_stderr_errors():444 """Writing to stderr should escape invalid characters instead of445 raising a UnicodeEncodeError.446 """447 runner = CliRunner()448449 with runner.isolation() as (_, err, _):450 click.echo("\udce2", err=True, nl=False)451 assert err.getvalue() == b"\\udce2"452453454def test_isolation_flushes_unflushed_stderr():455 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up456 flushed by the runner at end of invocation.457 """458 runner = CliRunner()459460 with runner.isolation() as (_, err, _):461 click.echo("\udce2", err=True, nl=False)462 assert err.getvalue() == b"\\udce2"463464 @click.command()465 def cli():466 # set end="", flush=False so that it's totally clear that we won't get any467 # auto-flush behaviors468 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)469470 result = runner.invoke(cli)471 assert result.stderr == "gyarados gyarados gyarados"