Skip to content
Myr

test_context.py

This file

Path

tests/test_context.py

782 lines · 22.5 KiB · Python

Last changed by

Provide altered context to callbacks to hide `UNSET` values as `None` (#3137)Rowlando13before adoptionb91bb95

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_hiding_of_unset_sentinel_in_callbacks():185    """Fix: https://github.com/pallets/click/issues/3136"""186187    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 ctx190        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}")193194        click.echo(f"callback.param: {param!r}")195        click.echo(f"callback.value: {value!r}")196197        return "hard-coded"198199    class ParameterInternalCheck(Option):200        """An option that checks internal state during processing."""201202        def process_value(self, ctx, value):203            """Check that UNSET values are hidden as None in ctx.params within the204            callback, and then properly restored afterwards.205            """206            assert click.get_current_context() is ctx207            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}")210211            value = super().process_value(ctx, value)212213            assert click.get_current_context() is ctx214            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}")217218            return value219220    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 ctx223        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}")226227        click.echo(f"before_change.param: {param!r}")228        click.echo(f"before_change.value: {value!r}")229230        ctx.params["my_arg"] = "changed"231        # Reset to None parameters that where not UNSET to see they are not forced back232        # to UNSET.233        ctx.params["my_callback"] = None234235        return value236237    @click.command238    @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_params244    )245    @click.pass_context246    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}")252253    runner = click.testing.CliRunner()254    result = runner.invoke(cli)255256    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.stderr290    assert not result.exception291    assert result.exit_code == 0292293294def test_context_pushing():295    rv = []296297    @click.command()298    def cli():299        pass300301    ctx = click.Context(cli)302303    @ctx.call_on_close304    def test_callback():305        rv.append(42)306307    with ctx.scope(cleanup=False):308        # Internal309        assert ctx._depth == 2310311    assert rv == []312313    with ctx.scope():314        # Internal315        assert ctx._depth == 1316317    assert rv == [42]318319320def test_pass_obj(runner):321    @click.group()322    @click.pass_context323    def cli(ctx):324        ctx.obj = "test"325326    @cli.command()327    @click.pass_obj328    def test(obj):329        click.echo(obj)330331    result = runner.invoke(cli, ["test"])332    assert not result.exception333    assert result.output == "test\n"334335336def test_close_before_pop(runner):337    called = []338339    @click.command()340    @click.pass_context341    def cli(ctx):342        ctx.obj = "test"343344        @ctx.call_on_close345        def foo():346            assert click.get_current_context().obj == "test"347            called.append(True)348349        click.echo("aha!")350351    result = runner.invoke(cli, [])352    assert not result.exception353    assert result.output == "aha!\n"354    assert called == [True]355356357def test_close_before_exit(runner):358    called = []359360    @click.command()361    @click.pass_context362    def cli(ctx):363        ctx.obj = "test"364365        @ctx.call_on_close366        def foo():367            assert click.get_current_context().obj == "test"368            called.append(True)369370        ctx.exit()371372        click.echo("aha!")373374    result = runner.invoke(cli, [])375    assert not result.exception376    assert not result.output377    assert called == [True]378379380@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)395def test_multiple_eager_callbacks(runner, cli_args, expect):396    """Checks all callbacks are called on exit, even the nasty ones hidden within397    callbacks.398399    Also checks the order in which they're called.400    """401    # Keeps track of callback calls.402    called = []403404    class NonExitingOption(Option):405        def reset_state(self):406            called.append(self.__class__.__name__)407408        def set_state(self, ctx: Context, param: Parameter, value: str) -> str:409            ctx.call_on_close(self.reset_state)410            return value411412        def __init__(self, *args, **kwargs) -> None:413            kwargs.setdefault("expose_value", False)414            kwargs.setdefault("callback", self.set_state)415            super().__init__(*args, **kwargs)416417    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 value422423    @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")428429    result = runner.invoke(cli, cli_args)430    assert not result.exception431    assert not result.output432433    assert called == expect434435436def test_no_state_leaks(runner):437    """Demonstrate state leaks with a specific case of the generic test above.438439    Use a logger as a real-world example of a common fixture which, due to its global440    nature, can leak state if not clean-up properly in a callback.441    """442    # Keeps track of callback calls.443    called = []444445    class DebugLoggerOption(Option):446        """A custom option to set the name of the debug logger."""447448        logger_name: str449        """The ID of the logger to use."""450451        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)455456            # Logger has been properly reset to its initial state.457            assert logger.level == logging.NOTSET458            assert logger.getEffectiveLevel() == logging.WARNING459460            called.append(True)461462        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 down465            # the option.466            self.logger_name = value467468            # Get the global logger object.469            logger = logging.getLogger(self.logger_name)470471            # Check pre-conditions: new logger is not set, but inherits its level from472            # default <root> logger. That's the exact same state we are expecting our473            # logger to be in after being messed with by the CLI.474            assert logger.level == logging.NOTSET475            assert logger.getEffectiveLevel() == logging.WARNING476477            logger.setLevel(logging.DEBUG)478            ctx.call_on_close(self.reset_loggers)479            return value480481        def __init__(self, *args, **kwargs) -> None:482            kwargs.setdefault("callback", self.set_level)483            super().__init__(*args, **kwargs)484485    @click.command()486    @click.option("--debug-logger-name", is_eager=True, cls=DebugLoggerOption)487    @help_option()488    @click.pass_context489    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_name492493        logger = logging.getLogger(debug_logger_name)494495        # Logger's level has been properly set to DEBUG by DebugLoggerOption.496        assert logger.level == logging.DEBUG497        assert logger.getEffectiveLevel() == logging.DEBUG498499        logger.debug("Blah blah blah")500501        ctx.exit()502503        click.echo("This will never be printed as we exited early")504505    # Call the CLI to mess with the custom logger.506    result = runner.invoke(507        messing_with_logger, ["--debug-logger-name", "my_logger", "--help"]508    )509510    assert called == [True]511512    # Check the custom logger has been reverted to it initial state by the option513    # callback after being messed with by the CLI.514    logger = logging.getLogger("my_logger")515    assert logger.level == logging.NOTSET516    assert logger.getEffectiveLevel() == logging.WARNING517518    assert not result.exception519    assert result.output.startswith("Usage: messing-with-logger [OPTIONS]")520521522def test_with_resource():523    @contextmanager524    def manager():525        val = [1]526        yield val527        val[0] = 0528529    ctx = click.Context(click.Command("test"))530531    with ctx.scope():532        rv = ctx.with_resource(manager())533        assert rv[0] == 1534535    assert rv == [0]536537538def test_with_resource_exception() -> None:539    class TestContext(AbstractContextManager[list[int]]):540        _handle_exception: bool541        _base_val: int542        val: list[int]543544        def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:545            self._handle_exception = handle_exception546            self._base_val = base_val547548        def __enter__(self) -> list[int]:549            self.val = [self._base_val]550            return self.val551552        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 - 1560                return None561562            self.val[0] = self._base_val + 1563            return self._handle_exception564565    class TestException(Exception):566        pass567568    ctx = click.Context(click.Command("test"))569570    base_val = 1571572    with ctx.scope():573        rv = ctx.with_resource(TestContext(base_val=base_val))574        assert rv[0] == base_val575576    assert rv == [base_val - 1]577578    with ctx.scope():579        rv = ctx.with_resource(TestContext(base_val=base_val))580        raise TestException()581582    assert rv == [base_val + 1]583584    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()590591592def test_with_resource_nested_exception() -> None:593    class TestContext(AbstractContextManager[list[int]]):594        _handle_exception: bool595        _base_val: int596        val: list[int]597598        def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:599            self._handle_exception = handle_exception600            self._base_val = base_val601602        def __enter__(self) -> list[int]:603            self.val = [self._base_val]604            return self.val605606        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 - 1614                return None615616            self.val[0] = self._base_val + 1617            return self._handle_exception618619    class TestException(Exception):620        pass621622    ctx = click.Context(click.Command("test"))623    base_val = 1624    base_val_nested = 11625626    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_val630        assert rv_nested[0] == base_val_nested631632    assert rv == [base_val - 1]633    assert rv_nested == [base_val_nested - 1]634635    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()639640    # If one of the context "eats" the exceptions they will not be forwarded to other641    # parts. This is due to how ExitStack unwinding works642    assert rv_nested == [base_val_nested + 1]643    assert rv == [base_val - 1]644645    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()651652    assert rv_nested == [base_val_nested + 1]653    assert rv == [base_val + 1]654655    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()661662663def test_make_pass_decorator_args(runner):664    """665    Test to check that make_pass_decorator doesn't consume arguments based on666    invocation order.667    """668669    class Foo:670        title = "foocmd"671672    pass_foo = click.make_pass_decorator(Foo)673674    @click.group()675    @click.pass_context676    def cli(ctx):677        ctx.obj = Foo()678679    @cli.command()680    @click.pass_context681    @pass_foo682    def test1(foo, ctx):683        click.echo(foo.title)684685    @cli.command()686    @pass_foo687    @click.pass_context688    def test2(ctx, foo):689        click.echo(foo.title)690691    result = runner.invoke(cli, ["test1"])692    assert not result.exception693    assert result.output == "foocmd\n"694695    result = runner.invoke(cli, ["test2"])696    assert not result.exception697    assert result.output == "foocmd\n"698699700def test_propagate_show_default_setting(runner):701    """A context's ``show_default`` setting defaults to the value from702    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.output712713714def test_exit_not_standalone():715    @click.command()716    @click.pass_context717    def cli(ctx):718        ctx.exit(1)719720    assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1721722    @click.command()723    @click.pass_context724    def cli(ctx):725        ctx.exit(0)726727    assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0728729730@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)766def test_parameter_source(runner, option_args, invoke_args, expect):767    @click.command()768    @click.pass_context769    @click.option("-o", "--option", default=1, **option_args)770    def cli(ctx, option):771        return ctx.get_parameter_source("option")772773    rv = runner.invoke(cli, standalone_mode=False, **invoke_args)774    assert rv.return_value == expect775776777def test_propagate_opt_prefixes():778    parent = click.Context(click.Command("test"))779    parent._opt_prefixes = {"-", "--", "!"}780    ctx = click.Context(click.Command("test2"), parent=parent)781782    assert ctx._opt_prefixes == {"-", "--", "!"}