test_context.py
This file
Path
tests/test_context.py
375 lines · 8.5 KiB · Python
Last changed by
Merge pull request #2041 from spanglerco/shell-completion-option-valuesDavid Lordbefore adoptionef11be6
History of this fileTake it
The walk stopped after 200 commits: lines older than ca1cefb point at it.
Merge pull request #1748 from pallets/dependabot/pip/importlib-metadata-3.3.0dependabot-preview[bot]before adoptionca1cefb
lines 1–6why, one step back1from contextlib import contextmanager23import pytest45import click6from click.core import ParameterSourceMerge pull request #1807 from pallets/pass-metaDavid Lordbefore adoptiona6fea31
line 7why, one step back7from click.decorators import pass_meta_keyMerge pull request #1748 from pallets/dependabot/pip/importlib-metadata-3.3.0dependabot-preview[bot]before adoptionca1cefb
lines 8–152why, one step back8910def test_ensure_context_objects(runner):11 class Foo:12 def __init__(self):13 self.title = "default"1415 pass_foo = click.make_pass_decorator(Foo, ensure=True)1617 @click.group()18 @pass_foo19 def cli(foo):20 pass2122 @cli.command()23 @pass_foo24 def test(foo):25 click.echo(foo.title)2627 result = runner.invoke(cli, ["test"])28 assert not result.exception29 assert result.output == "default\n"303132def test_get_context_objects(runner):33 class Foo:34 def __init__(self):35 self.title = "default"3637 pass_foo = click.make_pass_decorator(Foo, ensure=True)3839 @click.group()40 @click.pass_context41 def cli(ctx):42 ctx.obj = Foo()43 ctx.obj.title = "test"4445 @cli.command()46 @pass_foo47 def test(foo):48 click.echo(foo.title)4950 result = runner.invoke(cli, ["test"])51 assert not result.exception52 assert result.output == "test\n"535455def test_get_context_objects_no_ensuring(runner):56 class Foo:57 def __init__(self):58 self.title = "default"5960 pass_foo = click.make_pass_decorator(Foo)6162 @click.group()63 @click.pass_context64 def cli(ctx):65 ctx.obj = Foo()66 ctx.obj.title = "test"6768 @cli.command()69 @pass_foo70 def test(foo):71 click.echo(foo.title)7273 result = runner.invoke(cli, ["test"])74 assert not result.exception75 assert result.output == "test\n"767778def test_get_context_objects_missing(runner):79 class Foo:80 pass8182 pass_foo = click.make_pass_decorator(Foo)8384 @click.group()85 @click.pass_context86 def cli(ctx):87 pass8889 @cli.command()90 @pass_foo91 def test(foo):92 click.echo(foo.title)9394 result = runner.invoke(cli, ["test"])95 assert result.exception is not None96 assert isinstance(result.exception, RuntimeError)97 assert (98 "Managed to invoke callback without a context object of type"99 " 'Foo' existing" in str(result.exception)100 )101102103def test_multi_enter(runner):104 called = []105106 @click.command()107 @click.pass_context108 def cli(ctx):109 def callback():110 called.append(True)111112 ctx.call_on_close(callback)113114 with ctx:115 pass116 assert not called117118 result = runner.invoke(cli, [])119 assert result.exception is None120 assert called == [True]121122123def test_global_context_object(runner):124 @click.command()125 @click.pass_context126 def cli(ctx):127 assert click.get_current_context() is ctx128 ctx.obj = "FOOBAR"129 assert click.get_current_context().obj == "FOOBAR"130131 assert click.get_current_context(silent=True) is None132 runner.invoke(cli, [], catch_exceptions=False)133 assert click.get_current_context(silent=True) is None134135136def test_context_meta(runner):137 LANG_KEY = f"{__name__}.lang"138139 def set_language(value):140 click.get_current_context().meta[LANG_KEY] = value141142 def get_language():143 return click.get_current_context().meta.get(LANG_KEY, "en_US")144145 @click.command()146 @click.pass_context147 def cli(ctx):148 assert get_language() == "en_US"149 set_language("de_DE")150 assert get_language() == "de_DE"151152 runner.invoke(cli, [], catch_exceptions=False)Merge pull request #1807 from pallets/pass-metaDavid Lordbefore adoptiona6fea31
lines 153–174why, one step back153154155def test_make_pass_meta_decorator(runner):156 @click.group()157 @click.pass_context158 def cli(ctx):159 ctx.meta["value"] = "good"160161 @cli.command()162 @pass_meta_key("value")163 def show(value):164 return value165166 result = runner.invoke(cli, ["show"], standalone_mode=False)167 assert result.return_value == "good"168169170def test_make_pass_meta_decorator_doc():171 pass_value = pass_meta_key("value")172 assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__173 pass_value = pass_meta_key("value", doc_description="the test value")174 assert "passes the test value" in pass_value.__doc__Merge pull request #1748 from pallets/dependabot/pip/importlib-metadata-3.3.0dependabot-preview[bot]before adoptionca1cefb
lines 175–367why, one step back175176177def test_context_pushing():178 rv = []179180 @click.command()181 def cli():182 pass183184 ctx = click.Context(cli)185186 @ctx.call_on_close187 def test_callback():188 rv.append(42)189190 with ctx.scope(cleanup=False):191 # Internal192 assert ctx._depth == 2193194 assert rv == []195196 with ctx.scope():197 # Internal198 assert ctx._depth == 1199200 assert rv == [42]201202203def test_pass_obj(runner):204 @click.group()205 @click.pass_context206 def cli(ctx):207 ctx.obj = "test"208209 @cli.command()210 @click.pass_obj211 def test(obj):212 click.echo(obj)213214 result = runner.invoke(cli, ["test"])215 assert not result.exception216 assert result.output == "test\n"217218219def test_close_before_pop(runner):220 called = []221222 @click.command()223 @click.pass_context224 def cli(ctx):225 ctx.obj = "test"226227 @ctx.call_on_close228 def foo():229 assert click.get_current_context().obj == "test"230 called.append(True)231232 click.echo("aha!")233234 result = runner.invoke(cli, [])235 assert not result.exception236 assert result.output == "aha!\n"237 assert called == [True]238239240def test_with_resource():241 @contextmanager242 def manager():243 val = [1]244 yield val245 val[0] = 0246247 ctx = click.Context(click.Command("test"))248249 with ctx.scope():250 rv = ctx.with_resource(manager())251 assert rv[0] == 1252253 assert rv == [0]254255256def test_make_pass_decorator_args(runner):257 """258 Test to check that make_pass_decorator doesn't consume arguments based on259 invocation order.260 """261262 class Foo:263 title = "foocmd"264265 pass_foo = click.make_pass_decorator(Foo)266267 @click.group()268 @click.pass_context269 def cli(ctx):270 ctx.obj = Foo()271272 @cli.command()273 @click.pass_context274 @pass_foo275 def test1(foo, ctx):276 click.echo(foo.title)277278 @cli.command()279 @pass_foo280 @click.pass_context281 def test2(ctx, foo):282 click.echo(foo.title)283284 result = runner.invoke(cli, ["test1"])285 assert not result.exception286 assert result.output == "foocmd\n"287288 result = runner.invoke(cli, ["test2"])289 assert not result.exception290 assert result.output == "foocmd\n"291292293def test_propagate_show_default_setting(runner):294 """A context's ``show_default`` setting defaults to the value from295 the parent context.296 """297 group = click.Group(298 commands={299 "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]),300 },301 context_settings={"show_default": True},302 )303 result = runner.invoke(group, ["sub", "--help"])304 assert "[default: a]" in result.output305306307def test_exit_not_standalone():308 @click.command()309 @click.pass_context310 def cli(ctx):311 ctx.exit(1)312313 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1314315 @click.command()316 @click.pass_context317 def cli(ctx):318 ctx.exit(0)319320 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0321322323@pytest.mark.parametrize(324 ("option_args", "invoke_args", "expect"),325 [326 pytest.param({}, {}, ParameterSource.DEFAULT, id="default"),327 pytest.param(328 {},329 {"default_map": {"option": 1}},330 ParameterSource.DEFAULT_MAP,331 id="default_map",332 ),333 pytest.param(334 {},335 {"args": ["-o", "1"]},336 ParameterSource.COMMANDLINE,337 id="commandline short",338 ),339 pytest.param(340 {},341 {"args": ["--option", "1"]},342 ParameterSource.COMMANDLINE,343 id="commandline long",344 ),345 pytest.param(346 {},347 {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}},348 ParameterSource.ENVIRONMENT,349 id="environment auto",350 ),351 pytest.param(352 {"envvar": "NAME"},353 {"env": {"NAME": "1"}},354 ParameterSource.ENVIRONMENT,355 id="environment manual",356 ),357 ],358)359def test_parameter_source(runner, option_args, invoke_args, expect):360 @click.command()361 @click.pass_context362 @click.option("-o", "--option", default=1, **option_args)363 def cli(ctx, option):364 return ctx.get_parameter_source("option")365366 rv = runner.invoke(cli, standalone_mode=False, **invoke_args)367 assert rv.return_value == expectMerge pull request #2041 from spanglerco/shell-completion-option-valuesDavid Lordbefore adoptionef11be6
lines 368–375why, one step back368369370def test_propagate_opt_prefixes():371 parent = click.Context(click.Command("test"))372 parent._opt_prefixes = {"-", "--", "!"}373 ctx = click.Context(click.Command("test2"), parent=parent)374375 assert ctx._opt_prefixes == {"-", "--", "!"}