test_context.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. from contextlib import contextmanager
  2. import pytest
  3. import click
  4. from click.core import ParameterSource
  5. from click.decorators import pass_meta_key
  6. def test_ensure_context_objects(runner):
  7. class Foo:
  8. def __init__(self):
  9. self.title = "default"
  10. pass_foo = click.make_pass_decorator(Foo, ensure=True)
  11. @click.group()
  12. @pass_foo
  13. def cli(foo):
  14. pass
  15. @cli.command()
  16. @pass_foo
  17. def test(foo):
  18. click.echo(foo.title)
  19. result = runner.invoke(cli, ["test"])
  20. assert not result.exception
  21. assert result.output == "default\n"
  22. def test_get_context_objects(runner):
  23. class Foo:
  24. def __init__(self):
  25. self.title = "default"
  26. pass_foo = click.make_pass_decorator(Foo, ensure=True)
  27. @click.group()
  28. @click.pass_context
  29. def cli(ctx):
  30. ctx.obj = Foo()
  31. ctx.obj.title = "test"
  32. @cli.command()
  33. @pass_foo
  34. def test(foo):
  35. click.echo(foo.title)
  36. result = runner.invoke(cli, ["test"])
  37. assert not result.exception
  38. assert result.output == "test\n"
  39. def test_get_context_objects_no_ensuring(runner):
  40. class Foo:
  41. def __init__(self):
  42. self.title = "default"
  43. pass_foo = click.make_pass_decorator(Foo)
  44. @click.group()
  45. @click.pass_context
  46. def cli(ctx):
  47. ctx.obj = Foo()
  48. ctx.obj.title = "test"
  49. @cli.command()
  50. @pass_foo
  51. def test(foo):
  52. click.echo(foo.title)
  53. result = runner.invoke(cli, ["test"])
  54. assert not result.exception
  55. assert result.output == "test\n"
  56. def test_get_context_objects_missing(runner):
  57. class Foo:
  58. pass
  59. pass_foo = click.make_pass_decorator(Foo)
  60. @click.group()
  61. @click.pass_context
  62. def cli(ctx):
  63. pass
  64. @cli.command()
  65. @pass_foo
  66. def test(foo):
  67. click.echo(foo.title)
  68. result = runner.invoke(cli, ["test"])
  69. assert result.exception is not None
  70. assert isinstance(result.exception, RuntimeError)
  71. assert (
  72. "Managed to invoke callback without a context object of type"
  73. " 'Foo' existing" in str(result.exception)
  74. )
  75. def test_multi_enter(runner):
  76. called = []
  77. @click.command()
  78. @click.pass_context
  79. def cli(ctx):
  80. def callback():
  81. called.append(True)
  82. ctx.call_on_close(callback)
  83. with ctx:
  84. pass
  85. assert not called
  86. result = runner.invoke(cli, [])
  87. assert result.exception is None
  88. assert called == [True]
  89. def test_global_context_object(runner):
  90. @click.command()
  91. @click.pass_context
  92. def cli(ctx):
  93. assert click.get_current_context() is ctx
  94. ctx.obj = "FOOBAR"
  95. assert click.get_current_context().obj == "FOOBAR"
  96. assert click.get_current_context(silent=True) is None
  97. runner.invoke(cli, [], catch_exceptions=False)
  98. assert click.get_current_context(silent=True) is None
  99. def test_context_meta(runner):
  100. LANG_KEY = f"{__name__}.lang"
  101. def set_language(value):
  102. click.get_current_context().meta[LANG_KEY] = value
  103. def get_language():
  104. return click.get_current_context().meta.get(LANG_KEY, "en_US")
  105. @click.command()
  106. @click.pass_context
  107. def cli(ctx):
  108. assert get_language() == "en_US"
  109. set_language("de_DE")
  110. assert get_language() == "de_DE"
  111. runner.invoke(cli, [], catch_exceptions=False)
  112. def test_make_pass_meta_decorator(runner):
  113. @click.group()
  114. @click.pass_context
  115. def cli(ctx):
  116. ctx.meta["value"] = "good"
  117. @cli.command()
  118. @pass_meta_key("value")
  119. def show(value):
  120. return value
  121. result = runner.invoke(cli, ["show"], standalone_mode=False)
  122. assert result.return_value == "good"
  123. def test_make_pass_meta_decorator_doc():
  124. pass_value = pass_meta_key("value")
  125. assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__
  126. pass_value = pass_meta_key("value", doc_description="the test value")
  127. assert "passes the test value" in pass_value.__doc__
  128. def test_context_pushing():
  129. rv = []
  130. @click.command()
  131. def cli():
  132. pass
  133. ctx = click.Context(cli)
  134. @ctx.call_on_close
  135. def test_callback():
  136. rv.append(42)
  137. with ctx.scope(cleanup=False):
  138. # Internal
  139. assert ctx._depth == 2
  140. assert rv == []
  141. with ctx.scope():
  142. # Internal
  143. assert ctx._depth == 1
  144. assert rv == [42]
  145. def test_pass_obj(runner):
  146. @click.group()
  147. @click.pass_context
  148. def cli(ctx):
  149. ctx.obj = "test"
  150. @cli.command()
  151. @click.pass_obj
  152. def test(obj):
  153. click.echo(obj)
  154. result = runner.invoke(cli, ["test"])
  155. assert not result.exception
  156. assert result.output == "test\n"
  157. def test_close_before_pop(runner):
  158. called = []
  159. @click.command()
  160. @click.pass_context
  161. def cli(ctx):
  162. ctx.obj = "test"
  163. @ctx.call_on_close
  164. def foo():
  165. assert click.get_current_context().obj == "test"
  166. called.append(True)
  167. click.echo("aha!")
  168. result = runner.invoke(cli, [])
  169. assert not result.exception
  170. assert result.output == "aha!\n"
  171. assert called == [True]
  172. def test_with_resource():
  173. @contextmanager
  174. def manager():
  175. val = [1]
  176. yield val
  177. val[0] = 0
  178. ctx = click.Context(click.Command("test"))
  179. with ctx.scope():
  180. rv = ctx.with_resource(manager())
  181. assert rv[0] == 1
  182. assert rv == [0]
  183. def test_make_pass_decorator_args(runner):
  184. """
  185. Test to check that make_pass_decorator doesn't consume arguments based on
  186. invocation order.
  187. """
  188. class Foo:
  189. title = "foocmd"
  190. pass_foo = click.make_pass_decorator(Foo)
  191. @click.group()
  192. @click.pass_context
  193. def cli(ctx):
  194. ctx.obj = Foo()
  195. @cli.command()
  196. @click.pass_context
  197. @pass_foo
  198. def test1(foo, ctx):
  199. click.echo(foo.title)
  200. @cli.command()
  201. @pass_foo
  202. @click.pass_context
  203. def test2(ctx, foo):
  204. click.echo(foo.title)
  205. result = runner.invoke(cli, ["test1"])
  206. assert not result.exception
  207. assert result.output == "foocmd\n"
  208. result = runner.invoke(cli, ["test2"])
  209. assert not result.exception
  210. assert result.output == "foocmd\n"
  211. def test_propagate_show_default_setting(runner):
  212. """A context's ``show_default`` setting defaults to the value from
  213. the parent context.
  214. """
  215. group = click.Group(
  216. commands={
  217. "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]),
  218. },
  219. context_settings={"show_default": True},
  220. )
  221. result = runner.invoke(group, ["sub", "--help"])
  222. assert "[default: a]" in result.output
  223. def test_exit_not_standalone():
  224. @click.command()
  225. @click.pass_context
  226. def cli(ctx):
  227. ctx.exit(1)
  228. assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1
  229. @click.command()
  230. @click.pass_context
  231. def cli(ctx):
  232. ctx.exit(0)
  233. assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0
  234. @pytest.mark.parametrize(
  235. ("option_args", "invoke_args", "expect"),
  236. [
  237. pytest.param({}, {}, ParameterSource.DEFAULT, id="default"),
  238. pytest.param(
  239. {},
  240. {"default_map": {"option": 1}},
  241. ParameterSource.DEFAULT_MAP,
  242. id="default_map",
  243. ),
  244. pytest.param(
  245. {},
  246. {"args": ["-o", "1"]},
  247. ParameterSource.COMMANDLINE,
  248. id="commandline short",
  249. ),
  250. pytest.param(
  251. {},
  252. {"args": ["--option", "1"]},
  253. ParameterSource.COMMANDLINE,
  254. id="commandline long",
  255. ),
  256. pytest.param(
  257. {},
  258. {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}},
  259. ParameterSource.ENVIRONMENT,
  260. id="environment auto",
  261. ),
  262. pytest.param(
  263. {"envvar": "NAME"},
  264. {"env": {"NAME": "1"}},
  265. ParameterSource.ENVIRONMENT,
  266. id="environment manual",
  267. ),
  268. ],
  269. )
  270. def test_parameter_source(runner, option_args, invoke_args, expect):
  271. @click.command()
  272. @click.pass_context
  273. @click.option("-o", "--option", default=1, **option_args)
  274. def cli(ctx, option):
  275. return ctx.get_parameter_source("option")
  276. rv = runner.invoke(cli, standalone_mode=False, **invoke_args)
  277. assert rv.return_value == expect
  278. def test_propagate_opt_prefixes():
  279. parent = click.Context(click.Command("test"))
  280. parent._opt_prefixes = {"-", "--", "!"}
  281. ctx = click.Context(click.Command("test2"), parent=parent)
  282. assert ctx._opt_prefixes == {"-", "--", "!"}