Debian Codegraph @

tests/test_context.py

raw
1 import logging
2 from contextlib import AbstractContextManager
3 from contextlib import contextmanager
4 from types import TracebackType
5
6 import pytest
7
8 import click
9 from click import Context
10 from click import Option
11 from click import Parameter
12 from click.core import ParameterSource
13 from click.decorators import help_option
14 from click.decorators import pass_meta_key
15
16
17 def test_ensure_context_objects(runner):
18 class Foo:
19 def __init__(self):
20 self.title = "default"
21
22 pass_foo = click.make_pass_decorator(Foo, ensure=True)
23
24 @click.group()
25 @pass_foo
26 def cli(foo):
27 pass
28
29 @cli.command()
30 @pass_foo
31 def test(foo):
32 click.echo(foo.title)
33
34 result = runner.invoke(cli, ["test"])
35 assert not result.exception
36 assert result.output == "default\n"
37
38
39 def test_get_context_objects(runner):
40 class Foo:
41 def __init__(self):
42 self.title = "default"
43
44 pass_foo = click.make_pass_decorator(Foo, ensure=True)
45
46 @click.group()
47 @click.pass_context
48 def cli(ctx):
49 ctx.obj = Foo()
50 ctx.obj.title = "test"
51
52 @cli.command()
53 @pass_foo
54 def test(foo):
55 click.echo(foo.title)
56
57 result = runner.invoke(cli, ["test"])
58 assert not result.exception
59 assert result.output == "test\n"
60
61
62 def test_get_context_objects_no_ensuring(runner):
63 class Foo:
64 def __init__(self):
65 self.title = "default"
66
67 pass_foo = click.make_pass_decorator(Foo)
68
69 @click.group()
70 @click.pass_context
71 def cli(ctx):
72 ctx.obj = Foo()
73 ctx.obj.title = "test"
74
75 @cli.command()
76 @pass_foo
77 def test(foo):
78 click.echo(foo.title)
79
80 result = runner.invoke(cli, ["test"])
81 assert not result.exception
82 assert result.output == "test\n"
83
84
85 def test_get_context_objects_missing(runner):
86 class Foo:
87 pass
88
89 pass_foo = click.make_pass_decorator(Foo)
90
91 @click.group()
92 @click.pass_context
93 def cli(ctx):
94 pass
95
96 @cli.command()
97 @pass_foo
98 def test(foo):
99 click.echo(foo.title)
100
101 result = runner.invoke(cli, ["test"])
102 assert result.exception is not None
103 assert isinstance(result.exception, RuntimeError)
104 assert (
105 "Managed to invoke callback without a context object of type"
106 " 'Foo' existing" in str(result.exception)
107 )
108
109
110 def test_multi_enter(runner):
111 called = []
112
113 @click.command()
114 @click.pass_context
115 def cli(ctx):
116 def callback():
117 called.append(True)
118
119 ctx.call_on_close(callback)
120
121 with ctx:
122 pass
123 assert not called
124
125 result = runner.invoke(cli, [])
126 assert result.exception is None
127 assert called == [True]
128
129
130 def test_global_context_object(runner):
131 @click.command()
132 @click.pass_context
133 def cli(ctx):
134 assert click.get_current_context() is ctx
135 ctx.obj = "FOOBAR"
136 assert click.get_current_context().obj == "FOOBAR"
137
138 assert click.get_current_context(silent=True) is None
139 runner.invoke(cli, [], catch_exceptions=False)
140 assert click.get_current_context(silent=True) is None
141
142
143 def test_context_meta(runner):
144 LANG_KEY = f"{__name__}.lang"
145
146 def set_language(value):
147 click.get_current_context().meta[LANG_KEY] = value
148
149 def get_language():
150 return click.get_current_context().meta.get(LANG_KEY, "en_US")
151
152 @click.command()
153 @click.pass_context
154 def cli(ctx):
155 assert get_language() == "en_US"
156 set_language("de_DE")
157 assert get_language() == "de_DE"
158
159 runner.invoke(cli, [], catch_exceptions=False)
160
161
162 def test_make_pass_meta_decorator(runner):
163 @click.group()
164 @click.pass_context
165 def cli(ctx):
166 ctx.meta["value"] = "good"
167
168 @cli.command()
169 @pass_meta_key("value")
170 def show(value):
171 return value
172
173 result = runner.invoke(cli, ["show"], standalone_mode=False)
174 assert result.return_value == "good"
175
176
177 def test_make_pass_meta_decorator_doc():
178 pass_value = pass_meta_key("value")
179 assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__
180 pass_value = pass_meta_key("value", doc_description="the test value")
181 assert "passes the test value" in pass_value.__doc__
182
183
184 def test_hiding_of_unset_sentinel_in_callbacks():
185 """Fix: https://github.com/pallets/click/issues/3136"""
186
187 def inspect_other_params(ctx, param, value):
188 """A callback that inspects other parameters' values via the context."""
189 assert click.get_current_context() is ctx
190 click.echo(f"callback.my_arg: {ctx.params.get('my_arg')!r}")
191 click.echo(f"callback.my_opt: {ctx.params.get('my_opt')!r}")
192 click.echo(f"callback.my_callback: {ctx.params.get('my_callback')!r}")
193
194 click.echo(f"callback.param: {param!r}")
195 click.echo(f"callback.value: {value!r}")
196
197 return "hard-coded"
198
199 class ParameterInternalCheck(Option):
200 """An option that checks internal state during processing."""
201
202 def process_value(self, ctx, value):
203 """Check that UNSET values are hidden as None in ctx.params within the
204 callback, and then properly restored afterwards.
205 """
206 assert click.get_current_context() is ctx
207 click.echo(f"before_process.my_arg: {ctx.params.get('my_arg')!r}")
208 click.echo(f"before_process.my_opt: {ctx.params.get('my_opt')!r}")
209 click.echo(f"before_process.my_callback: {ctx.params.get('my_callback')!r}")
210
211 value = super().process_value(ctx, value)
212
213 assert click.get_current_context() is ctx
214 click.echo(f"after_process.my_arg: {ctx.params.get('my_arg')!r}")
215 click.echo(f"after_process.my_opt: {ctx.params.get('my_opt')!r}")
216 click.echo(f"after_process.my_callback: {ctx.params.get('my_callback')!r}")
217
218 return value
219
220 def change_other_params(ctx, param, value):
221 """A callback that modifies other parameters' values via the context."""
222 assert click.get_current_context() is ctx
223 click.echo(f"before_change.my_arg: {ctx.params.get('my_arg')!r}")
224 click.echo(f"before_change.my_opt: {ctx.params.get('my_opt')!r}")
225 click.echo(f"before_change.my_callback: {ctx.params.get('my_callback')!r}")
226
227 click.echo(f"before_change.param: {param!r}")
228 click.echo(f"before_change.value: {value!r}")
229
230 ctx.params["my_arg"] = "changed"
231 # Reset to None parameters that where not UNSET to see they are not forced back
232 # to UNSET.
233 ctx.params["my_callback"] = None
234
235 return value
236
237 @click.command
238 @click.argument("my-arg", required=False)
239 @click.option("--my-opt")
240 @click.option("--my-callback", callback=inspect_other_params)
241 @click.option("--check-internal", cls=ParameterInternalCheck)
242 @click.option(
243 "--modifying-callback", cls=ParameterInternalCheck, callback=change_other_params
244 )
245 @click.pass_context
246 def cli(ctx, my_arg, my_opt, my_callback, check_internal, modifying_callback):
247 click.echo(f"cli.my_arg: {my_arg!r}")
248 click.echo(f"cli.my_opt: {my_opt!r}")
249 click.echo(f"cli.my_callback: {my_callback!r}")
250 click.echo(f"cli.check_internal: {check_internal!r}")
251 click.echo(f"cli.modifying_callback: {modifying_callback!r}")
252
253 runner = click.testing.CliRunner()
254 result = runner.invoke(cli)
255
256 assert result.stdout.splitlines() == [
257 # Values of other parameters within the callback are None, not UNSET.
258 "callback.my_arg: None",
259 "callback.my_opt: None",
260 "callback.my_callback: None",
261 "callback.param: <Option my_callback>",
262 "callback.value: None",
263 # Previous UNSET values were not altered by the callback.
264 "before_process.my_arg: Sentinel.UNSET",
265 "before_process.my_opt: Sentinel.UNSET",
266 "before_process.my_callback: 'hard-coded'",
267 "after_process.my_arg: Sentinel.UNSET",
268 "after_process.my_opt: Sentinel.UNSET",
269 "after_process.my_callback: 'hard-coded'",
270 # Changes on other parameters within the callback are restored afterwards.
271 "before_process.my_arg: Sentinel.UNSET",
272 "before_process.my_opt: Sentinel.UNSET",
273 "before_process.my_callback: 'hard-coded'",
274 "before_change.my_arg: None",
275 "before_change.my_opt: None",
276 "before_change.my_callback: 'hard-coded'",
277 "before_change.param: <ParameterInternalCheck modifying_callback>",
278 "before_change.value: None",
279 "after_process.my_arg: 'changed'",
280 "after_process.my_opt: Sentinel.UNSET",
281 "after_process.my_callback: None",
282 # Unset values within the main command are UNSET, but hidden as None.
283 "cli.my_arg: 'changed'",
284 "cli.my_opt: None",
285 "cli.my_callback: None",
286 "cli.check_internal: None",
287 "cli.modifying_callback: None",
288 ]
289 assert not result.stderr
290 assert not result.exception
291 assert result.exit_code == 0
292
293
294 def test_context_pushing():
295 rv = []
296
297 @click.command()
298 def cli():
299 pass
300
301 ctx = click.Context(cli)
302
303 @ctx.call_on_close
304 def test_callback():
305 rv.append(42)
306
307 with ctx.scope(cleanup=False):
308 # Internal
309 assert ctx._depth == 2
310
311 assert rv == []
312
313 with ctx.scope():
314 # Internal
315 assert ctx._depth == 1
316
317 assert rv == [42]
318
319
320 def test_pass_obj(runner):
321 @click.group()
322 @click.pass_context
323 def cli(ctx):
324 ctx.obj = "test"
325
326 @cli.command()
327 @click.pass_obj
328 def test(obj):
329 click.echo(obj)
330
331 result = runner.invoke(cli, ["test"])
332 assert not result.exception
333 assert result.output == "test\n"
334
335
336 def test_close_before_pop(runner):
337 called = []
338
339 @click.command()
340 @click.pass_context
341 def cli(ctx):
342 ctx.obj = "test"
343
344 @ctx.call_on_close
345 def foo():
346 assert click.get_current_context().obj == "test"
347 called.append(True)
348
349 click.echo("aha!")
350
351 result = runner.invoke(cli, [])
352 assert not result.exception
353 assert result.output == "aha!\n"
354 assert called == [True]
355
356
357 def test_close_before_exit(runner):
358 called = []
359
360 @click.command()
361 @click.pass_context
362 def cli(ctx):
363 ctx.obj = "test"
364
365 @ctx.call_on_close
366 def foo():
367 assert click.get_current_context().obj == "test"
368 called.append(True)
369
370 ctx.exit()
371
372 click.echo("aha!")
373
374 result = runner.invoke(cli, [])
375 assert not result.exception
376 assert not result.output
377 assert called == [True]
378
379
380 @pytest.mark.parametrize(
381 ("cli_args", "expect"),
382 [
383 pytest.param(
384 ("--option-with-callback", "--force-exit"),
385 ["ExitingOption", "NonExitingOption"],
386 id="natural_order",
387 ),
388 pytest.param(
389 ("--force-exit", "--option-with-callback"),
390 ["ExitingOption"],
391 id="eagerness_precedence",
392 ),
393 ],
394 )
395 def test_multiple_eager_callbacks(runner, cli_args, expect):
396 """Checks all callbacks are called on exit, even the nasty ones hidden within
397 callbacks.
398
399 Also checks the order in which they're called.
400 """
401 # Keeps track of callback calls.
402 called = []
403
404 class NonExitingOption(Option):
405 def reset_state(self):
406 called.append(self.__class__.__name__)
407
408 def set_state(self, ctx: Context, param: Parameter, value: str) -> str:
409 ctx.call_on_close(self.reset_state)
410 return value
411
412 def __init__(self, *args, **kwargs) -> None:
413 kwargs.setdefault("expose_value", False)
414 kwargs.setdefault("callback", self.set_state)
415 super().__init__(*args, **kwargs)
416
417 class ExitingOption(NonExitingOption):
418 def set_state(self, ctx: Context, param: Parameter, value: str) -> str:
419 value = super().set_state(ctx, param, value)
420 ctx.exit()
421 return value
422
423 @click.command()
424 @click.option("--option-with-callback", is_eager=True, cls=NonExitingOption)
425 @click.option("--force-exit", is_eager=True, cls=ExitingOption)
426 def cli():
427 click.echo("This will never be printed as we forced exit via --force-exit")
428
429 result = runner.invoke(cli, cli_args)
430 assert not result.exception
431 assert not result.output
432
433 assert called == expect
434
435
436 def test_no_state_leaks(runner):
437 """Demonstrate state leaks with a specific case of the generic test above.
438
439 Use a logger as a real-world example of a common fixture which, due to its global
440 nature, can leak state if not clean-up properly in a callback.
441 """
442 # Keeps track of callback calls.
443 called = []
444
445 class DebugLoggerOption(Option):
446 """A custom option to set the name of the debug logger."""
447
448 logger_name: str
449 """The ID of the logger to use."""
450
451 def reset_loggers(self):
452 """Forces logger managed by the option to be reset to the default level."""
453 logger = logging.getLogger(self.logger_name)
454 logger.setLevel(logging.NOTSET)
455
456 # Logger has been properly reset to its initial state.
457 assert logger.level == logging.NOTSET
458 assert logger.getEffectiveLevel() == logging.WARNING
459
460 called.append(True)
461
462 def set_level(self, ctx: Context, param: Parameter, value: str) -> None:
463 """Set the logger to DEBUG level."""
464 # Keep the logger name around so we can reset it later when winding down
465 # the option.
466 self.logger_name = value
467
468 # Get the global logger object.
469 logger = logging.getLogger(self.logger_name)
470
471 # Check pre-conditions: new logger is not set, but inherits its level from
472 # default <root> logger. That's the exact same state we are expecting our
473 # logger to be in after being messed with by the CLI.
474 assert logger.level == logging.NOTSET
475 assert logger.getEffectiveLevel() == logging.WARNING
476
477 logger.setLevel(logging.DEBUG)
478 ctx.call_on_close(self.reset_loggers)
479 return value
480
481 def __init__(self, *args, **kwargs) -> None:
482 kwargs.setdefault("callback", self.set_level)
483 super().__init__(*args, **kwargs)
484
485 @click.command()
486 @click.option("--debug-logger-name", is_eager=True, cls=DebugLoggerOption)
487 @help_option()
488 @click.pass_context
489 def messing_with_logger(ctx, debug_logger_name):
490 # Introspect context to make sure logger name are aligned.
491 assert debug_logger_name == ctx.command.params[0].logger_name
492
493 logger = logging.getLogger(debug_logger_name)
494
495 # Logger's level has been properly set to DEBUG by DebugLoggerOption.
496 assert logger.level == logging.DEBUG
497 assert logger.getEffectiveLevel() == logging.DEBUG
498
499 logger.debug("Blah blah blah")
500
501 ctx.exit()
502
503 click.echo("This will never be printed as we exited early")
504
505 # Call the CLI to mess with the custom logger.
506 result = runner.invoke(
507 messing_with_logger, ["--debug-logger-name", "my_logger", "--help"]
508 )
509
510 assert called == [True]
511
512 # Check the custom logger has been reverted to it initial state by the option
513 # callback after being messed with by the CLI.
514 logger = logging.getLogger("my_logger")
515 assert logger.level == logging.NOTSET
516 assert logger.getEffectiveLevel() == logging.WARNING
517
518 assert not result.exception
519 assert result.output.startswith("Usage: messing-with-logger [OPTIONS]")
520
521
522 def test_with_resource():
523 @contextmanager
524 def manager():
525 val = [1]
526 yield val
527 val[0] = 0
528
529 ctx = click.Context(click.Command("test"))
530
531 with ctx.scope():
532 rv = ctx.with_resource(manager())
533 assert rv[0] == 1
534
535 assert rv == [0]
536
537
538 def test_with_resource_exception() -> None:
539 class TestContext(AbstractContextManager[list[int]]):
540 _handle_exception: bool
541 _base_val: int
542 val: list[int]
543
544 def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:
545 self._handle_exception = handle_exception
546 self._base_val = base_val
547
548 def __enter__(self) -> list[int]:
549 self.val = [self._base_val]
550 return self.val
551
552 def __exit__(
553 self,
554 exc_type: type[BaseException] | None,
555 exc_value: BaseException | None,
556 traceback: TracebackType | None,
557 ) -> bool | None:
558 if not exc_type:
559 self.val[0] = self._base_val - 1
560 return None
561
562 self.val[0] = self._base_val + 1
563 return self._handle_exception
564
565 class TestException(Exception):
566 pass
567
568 ctx = click.Context(click.Command("test"))
569
570 base_val = 1
571
572 with ctx.scope():
573 rv = ctx.with_resource(TestContext(base_val=base_val))
574 assert rv[0] == base_val
575
576 assert rv == [base_val - 1]
577
578 with ctx.scope():
579 rv = ctx.with_resource(TestContext(base_val=base_val))
580 raise TestException()
581
582 assert rv == [base_val + 1]
583
584 with pytest.raises(TestException):
585 with ctx.scope():
586 rv = ctx.with_resource(
587 TestContext(base_val=base_val, handle_exception=False)
588 )
589 raise TestException()
590
591
592 def test_with_resource_nested_exception() -> None:
593 class TestContext(AbstractContextManager[list[int]]):
594 _handle_exception: bool
595 _base_val: int
596 val: list[int]
597
598 def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:
599 self._handle_exception = handle_exception
600 self._base_val = base_val
601
602 def __enter__(self) -> list[int]:
603 self.val = [self._base_val]
604 return self.val
605
606 def __exit__(
607 self,
608 exc_type: type[BaseException] | None,
609 exc_value: BaseException | None,
610 traceback: TracebackType | None,
611 ) -> bool | None:
612 if not exc_type:
613 self.val[0] = self._base_val - 1
614 return None
615
616 self.val[0] = self._base_val + 1
617 return self._handle_exception
618
619 class TestException(Exception):
620 pass
621
622 ctx = click.Context(click.Command("test"))
623 base_val = 1
624 base_val_nested = 11
625
626 with ctx.scope():
627 rv = ctx.with_resource(TestContext(base_val=base_val))
628 rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))
629 assert rv[0] == base_val
630 assert rv_nested[0] == base_val_nested
631
632 assert rv == [base_val - 1]
633 assert rv_nested == [base_val_nested - 1]
634
635 with ctx.scope():
636 rv = ctx.with_resource(TestContext(base_val=base_val))
637 rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))
638 raise TestException()
639
640 # If one of the context "eats" the exceptions they will not be forwarded to other
641 # parts. This is due to how ExitStack unwinding works
642 assert rv_nested == [base_val_nested + 1]
643 assert rv == [base_val - 1]
644
645 with ctx.scope():
646 rv = ctx.with_resource(TestContext(base_val=base_val))
647 rv_nested = ctx.with_resource(
648 TestContext(base_val=base_val_nested, handle_exception=False)
649 )
650 raise TestException()
651
652 assert rv_nested == [base_val_nested + 1]
653 assert rv == [base_val + 1]
654
655 with pytest.raises(TestException):
656 rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False))
657 rv_nested = ctx.with_resource(
658 TestContext(base_val=base_val_nested, handle_exception=False)
659 )
660 raise TestException()
661
662
663 def test_make_pass_decorator_args(runner):
664 """
665 Test to check that make_pass_decorator doesn't consume arguments based on
666 invocation order.
667 """
668
669 class Foo:
670 title = "foocmd"
671
672 pass_foo = click.make_pass_decorator(Foo)
673
674 @click.group()
675 @click.pass_context
676 def cli(ctx):
677 ctx.obj = Foo()
678
679 @cli.command()
680 @click.pass_context
681 @pass_foo
682 def test1(foo, ctx):
683 click.echo(foo.title)
684
685 @cli.command()
686 @pass_foo
687 @click.pass_context
688 def test2(ctx, foo):
689 click.echo(foo.title)
690
691 result = runner.invoke(cli, ["test1"])
692 assert not result.exception
693 assert result.output == "foocmd\n"
694
695 result = runner.invoke(cli, ["test2"])
696 assert not result.exception
697 assert result.output == "foocmd\n"
698
699
700 def test_propagate_show_default_setting(runner):
701 """A context's ``show_default`` setting defaults to the value from
702 the parent context.
703 """
704 group = click.Group(
705 commands={
706 "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]),
707 },
708 context_settings={"show_default": True},
709 )
710 result = runner.invoke(group, ["sub", "--help"])
711 assert "[default: a]" in result.output
712
713
714 def test_exit_not_standalone():
715 @click.command()
716 @click.pass_context
717 def cli(ctx):
718 ctx.exit(1)
719
720 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1
721
722 @click.command()
723 @click.pass_context
724 def cli(ctx):
725 ctx.exit(0)
726
727 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0
728
729
730 @pytest.mark.parametrize(
731 ("option_args", "invoke_args", "expect"),
732 [
733 pytest.param({}, {}, ParameterSource.DEFAULT, id="default"),
734 pytest.param(
735 {},
736 {"default_map": {"option": 1}},
737 ParameterSource.DEFAULT_MAP,
738 id="default_map",
739 ),
740 pytest.param(
741 {},
742 {"args": ["-o", "1"]},
743 ParameterSource.COMMANDLINE,
744 id="commandline short",
745 ),
746 pytest.param(
747 {},
748 {"args": ["--option", "1"]},
749 ParameterSource.COMMANDLINE,
750 id="commandline long",
751 ),
752 pytest.param(
753 {},
754 {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}},
755 ParameterSource.ENVIRONMENT,
756 id="environment auto",
757 ),
758 pytest.param(
759 {"envvar": "NAME"},
760 {"env": {"NAME": "1"}},
761 ParameterSource.ENVIRONMENT,
762 id="environment manual",
763 ),
764 ],
765 )
766 def test_parameter_source(runner, option_args, invoke_args, expect):
767 @click.command()
768 @click.pass_context
769 @click.option("-o", "--option", default=1, **option_args)
770 def cli(ctx, option):
771 return ctx.get_parameter_source("option")
772
773 rv = runner.invoke(cli, standalone_mode=False, **invoke_args)
774 assert rv.return_value == expect
775
776
777 def test_propagate_opt_prefixes():
778 parent = click.Context(click.Command("test"))
779 parent._opt_prefixes = {"-", "--", "!"}
780 ctx = click.Context(click.Command("test2"), parent=parent)
781
782 assert ctx._opt_prefixes == {"-", "--", "!"}