Fix closing of callbacks on CLI exit (#2680)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by GitHub · parent a8c0542 · Browse files · 4 files·+185 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Andreas Backx <andreas@backx.org>
Diff stats
4 files+185 added−1 removed
- tests:+170 added−0 removed
- other:+15 added−1 removed
Provenance
- Commit
c326df9- Tree
2ca9b89- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a8c0542
4 files changed+185 added−1 removed
modified:docs/advanced.rst+5 added
492 unmodified lines493 def close_db():494 db.record_use()495 db.save()496 db.close()497+498+499+.. versionchanged:: 8.2 ``Context.call_on_close`` and context managers registered500+ via ``Context.with_resource`` will be closed when the CLI exits. These were501+ previously not called on exit.modified:src/click/core.py+7 added-1 removed
697 unmodified lines698 """Aborts the script."""699 raise Abort()700 701 def exit(self, code: int = 0) -> t.NoReturn:702- """Exits the application with a given exit code."""702+ """Exits the application with a given exit code.703+704+ .. versionchanged:: 8.2705+ Force closing of callbacks registered with706+ :meth:`call_on_close` before exiting the CLI.707+ """708+ self.close()709 raise Exit(code)710 711 def get_usage(self) -> str:712 """Helper method to get formatted usage string for the current2300 unmodified linesmodified:tests/test_context.py+170 added
1+import logging2 from contextlib import contextmanager3 4 import pytest5 6 import click7+from click import Context8+from click import Option9+from click import Parameter10 from click.core import ParameterSource11+from click.decorators import help_option12 from click.decorators import pass_meta_key13 14 15 def test_ensure_context_objects(runner):225 unmodified lines241 assert result.output == "aha!\n"242 assert called == [True]243 244 245+def test_close_before_exit(runner):246+ called = []247+248+ @click.command()249+ @click.pass_context250+ def cli(ctx):251+ ctx.obj = "test"252+253+ @ctx.call_on_close254+ def foo():255+ assert click.get_current_context().obj == "test"256+ called.append(True)257+258+ ctx.exit()259+260+ click.echo("aha!")261+262+ result = runner.invoke(cli, [])263+ assert not result.exception264+ assert not result.output265+ assert called == [True]266+267+268+@pytest.mark.parametrize(269+ ("cli_args", "expect"),270+ [271+ pytest.param(272+ ("--option-with-callback", "--force-exit"),273+ ["ExitingOption", "NonExitingOption"],274+ id="natural_order",275+ ),276+ pytest.param(277+ ("--force-exit", "--option-with-callback"),278+ ["ExitingOption"],279+ id="eagerness_precedence",280+ ),281+ ],282+)283+def test_multiple_eager_callbacks(runner, cli_args, expect):284+ """Checks all callbacks are called on exit, even the nasty ones hidden within285+ callbacks.286+287+ Also checks the order in which they're called.288+ """289+ # Keeps track of callback calls.290+ called = []291+292+ class NonExitingOption(Option):293+ def reset_state(self):294+ called.append(self.__class__.__name__)295+296+ def set_state(self, ctx: Context, param: Parameter, value: str) -> str:297+ ctx.call_on_close(self.reset_state)298+ return value299+300+ def __init__(self, *args, **kwargs) -> None:301+ kwargs.setdefault("expose_value", False)302+ kwargs.setdefault("callback", self.set_state)303+ super().__init__(*args, **kwargs)304+305+ class ExitingOption(NonExitingOption):306+ def set_state(self, ctx: Context, param: Parameter, value: str) -> str:307+ value = super().set_state(ctx, param, value)308+ ctx.exit()309+ return value310+311+ @click.command()312+ @click.option("--option-with-callback", is_eager=True, cls=NonExitingOption)313+ @click.option("--force-exit", is_eager=True, cls=ExitingOption)314+ def cli():315+ click.echo("This will never be printed as we forced exit via --force-exit")316+317+ result = runner.invoke(cli, cli_args)318+ assert not result.exception319+ assert not result.output320+321+ assert called == expect322+323+324+def test_no_state_leaks(runner):325+ """Demonstrate state leaks with a specific case of the generic test above.326+327+ Use a logger as a real-world example of a common fixture which, due to its global328+ nature, can leak state if not clean-up properly in a callback.329+ """330+ # Keeps track of callback calls.331+ called = []332+333+ class DebugLoggerOption(Option):334+ """A custom option to set the name of the debug logger."""335+336+ logger_name: str337+ """The ID of the logger to use."""338+339+ def reset_loggers(self):340+ """Forces logger managed by the option to be reset to the default level."""341+ logger = logging.getLogger(self.logger_name)342+ logger.setLevel(logging.NOTSET)343+344+ # Logger has been properly reset to its initial state.345+ assert logger.level == logging.NOTSET346+ assert logger.getEffectiveLevel() == logging.WARNING347+348+ called.append(True)349+350+ def set_level(self, ctx: Context, param: Parameter, value: str) -> None:351+ """Set the logger to DEBUG level."""352+ # Keep the logger name around so we can reset it later when winding down353+ # the option.354+ self.logger_name = value355+356+ # Get the global logger object.357+ logger = logging.getLogger(self.logger_name)358+359+ # Check pre-conditions: new logger is not set, but inherits its level from360+ # default <root> logger. That's the exact same state we are expecting our361+ # logger to be in after being messed with by the CLI.362+ assert logger.level == logging.NOTSET363+ assert logger.getEffectiveLevel() == logging.WARNING364+365+ logger.setLevel(logging.DEBUG)366+ ctx.call_on_close(self.reset_loggers)367+ return value368+369+ def __init__(self, *args, **kwargs) -> None:370+ kwargs.setdefault("callback", self.set_level)371+ super().__init__(*args, **kwargs)372+373+ @click.command()374+ @click.option("--debug-logger-name", is_eager=True, cls=DebugLoggerOption)375+ @help_option()376+ @click.pass_context377+ def messing_with_logger(ctx, debug_logger_name):378+ # Introspect context to make sure logger name are aligned.379+ assert debug_logger_name == ctx.command.params[0].logger_name380+381+ logger = logging.getLogger(debug_logger_name)382+383+ # Logger's level has been properly set to DEBUG by DebugLoggerOption.384+ assert logger.level == logging.DEBUG385+ assert logger.getEffectiveLevel() == logging.DEBUG386+387+ logger.debug("Blah blah blah")388+389+ ctx.exit()390+391+ click.echo("This will never be printed as we exited early")392+393+ # Call the CLI to mess with the custom logger.394+ result = runner.invoke(395+ messing_with_logger, ["--debug-logger-name", "my_logger", "--help"]396+ )397+398+ assert called == [True]399+400+ # Check the custom logger has been reverted to it initial state by the option401+ # callback after being messed with by the CLI.402+ logger = logging.getLogger("my_logger")403+ assert logger.level == logging.NOTSET404+ assert logger.getEffectiveLevel() == logging.WARNING405+406+ assert not result.exception407+ assert result.output.startswith("Usage: messing-with-logger [OPTIONS]")408+409+410 def test_with_resource():411 @contextmanager412 def manager():413 val = [1]132 unmodified linesmodified:CHANGES.rst+3 added
43 unmodified lines44 output` stream to simulate what the user sees in its terminal. Removes45 the ``mix_stderr`` parameter in ``CliRunner``. :issue:`2522` :pr:`2523`46 - ``Option.show_envvar`` now also shows environment variable in error messages.47 :issue:`2695` :pr:`2696`48+- ``Context.close`` will be called on exit. This results in all49+ ``Context.call_on_close`` callbacks and context managers added via50+ ``Context.with_resource`` to be closed on exit as well. :pr:`2680`51 52 53 Version 8.1.854 -------------1116 unmodified lines