Skip to content
Myr

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

4 files+185 added−1 removed

modified:docs/advanced.rst+5 added
492 unmodified lines
493 def close_db():494 db.record_use()495 db.save()496 db.close()497498499.. 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 lines
698 """Aborts the script."""699 raise Abort()700701 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.703704 .. 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)710711 def get_usage(self) -> str:712 """Helper method to get formatted usage string for the current
2300 unmodified lines
modified:tests/test_context.py+170 added
1import logging2from contextlib import contextmanager34import pytest56import click7from click import Context8from click import Option9from click import Parameter10from click.core import ParameterSource11from click.decorators import help_option12from click.decorators import pass_meta_key131415def test_ensure_context_objects(runner):
225 unmodified lines
241 assert result.output == "aha!\n"242 assert called == [True]243244245def test_close_before_exit(runner):246 called = []247248 @click.command()249 @click.pass_context250 def cli(ctx):251 ctx.obj = "test"252253 @ctx.call_on_close254 def foo():255 assert click.get_current_context().obj == "test"256 called.append(True)257258 ctx.exit()259260 click.echo("aha!")261262 result = runner.invoke(cli, [])263 assert not result.exception264 assert not result.output265 assert called == [True]266267268@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)283def test_multiple_eager_callbacks(runner, cli_args, expect):284 """Checks all callbacks are called on exit, even the nasty ones hidden within285 callbacks.286287 Also checks the order in which they're called.288 """289 # Keeps track of callback calls.290 called = []291292 class NonExitingOption(Option):293 def reset_state(self):294 called.append(self.__class__.__name__)295296 def set_state(self, ctx: Context, param: Parameter, value: str) -> str:297 ctx.call_on_close(self.reset_state)298 return value299300 def __init__(self, *args, **kwargs) -> None:301 kwargs.setdefault("expose_value", False)302 kwargs.setdefault("callback", self.set_state)303 super().__init__(*args, **kwargs)304305 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 value310311 @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")316317 result = runner.invoke(cli, cli_args)318 assert not result.exception319 assert not result.output320321 assert called == expect322323324def test_no_state_leaks(runner):325 """Demonstrate state leaks with a specific case of the generic test above.326327 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 = []332333 class DebugLoggerOption(Option):334 """A custom option to set the name of the debug logger."""335336 logger_name: str337 """The ID of the logger to use."""338339 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)343344 # Logger has been properly reset to its initial state.345 assert logger.level == logging.NOTSET346 assert logger.getEffectiveLevel() == logging.WARNING347348 called.append(True)349350 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 = value355356 # Get the global logger object.357 logger = logging.getLogger(self.logger_name)358359 # 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.WARNING364365 logger.setLevel(logging.DEBUG)366 ctx.call_on_close(self.reset_loggers)367 return value368369 def __init__(self, *args, **kwargs) -> None:370 kwargs.setdefault("callback", self.set_level)371 super().__init__(*args, **kwargs)372373 @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_name380381 logger = logging.getLogger(debug_logger_name)382383 # Logger's level has been properly set to DEBUG by DebugLoggerOption.384 assert logger.level == logging.DEBUG385 assert logger.getEffectiveLevel() == logging.DEBUG386387 logger.debug("Blah blah blah")388389 ctx.exit()390391 click.echo("This will never be printed as we exited early")392393 # Call the CLI to mess with the custom logger.394 result = runner.invoke(395 messing_with_logger, ["--debug-logger-name", "my_logger", "--help"]396 )397398 assert called == [True]399400 # 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.WARNING405406 assert not result.exception407 assert result.output.startswith("Usage: messing-with-logger [OPTIONS]")408409410def test_with_resource():411 @contextmanager412 def manager():413 val = [1]
132 unmodified lines
modified:CHANGES.rst+3 added
43 unmodified lines
44 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`515253Version 8.1.854-------------
1116 unmodified lines