Skip to content
Myr

test_context.py

This file

Path

tests/test_context.py

672 lines · 17.8 KiB · Python

Last changed by

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

History of this file

Take it

1import logging2from contextlib import AbstractContextManager3from contextlib import contextmanager4from types import TracebackType56import pytest78import click9from click import Context10from click import Option11from click import Parameter12from click.core import ParameterSource13from click.decorators import help_option14from click.decorators import pass_meta_key151617def test_ensure_context_objects(runner):18    class Foo:19        def __init__(self):20            self.title = "default"2122    pass_foo = click.make_pass_decorator(Foo, ensure=True)2324    @click.group()25    @pass_foo26    def cli(foo):27        pass2829    @cli.command()30    @pass_foo31    def test(foo):32        click.echo(foo.title)3334    result = runner.invoke(cli, ["test"])35    assert not result.exception36    assert result.output == "default\n"373839def test_get_context_objects(runner):40    class Foo:41        def __init__(self):42            self.title = "default"4344    pass_foo = click.make_pass_decorator(Foo, ensure=True)4546    @click.group()47    @click.pass_context48    def cli(ctx):49        ctx.obj = Foo()50        ctx.obj.title = "test"5152    @cli.command()53    @pass_foo54    def test(foo):55        click.echo(foo.title)5657    result = runner.invoke(cli, ["test"])58    assert not result.exception59    assert result.output == "test\n"606162def test_get_context_objects_no_ensuring(runner):63    class Foo:64        def __init__(self):65            self.title = "default"6667    pass_foo = click.make_pass_decorator(Foo)6869    @click.group()70    @click.pass_context71    def cli(ctx):72        ctx.obj = Foo()73        ctx.obj.title = "test"7475    @cli.command()76    @pass_foo77    def test(foo):78        click.echo(foo.title)7980    result = runner.invoke(cli, ["test"])81    assert not result.exception82    assert result.output == "test\n"838485def test_get_context_objects_missing(runner):86    class Foo:87        pass8889    pass_foo = click.make_pass_decorator(Foo)9091    @click.group()92    @click.pass_context93    def cli(ctx):94        pass9596    @cli.command()97    @pass_foo98    def test(foo):99        click.echo(foo.title)100101    result = runner.invoke(cli, ["test"])102    assert result.exception is not None103    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    )108109110def test_multi_enter(runner):111    called = []112113    @click.command()114    @click.pass_context115    def cli(ctx):116        def callback():117            called.append(True)118119        ctx.call_on_close(callback)120121        with ctx:122            pass123        assert not called124125    result = runner.invoke(cli, [])126    assert result.exception is None127    assert called == [True]128129130def test_global_context_object(runner):131    @click.command()132    @click.pass_context133    def cli(ctx):134        assert click.get_current_context() is ctx135        ctx.obj = "FOOBAR"136        assert click.get_current_context().obj == "FOOBAR"137138    assert click.get_current_context(silent=True) is None139    runner.invoke(cli, [], catch_exceptions=False)140    assert click.get_current_context(silent=True) is None141142143def test_context_meta(runner):144    LANG_KEY = f"{__name__}.lang"145146    def set_language(value):147        click.get_current_context().meta[LANG_KEY] = value148149    def get_language():150        return click.get_current_context().meta.get(LANG_KEY, "en_US")151152    @click.command()153    @click.pass_context154    def cli(ctx):155        assert get_language() == "en_US"156        set_language("de_DE")157        assert get_language() == "de_DE"158159    runner.invoke(cli, [], catch_exceptions=False)160161162def test_make_pass_meta_decorator(runner):163    @click.group()164    @click.pass_context165    def cli(ctx):166        ctx.meta["value"] = "good"167168    @cli.command()169    @pass_meta_key("value")170    def show(value):171        return value172173    result = runner.invoke(cli, ["show"], standalone_mode=False)174    assert result.return_value == "good"175176177def 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__182183184def test_context_pushing():185    rv = []186187    @click.command()188    def cli():189        pass190191    ctx = click.Context(cli)192193    @ctx.call_on_close194    def test_callback():195        rv.append(42)196197    with ctx.scope(cleanup=False):198        # Internal199        assert ctx._depth == 2200201    assert rv == []202203    with ctx.scope():204        # Internal205        assert ctx._depth == 1206207    assert rv == [42]208209210def test_pass_obj(runner):211    @click.group()212    @click.pass_context213    def cli(ctx):214        ctx.obj = "test"215216    @cli.command()217    @click.pass_obj218    def test(obj):219        click.echo(obj)220221    result = runner.invoke(cli, ["test"])222    assert not result.exception223    assert result.output == "test\n"224225226def test_close_before_pop(runner):227    called = []228229    @click.command()230    @click.pass_context231    def cli(ctx):232        ctx.obj = "test"233234        @ctx.call_on_close235        def foo():236            assert click.get_current_context().obj == "test"237            called.append(True)238239        click.echo("aha!")240241    result = runner.invoke(cli, [])242    assert not result.exception243    assert result.output == "aha!\n"244    assert called == [True]245246247def test_close_before_exit(runner):248    called = []249250    @click.command()251    @click.pass_context252    def cli(ctx):253        ctx.obj = "test"254255        @ctx.call_on_close256        def foo():257            assert click.get_current_context().obj == "test"258            called.append(True)259260        ctx.exit()261262        click.echo("aha!")263264    result = runner.invoke(cli, [])265    assert not result.exception266    assert not result.output267    assert called == [True]268269270@pytest.mark.parametrize(271    ("cli_args", "expect"),272    [273        pytest.param(274            ("--option-with-callback", "--force-exit"),275            ["ExitingOption", "NonExitingOption"],276            id="natural_order",277        ),278        pytest.param(279            ("--force-exit", "--option-with-callback"),280            ["ExitingOption"],281            id="eagerness_precedence",282        ),283    ],284)285def test_multiple_eager_callbacks(runner, cli_args, expect):286    """Checks all callbacks are called on exit, even the nasty ones hidden within287    callbacks.288289    Also checks the order in which they're called.290    """291    # Keeps track of callback calls.292    called = []293294    class NonExitingOption(Option):295        def reset_state(self):296            called.append(self.__class__.__name__)297298        def set_state(self, ctx: Context, param: Parameter, value: str) -> str:299            ctx.call_on_close(self.reset_state)300            return value301302        def __init__(self, *args, **kwargs) -> None:303            kwargs.setdefault("expose_value", False)304            kwargs.setdefault("callback", self.set_state)305            super().__init__(*args, **kwargs)306307    class ExitingOption(NonExitingOption):308        def set_state(self, ctx: Context, param: Parameter, value: str) -> str:309            value = super().set_state(ctx, param, value)310            ctx.exit()311            return value312313    @click.command()314    @click.option("--option-with-callback", is_eager=True, cls=NonExitingOption)315    @click.option("--force-exit", is_eager=True, cls=ExitingOption)316    def cli():317        click.echo("This will never be printed as we forced exit via --force-exit")318319    result = runner.invoke(cli, cli_args)320    assert not result.exception321    assert not result.output322323    assert called == expect324325326def test_no_state_leaks(runner):327    """Demonstrate state leaks with a specific case of the generic test above.328329    Use a logger as a real-world example of a common fixture which, due to its global330    nature, can leak state if not clean-up properly in a callback.331    """332    # Keeps track of callback calls.333    called = []334335    class DebugLoggerOption(Option):336        """A custom option to set the name of the debug logger."""337338        logger_name: str339        """The ID of the logger to use."""340341        def reset_loggers(self):342            """Forces logger managed by the option to be reset to the default level."""343            logger = logging.getLogger(self.logger_name)344            logger.setLevel(logging.NOTSET)345346            # Logger has been properly reset to its initial state.347            assert logger.level == logging.NOTSET348            assert logger.getEffectiveLevel() == logging.WARNING349350            called.append(True)351352        def set_level(self, ctx: Context, param: Parameter, value: str) -> None:353            """Set the logger to DEBUG level."""354            # Keep the logger name around so we can reset it later when winding down355            # the option.356            self.logger_name = value357358            # Get the global logger object.359            logger = logging.getLogger(self.logger_name)360361            # Check pre-conditions: new logger is not set, but inherits its level from362            # default <root> logger. That's the exact same state we are expecting our363            # logger to be in after being messed with by the CLI.364            assert logger.level == logging.NOTSET365            assert logger.getEffectiveLevel() == logging.WARNING366367            logger.setLevel(logging.DEBUG)368            ctx.call_on_close(self.reset_loggers)369            return value370371        def __init__(self, *args, **kwargs) -> None:372            kwargs.setdefault("callback", self.set_level)373            super().__init__(*args, **kwargs)374375    @click.command()376    @click.option("--debug-logger-name", is_eager=True, cls=DebugLoggerOption)377    @help_option()378    @click.pass_context379    def messing_with_logger(ctx, debug_logger_name):380        # Introspect context to make sure logger name are aligned.381        assert debug_logger_name == ctx.command.params[0].logger_name382383        logger = logging.getLogger(debug_logger_name)384385        # Logger's level has been properly set to DEBUG by DebugLoggerOption.386        assert logger.level == logging.DEBUG387        assert logger.getEffectiveLevel() == logging.DEBUG388389        logger.debug("Blah blah blah")390391        ctx.exit()392393        click.echo("This will never be printed as we exited early")394395    # Call the CLI to mess with the custom logger.396    result = runner.invoke(397        messing_with_logger, ["--debug-logger-name", "my_logger", "--help"]398    )399400    assert called == [True]401402    # Check the custom logger has been reverted to it initial state by the option403    # callback after being messed with by the CLI.404    logger = logging.getLogger("my_logger")405    assert logger.level == logging.NOTSET406    assert logger.getEffectiveLevel() == logging.WARNING407408    assert not result.exception409    assert result.output.startswith("Usage: messing-with-logger [OPTIONS]")410411412def test_with_resource():413    @contextmanager414    def manager():415        val = [1]416        yield val417        val[0] = 0418419    ctx = click.Context(click.Command("test"))420421    with ctx.scope():422        rv = ctx.with_resource(manager())423        assert rv[0] == 1424425    assert rv == [0]426427428def test_with_resource_exception() -> None:429    class TestContext(AbstractContextManager[list[int]]):430        _handle_exception: bool431        _base_val: int432        val: list[int]433434        def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:435            self._handle_exception = handle_exception436            self._base_val = base_val437438        def __enter__(self) -> list[int]:439            self.val = [self._base_val]440            return self.val441442        def __exit__(443            self,444            exc_type: type[BaseException] | None,445            exc_value: BaseException | None,446            traceback: TracebackType | None,447        ) -> bool | None:448            if not exc_type:449                self.val[0] = self._base_val - 1450                return None451452            self.val[0] = self._base_val + 1453            return self._handle_exception454455    class TestException(Exception):456        pass457458    ctx = click.Context(click.Command("test"))459460    base_val = 1461462    with ctx.scope():463        rv = ctx.with_resource(TestContext(base_val=base_val))464        assert rv[0] == base_val465466    assert rv == [base_val - 1]467468    with ctx.scope():469        rv = ctx.with_resource(TestContext(base_val=base_val))470        raise TestException()471472    assert rv == [base_val + 1]473474    with pytest.raises(TestException):475        with ctx.scope():476            rv = ctx.with_resource(477                TestContext(base_val=base_val, handle_exception=False)478            )479            raise TestException()480481482def test_with_resource_nested_exception() -> None:483    class TestContext(AbstractContextManager[list[int]]):484        _handle_exception: bool485        _base_val: int486        val: list[int]487488        def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:489            self._handle_exception = handle_exception490            self._base_val = base_val491492        def __enter__(self) -> list[int]:493            self.val = [self._base_val]494            return self.val495496        def __exit__(497            self,498            exc_type: type[BaseException] | None,499            exc_value: BaseException | None,500            traceback: TracebackType | None,501        ) -> bool | None:502            if not exc_type:503                self.val[0] = self._base_val - 1504                return None505506            self.val[0] = self._base_val + 1507            return self._handle_exception508509    class TestException(Exception):510        pass511512    ctx = click.Context(click.Command("test"))513    base_val = 1514    base_val_nested = 11515516    with ctx.scope():517        rv = ctx.with_resource(TestContext(base_val=base_val))518        rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))519        assert rv[0] == base_val520        assert rv_nested[0] == base_val_nested521522    assert rv == [base_val - 1]523    assert rv_nested == [base_val_nested - 1]524525    with ctx.scope():526        rv = ctx.with_resource(TestContext(base_val=base_val))527        rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))528        raise TestException()529530    # If one of the context "eats" the exceptions they will not be forwarded to other531    # parts. This is due to how ExitStack unwinding works532    assert rv_nested == [base_val_nested + 1]533    assert rv == [base_val - 1]534535    with ctx.scope():536        rv = ctx.with_resource(TestContext(base_val=base_val))537        rv_nested = ctx.with_resource(538            TestContext(base_val=base_val_nested, handle_exception=False)539        )540        raise TestException()541542    assert rv_nested == [base_val_nested + 1]543    assert rv == [base_val + 1]544545    with pytest.raises(TestException):546        rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False))547        rv_nested = ctx.with_resource(548            TestContext(base_val=base_val_nested, handle_exception=False)549        )550        raise TestException()551552553def test_make_pass_decorator_args(runner):554    """555    Test to check that make_pass_decorator doesn't consume arguments based on556    invocation order.557    """558559    class Foo:560        title = "foocmd"561562    pass_foo = click.make_pass_decorator(Foo)563564    @click.group()565    @click.pass_context566    def cli(ctx):567        ctx.obj = Foo()568569    @cli.command()570    @click.pass_context571    @pass_foo572    def test1(foo, ctx):573        click.echo(foo.title)574575    @cli.command()576    @pass_foo577    @click.pass_context578    def test2(ctx, foo):579        click.echo(foo.title)580581    result = runner.invoke(cli, ["test1"])582    assert not result.exception583    assert result.output == "foocmd\n"584585    result = runner.invoke(cli, ["test2"])586    assert not result.exception587    assert result.output == "foocmd\n"588589590def test_propagate_show_default_setting(runner):591    """A context's ``show_default`` setting defaults to the value from592    the parent context.593    """594    group = click.Group(595        commands={596            "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]),597        },598        context_settings={"show_default": True},599    )600    result = runner.invoke(group, ["sub", "--help"])601    assert "[default: a]" in result.output602603604def test_exit_not_standalone():605    @click.command()606    @click.pass_context607    def cli(ctx):608        ctx.exit(1)609610    assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1611612    @click.command()613    @click.pass_context614    def cli(ctx):615        ctx.exit(0)616617    assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0618619620@pytest.mark.parametrize(621    ("option_args", "invoke_args", "expect"),622    [623        pytest.param({}, {}, ParameterSource.DEFAULT, id="default"),624        pytest.param(625            {},626            {"default_map": {"option": 1}},627            ParameterSource.DEFAULT_MAP,628            id="default_map",629        ),630        pytest.param(631            {},632            {"args": ["-o", "1"]},633            ParameterSource.COMMANDLINE,634            id="commandline short",635        ),636        pytest.param(637            {},638            {"args": ["--option", "1"]},639            ParameterSource.COMMANDLINE,640            id="commandline long",641        ),642        pytest.param(643            {},644            {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}},645            ParameterSource.ENVIRONMENT,646            id="environment auto",647        ),648        pytest.param(649            {"envvar": "NAME"},650            {"env": {"NAME": "1"}},651            ParameterSource.ENVIRONMENT,652            id="environment manual",653        ),654    ],655)656def test_parameter_source(runner, option_args, invoke_args, expect):657    @click.command()658    @click.pass_context659    @click.option("-o", "--option", default=1, **option_args)660    def cli(ctx, option):661        return ctx.get_parameter_source("option")662663    rv = runner.invoke(cli, standalone_mode=False, **invoke_args)664    assert rv.return_value == expect665666667def test_propagate_opt_prefixes():668    parent = click.Context(click.Command("test"))669    parent._opt_prefixes = {"-", "--", "!"}670    ctx = click.Context(click.Command("test2"), parent=parent)671672    assert ctx._opt_prefixes == {"-", "--", "!"}