Debian Codegraph @

tests/test_testing.py

raw
1 import faulthandler
2 import os
3 import pdb
4 import sys
5 from io import BytesIO
6
7 import pytest
8
9 import click
10 from click.exceptions import ClickException
11 from click.testing import CliRunner
12
13
14 def 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 break
23 o.write(chunk)
24 o.flush()
25
26 runner = CliRunner()
27 result = runner.invoke(test, input="Hello World!\n")
28 assert not result.exception
29 assert result.output == "Hello World!\n"
30
31
32 def 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 break
41 o.write(chunk)
42 o.flush()
43
44 runner = CliRunner(echo_stdin=True)
45 result = runner.invoke(test, input="Hello World!\n")
46 assert not result.exception
47 assert result.output == "Hello World!\nHello World!\n"
48
49
50 def test_echo_stdin_prompts():
51 @click.command()
52 def test_python_input():
53 foo = input("Foo: ")
54 click.echo(f"foo={foo}")
55
56 runner = CliRunner(echo_stdin=True)
57 result = runner.invoke(test_python_input, input="bar bar\n")
58 assert not result.exception
59 assert result.output == "Foo: bar bar\nfoo=bar bar\n"
60
61 @click.command()
62 @click.option("--foo", prompt=True)
63 def test_prompt(foo):
64 click.echo(f"foo={foo}")
65
66 result = runner.invoke(test_prompt, input="bar bar\n")
67 assert not result.exception
68 assert result.output == "Foo: bar bar\nfoo=bar bar\n"
69
70 @click.command()
71 @click.option("--foo", prompt=True, hide_input=True)
72 def test_hidden_prompt(foo):
73 click.echo(f"foo={foo}")
74
75 result = runner.invoke(test_hidden_prompt, input="bar bar\n")
76 assert not result.exception
77 assert result.output == "Foo: \nfoo=bar bar\n"
78
79 @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}")
84
85 result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")
86 assert not result.exception
87 assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"
88
89
90 def 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 break
99 o.write(chunk)
100 o.flush()
101
102 runner = CliRunner()
103 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))
104 assert not result.exception
105 assert result.output == "Hello World!\n"
106
107 runner = CliRunner(echo_stdin=True)
108 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))
109 assert not result.exception
110 assert result.output == "Hello World!\nHello World!\n"
111
112
113 def test_prompts():
114 @click.command()
115 @click.option("--foo", prompt=True)
116 def test(foo):
117 click.echo(f"foo={foo}")
118
119 runner = CliRunner()
120 result = runner.invoke(test, input="wau wau\n")
121 assert not result.exception
122 assert result.output == "Foo: wau wau\nfoo=wau wau\n"
123
124 @click.command()
125 @click.option("--foo", prompt=True, hide_input=True)
126 def test(foo):
127 click.echo(f"foo={foo}")
128
129 runner = CliRunner()
130 result = runner.invoke(test, input="wau wau\n")
131 assert not result.exception
132 assert result.output == "Foo: \nfoo=wau wau\n"
133
134
135 def test_getchar():
136 @click.command()
137 def continue_it():
138 click.echo(click.getchar())
139
140 runner = CliRunner()
141 result = runner.invoke(continue_it, input="y")
142 assert not result.exception
143 assert result.output == "y\n"
144
145 runner = CliRunner(echo_stdin=True)
146 result = runner.invoke(continue_it, input="y")
147 assert not result.exception
148 assert result.output == "y\n"
149
150 @click.command()
151 def getchar_echo():
152 click.echo(click.getchar(echo=True))
153
154 runner = CliRunner()
155 result = runner.invoke(getchar_echo, input="y")
156 assert not result.exception
157 assert result.output == "yy\n"
158
159 runner = CliRunner(echo_stdin=True)
160 result = runner.invoke(getchar_echo, input="y")
161 assert not result.exception
162 assert result.output == "yy\n"
163
164
165 def test_catch_exceptions():
166 class CustomError(Exception):
167 pass
168
169 @click.command()
170 def cli():
171 raise CustomError(1)
172
173 runner = CliRunner()
174
175 result = runner.invoke(cli)
176 assert isinstance(result.exception, CustomError)
177 assert type(result.exc_info) is tuple
178 assert len(result.exc_info) == 3
179
180 with pytest.raises(CustomError):
181 runner.invoke(cli, catch_exceptions=False)
182
183 CustomError = SystemExit
184
185 result = runner.invoke(cli)
186 assert result.exit_code == 1
187
188
189 def test_catch_exceptions_cli_runner():
190 """Test that invoke `catch_exceptions` takes the value from CliRunner if not set
191 explicitly."""
192
193 class CustomError(Exception):
194 pass
195
196 @click.command()
197 def cli():
198 raise CustomError(1)
199
200 runner = CliRunner(catch_exceptions=False)
201
202 result = runner.invoke(cli, catch_exceptions=True)
203 assert isinstance(result.exception, CustomError)
204 assert type(result.exc_info) is tuple
205 assert len(result.exc_info) == 3
206
207 with pytest.raises(CustomError):
208 runner.invoke(cli)
209
210
211 def test_with_color():
212 @click.command()
213 def cli():
214 click.secho("hello world", fg="blue")
215
216 runner = CliRunner()
217
218 result = runner.invoke(cli)
219 assert result.output == "hello world\n"
220 assert not result.exception
221
222 result = runner.invoke(cli, color=True)
223 assert result.output == f"{click.style('hello world', fg='blue')}\n"
224 assert not result.exception
225
226
227 def test_with_color_errors():
228 class CLIError(ClickException):
229 def format_message(self) -> str:
230 return click.style(self.message, fg="red")
231
232 @click.command()
233 def cli():
234 raise CLIError("Red error")
235
236 runner = CliRunner()
237
238 result = runner.invoke(cli)
239 assert result.output == "Error: Red error\n"
240 assert result.exception
241
242 result = runner.invoke(cli, color=True)
243 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"
244 assert result.exception
245
246
247 def test_with_color_but_pause_not_blocking():
248 @click.command()
249 def cli():
250 click.pause()
251
252 runner = CliRunner()
253 result = runner.invoke(cli, color=True)
254 assert not result.exception
255 assert result.output == ""
256
257
258 def test_exit_code_and_output_from_sys_exit():
259 # See issue #362
260 @click.command()
261 def cli_string():
262 click.echo("hello world")
263 sys.exit("error")
264
265 @click.command()
266 @click.pass_context
267 def cli_string_ctx_exit(ctx):
268 click.echo("hello world")
269 ctx.exit("error")
270
271 @click.command()
272 def cli_int():
273 click.echo("hello world")
274 sys.exit(1)
275
276 @click.command()
277 @click.pass_context
278 def cli_int_ctx_exit(ctx):
279 click.echo("hello world")
280 ctx.exit(1)
281
282 @click.command()
283 def cli_float():
284 click.echo("hello world")
285 sys.exit(1.0)
286
287 @click.command()
288 @click.pass_context
289 def cli_float_ctx_exit(ctx):
290 click.echo("hello world")
291 ctx.exit(1.0)
292
293 @click.command()
294 def cli_no_error():
295 click.echo("hello world")
296
297 runner = CliRunner()
298
299 result = runner.invoke(cli_string)
300 assert result.exit_code == 1
301 assert result.output == "hello world\nerror\n"
302
303 result = runner.invoke(cli_string_ctx_exit)
304 assert result.exit_code == 1
305 assert result.output == "hello world\nerror\n"
306
307 result = runner.invoke(cli_int)
308 assert result.exit_code == 1
309 assert result.output == "hello world\n"
310
311 result = runner.invoke(cli_int_ctx_exit)
312 assert result.exit_code == 1
313 assert result.output == "hello world\n"
314
315 result = runner.invoke(cli_float)
316 assert result.exit_code == 1
317 assert result.output == "hello world\n1.0\n"
318
319 result = runner.invoke(cli_float_ctx_exit)
320 assert result.exit_code == 1
321 assert result.output == "hello world\n1.0\n"
322
323 result = runner.invoke(cli_no_error)
324 assert result.exit_code == 0
325 assert result.output == "hello world\n"
326
327
328 def test_env():
329 @click.command()
330 def cli_env():
331 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")
332
333 runner = CliRunner()
334
335 env_orig = dict(os.environ)
336 env = dict(env_orig)
337 assert "TEST_CLICK_ENV" not in env
338 env["TEST_CLICK_ENV"] = "some_value"
339 result = runner.invoke(cli_env, env=env)
340 assert result.exit_code == 0
341 assert result.output == "ENV=some_value\n"
342
343 assert os.environ == env_orig
344
345
346 def test_stderr():
347 @click.command()
348 def cli_stderr():
349 click.echo("1 - stdout")
350 click.echo("2 - stderr", err=True)
351 click.echo("3 - stdout")
352 click.echo("4 - stderr", err=True)
353
354 runner_mix = CliRunner()
355 result_mix = runner_mix.invoke(cli_stderr)
356
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"
360
361 @click.command()
362 def cli_empty_stderr():
363 click.echo("stdout")
364
365 runner = CliRunner()
366 result = runner.invoke(cli_empty_stderr)
367
368 assert result.output == "stdout\n"
369 assert result.stdout == "stdout\n"
370 assert result.stderr == ""
371
372
373 @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 )
383 def test_args(args, expected_output):
384 @click.command()
385 @click.option("--foo", default="bar")
386 def cli_args(foo):
387 click.echo(foo)
388
389 runner = CliRunner()
390 result = runner.invoke(cli_args, args=args)
391 assert result.exit_code == 0
392 assert result.output == expected_output
393
394
395 def test_setting_prog_name_in_extra():
396 @click.command()
397 def cli():
398 click.echo("ok")
399
400 runner = CliRunner()
401 result = runner.invoke(cli, prog_name="foobar")
402 assert not result.exception
403 assert result.output == "ok\n"
404
405
406 def test_command_standalone_mode_returns_value():
407 @click.command()
408 def cli():
409 click.echo("ok")
410 return "Hello, World!"
411
412 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 == 0
417
418
419 def 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)
425
426 result = runner.invoke(cli, ["-"])
427 assert result.output == "<stdin>\nr"
428
429
430 def test_isolated_runner(runner):
431 with runner.isolated_filesystem() as d:
432 assert os.path.exists(d)
433
434 assert not os.path.exists(d)
435
436
437 def 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)
440
441 assert os.path.exists(d)
442 os.rmdir(d)
443
444
445 def test_isolation_stderr_errors():
446 """Writing to stderr should escape invalid characters instead of
447 raising a UnicodeEncodeError.
448 """
449 runner = CliRunner()
450
451 with runner.isolation() as (_, err, _):
452 click.echo("\udce2", err=True, nl=False)
453 assert err.getvalue() == b"\\udce2"
454
455
456 def test_isolation_flushes_unflushed_stderr():
457 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up
458 flushed by the runner at end of invocation.
459 """
460 runner = CliRunner()
461
462 with runner.isolation() as (_, err, _):
463 click.echo("\udce2", err=True, nl=False)
464 assert err.getvalue() == b"\\udce2"
465
466 @click.command()
467 def cli():
468 # set end="", flush=False so that it's totally clear that we won't get any
469 # auto-flush behaviors
470 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)
471
472 result = runner.invoke(cli)
473 assert result.stderr == "gyarados gyarados gyarados"
474
475
476 def test_pdb_uses_real_streams():
477 """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams
478 so that interactive debuggers work instead of reading from the
479 captured ``BytesIO`` stdin.
480 """
481
482 @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")
488
489 runner = CliRunner()
490 result = runner.invoke(cli, catch_exceptions=False)
491 assert result.output == "after debugger\n"
492
493
494 def test_pdb_explicit_streams_honored():
495 """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not
496 overridden by the ``CliRunner`` patch.
497 """
498
499 @click.command()
500 def cli():
501 custom_in = sys.stdin
502 custom_out = sys.stdout
503 debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)
504 assert debugger.stdin is custom_in
505 assert debugger.stdout is custom_out
506
507 runner = CliRunner()
508 runner.invoke(cli, catch_exceptions=False)
509
510
511 def test_pdb_init_restored_after_invoke():
512 """``pdb.Pdb.__init__`` is restored to its original after invoke."""
513 original = pdb.Pdb.__init__
514
515 @click.command()
516 def cli():
517 pass
518
519 runner = CliRunner()
520 runner.invoke(cli)
521
522 assert pdb.Pdb.__init__ is original
523
524
525 def test_faulthandler_enable(runner):
526 """``faulthandler.enable()`` inside ``CliRunner`` should not crash with
527 ``io.UnsupportedOperation: fileno``.
528
529 ``faulthandler.enable()`` needs a real OS file descriptor to register
530 its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a
531 ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.
532
533 Reproduce:https://github.com/pallets/click/issues/2865
534 """
535
536 @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.")
544
545 result = runner.invoke(cli, ["--flag", True])
546 assert result.exit_code == 0, result.output
547 assert "Finished executing main function." in result.output