Skip to content
Myr

test_context.py

This file

Path

tests/test_context.py

545 lines · 14.0 KiB · Python

Last changed by

Fix closing of callbacks on CLI exit (#2680)Kevin Deldyckebefore adoptionc326df9

History of this file

Take it

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):16    class Foo:17        def __init__(self):18            self.title = "default"1920    pass_foo = click.make_pass_decorator(Foo, ensure=True)2122    @click.group()23    @pass_foo24    def cli(foo):25        pass2627    @cli.command()28    @pass_foo29    def test(foo):30        click.echo(foo.title)3132    result = runner.invoke(cli, ["test"])33    assert not result.exception34    assert result.output == "default\n"353637def test_get_context_objects(runner):38    class Foo:39        def __init__(self):40            self.title = "default"4142    pass_foo = click.make_pass_decorator(Foo, ensure=True)4344    @click.group()45    @click.pass_context46    def cli(ctx):47        ctx.obj = Foo()48        ctx.obj.title = "test"4950    @cli.command()51    @pass_foo52    def test(foo):53        click.echo(foo.title)5455    result = runner.invoke(cli, ["test"])56    assert not result.exception57    assert result.output == "test\n"585960def test_get_context_objects_no_ensuring(runner):61    class Foo:62        def __init__(self):63            self.title = "default"6465    pass_foo = click.make_pass_decorator(Foo)6667    @click.group()68    @click.pass_context69    def cli(ctx):70        ctx.obj = Foo()71        ctx.obj.title = "test"7273    @cli.command()74    @pass_foo75    def test(foo):76        click.echo(foo.title)7778    result = runner.invoke(cli, ["test"])79    assert not result.exception80    assert result.output == "test\n"818283def test_get_context_objects_missing(runner):84    class Foo:85        pass8687    pass_foo = click.make_pass_decorator(Foo)8889    @click.group()90    @click.pass_context91    def cli(ctx):92        pass9394    @cli.command()95    @pass_foo96    def test(foo):97        click.echo(foo.title)9899    result = runner.invoke(cli, ["test"])100    assert result.exception is not None101    assert isinstance(result.exception, RuntimeError)102    assert (103        "Managed to invoke callback without a context object of type"104        " 'Foo' existing" in str(result.exception)105    )106107108def test_multi_enter(runner):109    called = []110111    @click.command()112    @click.pass_context113    def cli(ctx):114        def callback():115            called.append(True)116117        ctx.call_on_close(callback)118119        with ctx:120            pass121        assert not called122123    result = runner.invoke(cli, [])124    assert result.exception is None125    assert called == [True]126127128def test_global_context_object(runner):129    @click.command()130    @click.pass_context131    def cli(ctx):132        assert click.get_current_context() is ctx133        ctx.obj = "FOOBAR"134        assert click.get_current_context().obj == "FOOBAR"135136    assert click.get_current_context(silent=True) is None137    runner.invoke(cli, [], catch_exceptions=False)138    assert click.get_current_context(silent=True) is None139140141def test_context_meta(runner):142    LANG_KEY = f"{__name__}.lang"143144    def set_language(value):145        click.get_current_context().meta[LANG_KEY] = value146147    def get_language():148        return click.get_current_context().meta.get(LANG_KEY, "en_US")149150    @click.command()151    @click.pass_context152    def cli(ctx):153        assert get_language() == "en_US"154        set_language("de_DE")155        assert get_language() == "de_DE"156157    runner.invoke(cli, [], catch_exceptions=False)158159160def test_make_pass_meta_decorator(runner):161    @click.group()162    @click.pass_context163    def cli(ctx):164        ctx.meta["value"] = "good"165166    @cli.command()167    @pass_meta_key("value")168    def show(value):169        return value170171    result = runner.invoke(cli, ["show"], standalone_mode=False)172    assert result.return_value == "good"173174175def test_make_pass_meta_decorator_doc():176    pass_value = pass_meta_key("value")177    assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__178    pass_value = pass_meta_key("value", doc_description="the test value")179    assert "passes the test value" in pass_value.__doc__180181182def test_context_pushing():183    rv = []184185    @click.command()186    def cli():187        pass188189    ctx = click.Context(cli)190191    @ctx.call_on_close192    def test_callback():193        rv.append(42)194195    with ctx.scope(cleanup=False):196        # Internal197        assert ctx._depth == 2198199    assert rv == []200201    with ctx.scope():202        # Internal203        assert ctx._depth == 1204205    assert rv == [42]206207208def test_pass_obj(runner):209    @click.group()210    @click.pass_context211    def cli(ctx):212        ctx.obj = "test"213214    @cli.command()215    @click.pass_obj216    def test(obj):217        click.echo(obj)218219    result = runner.invoke(cli, ["test"])220    assert not result.exception221    assert result.output == "test\n"222223224def test_close_before_pop(runner):225    called = []226227    @click.command()228    @click.pass_context229    def cli(ctx):230        ctx.obj = "test"231232        @ctx.call_on_close233        def foo():234            assert click.get_current_context().obj == "test"235            called.append(True)236237        click.echo("aha!")238239    result = runner.invoke(cli, [])240    assert not result.exception241    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]414        yield val415        val[0] = 0416417    ctx = click.Context(click.Command("test"))418419    with ctx.scope():420        rv = ctx.with_resource(manager())421        assert rv[0] == 1422423    assert rv == [0]424425426def test_make_pass_decorator_args(runner):427    """428    Test to check that make_pass_decorator doesn't consume arguments based on429    invocation order.430    """431432    class Foo:433        title = "foocmd"434435    pass_foo = click.make_pass_decorator(Foo)436437    @click.group()438    @click.pass_context439    def cli(ctx):440        ctx.obj = Foo()441442    @cli.command()443    @click.pass_context444    @pass_foo445    def test1(foo, ctx):446        click.echo(foo.title)447448    @cli.command()449    @pass_foo450    @click.pass_context451    def test2(ctx, foo):452        click.echo(foo.title)453454    result = runner.invoke(cli, ["test1"])455    assert not result.exception456    assert result.output == "foocmd\n"457458    result = runner.invoke(cli, ["test2"])459    assert not result.exception460    assert result.output == "foocmd\n"461462463def test_propagate_show_default_setting(runner):464    """A context's ``show_default`` setting defaults to the value from465    the parent context.466    """467    group = click.Group(468        commands={469            "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]),470        },471        context_settings={"show_default": True},472    )473    result = runner.invoke(group, ["sub", "--help"])474    assert "[default: a]" in result.output475476477def test_exit_not_standalone():478    @click.command()479    @click.pass_context480    def cli(ctx):481        ctx.exit(1)482483    assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1484485    @click.command()486    @click.pass_context487    def cli(ctx):488        ctx.exit(0)489490    assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0491492493@pytest.mark.parametrize(494    ("option_args", "invoke_args", "expect"),495    [496        pytest.param({}, {}, ParameterSource.DEFAULT, id="default"),497        pytest.param(498            {},499            {"default_map": {"option": 1}},500            ParameterSource.DEFAULT_MAP,501            id="default_map",502        ),503        pytest.param(504            {},505            {"args": ["-o", "1"]},506            ParameterSource.COMMANDLINE,507            id="commandline short",508        ),509        pytest.param(510            {},511            {"args": ["--option", "1"]},512            ParameterSource.COMMANDLINE,513            id="commandline long",514        ),515        pytest.param(516            {},517            {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}},518            ParameterSource.ENVIRONMENT,519            id="environment auto",520        ),521        pytest.param(522            {"envvar": "NAME"},523            {"env": {"NAME": "1"}},524            ParameterSource.ENVIRONMENT,525            id="environment manual",526        ),527    ],528)529def test_parameter_source(runner, option_args, invoke_args, expect):530    @click.command()531    @click.pass_context532    @click.option("-o", "--option", default=1, **option_args)533    def cli(ctx, option):534        return ctx.get_parameter_source("option")535536    rv = runner.invoke(cli, standalone_mode=False, **invoke_args)537    assert rv.return_value == expect538539540def test_propagate_opt_prefixes():541    parent = click.Context(click.Command("test"))542    parent._opt_prefixes = {"-", "--", "!"}543    ctx = click.Context(click.Command("test2"), parent=parent)544545    assert ctx._opt_prefixes == {"-", "--", "!"}