test_options.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. import os
  2. import re
  3. import pytest
  4. import click
  5. from click import Option
  6. def test_prefixes(runner):
  7. @click.command()
  8. @click.option("++foo", is_flag=True, help="das foo")
  9. @click.option("--bar", is_flag=True, help="das bar")
  10. def cli(foo, bar):
  11. click.echo(f"foo={foo} bar={bar}")
  12. result = runner.invoke(cli, ["++foo", "--bar"])
  13. assert not result.exception
  14. assert result.output == "foo=True bar=True\n"
  15. result = runner.invoke(cli, ["--help"])
  16. assert re.search(r"\+\+foo\s+das foo", result.output) is not None
  17. assert re.search(r"--bar\s+das bar", result.output) is not None
  18. def test_invalid_option(runner):
  19. with pytest.raises(TypeError, match="name was passed") as exc_info:
  20. click.Option(["foo"])
  21. message = str(exc_info.value)
  22. assert "name was passed (foo)" in message
  23. assert "declare an argument" in message
  24. assert "'--foo'" in message
  25. def test_invalid_nargs(runner):
  26. with pytest.raises(TypeError, match="nargs=-1"):
  27. @click.command()
  28. @click.option("--foo", nargs=-1)
  29. def cli(foo):
  30. pass
  31. def test_nargs_tup_composite_mult(runner):
  32. @click.command()
  33. @click.option("--item", type=(str, int), multiple=True)
  34. def copy(item):
  35. for name, id in item:
  36. click.echo(f"name={name} id={id:d}")
  37. result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])
  38. assert not result.exception
  39. assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]
  40. def test_counting(runner):
  41. @click.command()
  42. @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))
  43. def cli(v):
  44. click.echo(f"verbosity={v:d}")
  45. result = runner.invoke(cli, ["-vvv"])
  46. assert not result.exception
  47. assert result.output == "verbosity=3\n"
  48. result = runner.invoke(cli, ["-vvvv"])
  49. assert result.exception
  50. assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output
  51. result = runner.invoke(cli, [])
  52. assert not result.exception
  53. assert result.output == "verbosity=0\n"
  54. result = runner.invoke(cli, ["--help"])
  55. assert re.search(r"-v\s+Verbosity", result.output) is not None
  56. @pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])
  57. def test_unknown_options(runner, unknown_flag):
  58. @click.command()
  59. def cli():
  60. pass
  61. result = runner.invoke(cli, [unknown_flag])
  62. assert result.exception
  63. assert f"No such option: {unknown_flag}" in result.output
  64. @pytest.mark.parametrize(
  65. ("value", "expect"),
  66. [
  67. ("--cat", "Did you mean --count?"),
  68. ("--bounds", "(Possible options: --bound, --count)"),
  69. ("--bount", "(Possible options: --bound, --count)"),
  70. ],
  71. )
  72. def test_suggest_possible_options(runner, value, expect):
  73. cli = click.Command(
  74. "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]
  75. )
  76. result = runner.invoke(cli, [value])
  77. assert expect in result.output
  78. def test_multiple_required(runner):
  79. @click.command()
  80. @click.option("-m", "--message", multiple=True, required=True)
  81. def cli(message):
  82. click.echo("\n".join(message))
  83. result = runner.invoke(cli, ["-m", "foo", "-mbar"])
  84. assert not result.exception
  85. assert result.output == "foo\nbar\n"
  86. result = runner.invoke(cli, [])
  87. assert result.exception
  88. assert "Error: Missing option '-m' / '--message'." in result.output
  89. @pytest.mark.parametrize(
  90. ("multiple", "nargs", "default"),
  91. [
  92. (True, 1, []),
  93. (True, 1, [1]),
  94. # (False, -1, []),
  95. # (False, -1, [1]),
  96. (False, 2, [1, 2]),
  97. # (True, -1, [[]]),
  98. # (True, -1, []),
  99. # (True, -1, [[1]]),
  100. (True, 2, []),
  101. (True, 2, [[1, 2]]),
  102. ],
  103. )
  104. def test_init_good_default_list(runner, multiple, nargs, default):
  105. click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)
  106. @pytest.mark.parametrize(
  107. ("multiple", "nargs", "default"),
  108. [
  109. (True, 1, 1),
  110. # (False, -1, 1),
  111. (False, 2, [1]),
  112. (True, 2, [[1]]),
  113. ],
  114. )
  115. def test_init_bad_default_list(runner, multiple, nargs, default):
  116. type = (str, str) if nargs == 2 else None
  117. with pytest.raises(ValueError, match="default"):
  118. click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)
  119. @pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])
  120. def test_empty_envvar(runner, env_key):
  121. @click.command()
  122. @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")
  123. def cli(mypath):
  124. click.echo(f"mypath: {mypath}")
  125. result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")
  126. assert result.exception is None
  127. assert result.output == "mypath: None\n"
  128. def test_multiple_envvar(runner):
  129. @click.command()
  130. @click.option("--arg", multiple=True)
  131. def cmd(arg):
  132. click.echo("|".join(arg))
  133. result = runner.invoke(
  134. cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}
  135. )
  136. assert not result.exception
  137. assert result.output == "foo|bar|baz\n"
  138. @click.command()
  139. @click.option("--arg", multiple=True, envvar="X")
  140. def cmd(arg):
  141. click.echo("|".join(arg))
  142. result = runner.invoke(cmd, [], env={"X": "foo bar baz"})
  143. assert not result.exception
  144. assert result.output == "foo|bar|baz\n"
  145. @click.command()
  146. @click.option("--arg", multiple=True, type=click.Path())
  147. def cmd(arg):
  148. click.echo("|".join(arg))
  149. result = runner.invoke(
  150. cmd,
  151. [],
  152. auto_envvar_prefix="TEST",
  153. env={"TEST_ARG": f"foo{os.path.pathsep}bar"},
  154. )
  155. assert not result.exception
  156. assert result.output == "foo|bar\n"
  157. def test_trailing_blanks_boolean_envvar(runner):
  158. @click.command()
  159. @click.option("--shout/--no-shout", envvar="SHOUT")
  160. def cli(shout):
  161. click.echo(f"shout: {shout!r}")
  162. result = runner.invoke(cli, [], env={"SHOUT": " true "})
  163. assert result.exit_code == 0
  164. assert result.output == "shout: True\n"
  165. def test_multiple_default_help(runner):
  166. @click.command()
  167. @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)
  168. @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)
  169. def cmd(arg, arg2):
  170. pass
  171. result = runner.invoke(cmd, ["--help"])
  172. assert not result.exception
  173. assert "foo, bar" in result.output
  174. assert "1, 2" in result.output
  175. def test_show_default_default_map(runner):
  176. @click.command()
  177. @click.option("--arg", default="a", show_default=True)
  178. def cmd(arg):
  179. click.echo(arg)
  180. result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})
  181. assert not result.exception
  182. assert "[default: b]" in result.output
  183. def test_multiple_default_type():
  184. opt = click.Option(["-a"], multiple=True, default=(1, 2))
  185. assert opt.nargs == 1
  186. assert opt.multiple
  187. assert opt.type is click.INT
  188. ctx = click.Context(click.Command("test"))
  189. assert opt.get_default(ctx) == (1, 2)
  190. def test_multiple_default_composite_type():
  191. opt = click.Option(["-a"], multiple=True, default=[(1, "a")])
  192. assert opt.nargs == 2
  193. assert opt.multiple
  194. assert isinstance(opt.type, click.Tuple)
  195. assert opt.type.types == [click.INT, click.STRING]
  196. ctx = click.Context(click.Command("test"))
  197. assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)
  198. def test_parse_multiple_default_composite_type(runner):
  199. @click.command()
  200. @click.option("-a", multiple=True, default=("a", "b"))
  201. @click.option("-b", multiple=True, default=[(1, "a")])
  202. def cmd(a, b):
  203. click.echo(a)
  204. click.echo(b)
  205. # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())
  206. # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"
  207. result = runner.invoke(cmd)
  208. assert result.output == "('a', 'b')\n((1, 'a'),)\n"
  209. def test_dynamic_default_help_unset(runner):
  210. @click.command()
  211. @click.option(
  212. "--username",
  213. prompt=True,
  214. default=lambda: os.environ.get("USER", ""),
  215. show_default=True,
  216. )
  217. def cmd(username):
  218. print("Hello,", username)
  219. result = runner.invoke(cmd, ["--help"])
  220. assert result.exit_code == 0
  221. assert "--username" in result.output
  222. assert "lambda" not in result.output
  223. assert "(dynamic)" in result.output
  224. def test_dynamic_default_help_text(runner):
  225. @click.command()
  226. @click.option(
  227. "--username",
  228. prompt=True,
  229. default=lambda: os.environ.get("USER", ""),
  230. show_default="current user",
  231. )
  232. def cmd(username):
  233. print("Hello,", username)
  234. result = runner.invoke(cmd, ["--help"])
  235. assert result.exit_code == 0
  236. assert "--username" in result.output
  237. assert "lambda" not in result.output
  238. assert "(current user)" in result.output
  239. def test_dynamic_default_help_special_method(runner):
  240. class Value:
  241. def __call__(self):
  242. return 42
  243. def __str__(self):
  244. return "special value"
  245. opt = click.Option(["-a"], default=Value(), show_default=True)
  246. ctx = click.Context(click.Command("cli"))
  247. assert "special value" in opt.get_help_record(ctx)[1]
  248. @pytest.mark.parametrize(
  249. ("type", "expect"),
  250. [
  251. (click.IntRange(1, 32), "1<=x<=32"),
  252. (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),
  253. (click.IntRange(1), "x>=1"),
  254. (click.IntRange(max=32), "x<=32"),
  255. ],
  256. )
  257. def test_intrange_default_help_text(type, expect):
  258. option = click.Option(["--num"], type=type, show_default=True, default=2)
  259. context = click.Context(click.Command("test"))
  260. result = option.get_help_record(context)[1]
  261. assert expect in result
  262. def test_count_default_type_help():
  263. """A count option with the default type should not show >=0 in help."""
  264. option = click.Option(["--count"], count=True, help="some words")
  265. context = click.Context(click.Command("test"))
  266. result = option.get_help_record(context)[1]
  267. assert result == "some words"
  268. def test_file_type_help_default():
  269. """The default for a File type is a filename string. The string
  270. should be displayed in help, not an open file object.
  271. Type casting is only applied to defaults in processing, not when
  272. getting the default value.
  273. """
  274. option = click.Option(
  275. ["--in"], type=click.File(), default=__file__, show_default=True
  276. )
  277. context = click.Context(click.Command("test"))
  278. result = option.get_help_record(context)[1]
  279. assert __file__ in result
  280. def test_toupper_envvar_prefix(runner):
  281. @click.command()
  282. @click.option("--arg")
  283. def cmd(arg):
  284. click.echo(arg)
  285. result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})
  286. assert not result.exception
  287. assert result.output == "foo\n"
  288. def test_nargs_envvar(runner):
  289. @click.command()
  290. @click.option("--arg", nargs=2)
  291. def cmd(arg):
  292. click.echo("|".join(arg))
  293. result = runner.invoke(
  294. cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}
  295. )
  296. assert not result.exception
  297. assert result.output == "foo|bar\n"
  298. @click.command()
  299. @click.option("--arg", nargs=2, multiple=True)
  300. def cmd(arg):
  301. for item in arg:
  302. click.echo("|".join(item))
  303. result = runner.invoke(
  304. cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}
  305. )
  306. assert not result.exception
  307. assert result.output == "x|1\ny|2\n"
  308. def test_show_envvar(runner):
  309. @click.command()
  310. @click.option("--arg1", envvar="ARG1", show_envvar=True)
  311. def cmd(arg):
  312. pass
  313. result = runner.invoke(cmd, ["--help"])
  314. assert not result.exception
  315. assert "ARG1" in result.output
  316. def test_show_envvar_auto_prefix(runner):
  317. @click.command()
  318. @click.option("--arg1", show_envvar=True)
  319. def cmd(arg):
  320. pass
  321. result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")
  322. assert not result.exception
  323. assert "TEST_ARG1" in result.output
  324. def test_show_envvar_auto_prefix_dash_in_command(runner):
  325. @click.group()
  326. def cli():
  327. pass
  328. @cli.command()
  329. @click.option("--baz", show_envvar=True)
  330. def foo_bar(baz):
  331. pass
  332. result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")
  333. assert not result.exception
  334. assert "TEST_FOO_BAR_BAZ" in result.output
  335. def test_custom_validation(runner):
  336. def validate_pos_int(ctx, param, value):
  337. if value < 0:
  338. raise click.BadParameter("Value needs to be positive")
  339. return value
  340. @click.command()
  341. @click.option("--foo", callback=validate_pos_int, default=1)
  342. def cmd(foo):
  343. click.echo(foo)
  344. result = runner.invoke(cmd, ["--foo", "-1"])
  345. assert "Invalid value for '--foo': Value needs to be positive" in result.output
  346. result = runner.invoke(cmd, ["--foo", "42"])
  347. assert result.output == "42\n"
  348. def test_callback_validates_prompt(runner, monkeypatch):
  349. def validate(ctx, param, value):
  350. if value < 0:
  351. raise click.BadParameter("should be positive")
  352. return value
  353. @click.command()
  354. @click.option("-a", type=int, callback=validate, prompt=True)
  355. def cli(a):
  356. click.echo(a)
  357. result = runner.invoke(cli, input="-12\n60\n")
  358. assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"
  359. def test_winstyle_options(runner):
  360. @click.command()
  361. @click.option("/debug;/no-debug", help="Enables or disables debug mode.")
  362. def cmd(debug):
  363. click.echo(debug)
  364. result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])
  365. assert result.output == "True\n"
  366. result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])
  367. assert result.output == "False\n"
  368. result = runner.invoke(cmd, [], help_option_names=["/?"])
  369. assert result.output == "False\n"
  370. result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])
  371. assert "/debug; /no-debug Enables or disables debug mode." in result.output
  372. assert "/? Show this message and exit." in result.output
  373. def test_legacy_options(runner):
  374. @click.command()
  375. @click.option("-whatever")
  376. def cmd(whatever):
  377. click.echo(whatever)
  378. result = runner.invoke(cmd, ["-whatever", "42"])
  379. assert result.output == "42\n"
  380. result = runner.invoke(cmd, ["-whatever=23"])
  381. assert result.output == "23\n"
  382. def test_missing_option_string_cast():
  383. ctx = click.Context(click.Command(""))
  384. with pytest.raises(click.MissingParameter) as excinfo:
  385. click.Option(["-a"], required=True).process_value(ctx, None)
  386. assert str(excinfo.value) == "Missing parameter: a"
  387. def test_missing_required_flag(runner):
  388. cli = click.Command(
  389. "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]
  390. )
  391. result = runner.invoke(cli)
  392. assert result.exit_code == 2
  393. assert "Error: Missing option '--on'." in result.output
  394. def test_missing_choice(runner):
  395. @click.command()
  396. @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)
  397. def cmd(foo):
  398. click.echo(foo)
  399. result = runner.invoke(cmd)
  400. assert result.exit_code == 2
  401. error, separator, choices = result.output.partition("Choose from")
  402. assert "Error: Missing option '--foo'. " in error
  403. assert "Choose from" in separator
  404. assert "foo" in choices
  405. assert "bar" in choices
  406. def test_case_insensitive_choice(runner):
  407. @click.command()
  408. @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))
  409. def cmd(foo):
  410. click.echo(foo)
  411. result = runner.invoke(cmd, ["--foo", "apple"])
  412. assert result.exit_code == 0
  413. assert result.output == "Apple\n"
  414. result = runner.invoke(cmd, ["--foo", "oRANGe"])
  415. assert result.exit_code == 0
  416. assert result.output == "Orange\n"
  417. result = runner.invoke(cmd, ["--foo", "Apple"])
  418. assert result.exit_code == 0
  419. assert result.output == "Apple\n"
  420. @click.command()
  421. @click.option("--foo", type=click.Choice(["Orange", "Apple"]))
  422. def cmd2(foo):
  423. click.echo(foo)
  424. result = runner.invoke(cmd2, ["--foo", "apple"])
  425. assert result.exit_code == 2
  426. result = runner.invoke(cmd2, ["--foo", "oRANGe"])
  427. assert result.exit_code == 2
  428. result = runner.invoke(cmd2, ["--foo", "Apple"])
  429. assert result.exit_code == 0
  430. def test_case_insensitive_choice_returned_exactly(runner):
  431. @click.command()
  432. @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))
  433. def cmd(foo):
  434. click.echo(foo)
  435. result = runner.invoke(cmd, ["--foo", "apple"])
  436. assert result.exit_code == 0
  437. assert result.output == "Apple\n"
  438. def test_option_help_preserve_paragraphs(runner):
  439. @click.command()
  440. @click.option(
  441. "-C",
  442. "--config",
  443. type=click.Path(),
  444. help="""Configuration file to use.
  445. If not given, the environment variable CONFIG_FILE is consulted
  446. and used if set. If neither are given, a default configuration
  447. file is loaded.""",
  448. )
  449. def cmd(config):
  450. pass
  451. result = runner.invoke(cmd, ["--help"])
  452. assert result.exit_code == 0
  453. i = " " * 21
  454. assert (
  455. " -C, --config PATH Configuration file to use.\n"
  456. f"{i}\n"
  457. f"{i}If not given, the environment variable CONFIG_FILE is\n"
  458. f"{i}consulted and used if set. If neither are given, a default\n"
  459. f"{i}configuration file is loaded."
  460. ) in result.output
  461. def test_argument_custom_class(runner):
  462. class CustomArgument(click.Argument):
  463. def get_default(self, ctx, call=True):
  464. """a dumb override of a default value for testing"""
  465. return "I am a default"
  466. @click.command()
  467. @click.argument("testarg", cls=CustomArgument, default="you wont see me")
  468. def cmd(testarg):
  469. click.echo(testarg)
  470. result = runner.invoke(cmd)
  471. assert "I am a default" in result.output
  472. assert "you wont see me" not in result.output
  473. def test_option_custom_class(runner):
  474. class CustomOption(click.Option):
  475. def get_help_record(self, ctx):
  476. """a dumb override of a help text for testing"""
  477. return ("--help", "I am a help text")
  478. @click.command()
  479. @click.option("--testoption", cls=CustomOption, help="you wont see me")
  480. def cmd(testoption):
  481. click.echo(testoption)
  482. result = runner.invoke(cmd, ["--help"])
  483. assert "I am a help text" in result.output
  484. assert "you wont see me" not in result.output
  485. def test_option_custom_class_reusable(runner):
  486. """Ensure we can reuse a custom class option. See Issue #926"""
  487. class CustomOption(click.Option):
  488. def get_help_record(self, ctx):
  489. """a dumb override of a help text for testing"""
  490. return ("--help", "I am a help text")
  491. # Assign to a variable to re-use the decorator.
  492. testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")
  493. @click.command()
  494. @testoption
  495. def cmd1(testoption):
  496. click.echo(testoption)
  497. @click.command()
  498. @testoption
  499. def cmd2(testoption):
  500. click.echo(testoption)
  501. # Both of the commands should have the --help option now.
  502. for cmd in (cmd1, cmd2):
  503. result = runner.invoke(cmd, ["--help"])
  504. assert "I am a help text" in result.output
  505. assert "you wont see me" not in result.output
  506. def test_bool_flag_with_type(runner):
  507. @click.command()
  508. @click.option("--shout/--no-shout", default=False, type=bool)
  509. def cmd(shout):
  510. pass
  511. result = runner.invoke(cmd)
  512. assert not result.exception
  513. def test_aliases_for_flags(runner):
  514. @click.command()
  515. @click.option("--warnings/--no-warnings", " /-W", default=True)
  516. def cli(warnings):
  517. click.echo(warnings)
  518. result = runner.invoke(cli, ["--warnings"])
  519. assert result.output == "True\n"
  520. result = runner.invoke(cli, ["--no-warnings"])
  521. assert result.output == "False\n"
  522. result = runner.invoke(cli, ["-W"])
  523. assert result.output == "False\n"
  524. @click.command()
  525. @click.option("--warnings/--no-warnings", "-w", default=True)
  526. def cli_alt(warnings):
  527. click.echo(warnings)
  528. result = runner.invoke(cli_alt, ["--warnings"])
  529. assert result.output == "True\n"
  530. result = runner.invoke(cli_alt, ["--no-warnings"])
  531. assert result.output == "False\n"
  532. result = runner.invoke(cli_alt, ["-w"])
  533. assert result.output == "True\n"
  534. @pytest.mark.parametrize(
  535. "option_args,expected",
  536. [
  537. (["--aggressive", "--all", "-a"], "aggressive"),
  538. (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),
  539. (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),
  540. (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),
  541. (["-a", "-b", "-c"], "a"),
  542. (["-c", "-b", "-a"], "c"),
  543. (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),
  544. (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),
  545. (["--from", "-f", "_from"], "_from"),
  546. (["--return", "-r", "_ret"], "_ret"),
  547. ],
  548. )
  549. def test_option_names(runner, option_args, expected):
  550. @click.command()
  551. @click.option(*option_args, is_flag=True)
  552. def cmd(**kwargs):
  553. click.echo(str(kwargs[expected]))
  554. assert cmd.params[0].name == expected
  555. for form in option_args:
  556. if form.startswith("-"):
  557. result = runner.invoke(cmd, [form])
  558. assert result.output == "True\n"
  559. def test_flag_duplicate_names(runner):
  560. with pytest.raises(ValueError, match="cannot use the same flag for true/false"):
  561. click.Option(["--foo/--foo"], default=False)
  562. @pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])
  563. def test_show_default_boolean_flag_name(runner, default, expect):
  564. """When a boolean flag has distinct True/False opts, it should show
  565. the default opt name instead of the default value. It should only
  566. show one name even if multiple are declared.
  567. """
  568. opt = click.Option(
  569. ("--cache/--no-cache", "--c/--nc"),
  570. default=default,
  571. show_default=True,
  572. help="Enable/Disable the cache.",
  573. )
  574. ctx = click.Context(click.Command("test"))
  575. message = opt.get_help_record(ctx)[1]
  576. assert f"[default: {expect}]" in message
  577. def test_show_true_default_boolean_flag_value(runner):
  578. """When a boolean flag only has one opt and its default is True,
  579. it will show the default value, not the opt name.
  580. """
  581. opt = click.Option(
  582. ("--cache",),
  583. is_flag=True,
  584. show_default=True,
  585. default=True,
  586. help="Enable the cache.",
  587. )
  588. ctx = click.Context(click.Command("test"))
  589. message = opt.get_help_record(ctx)[1]
  590. assert "[default: True]" in message
  591. @pytest.mark.parametrize("default", [False, None])
  592. def test_hide_false_default_boolean_flag_value(runner, default):
  593. """When a boolean flag only has one opt and its default is False or
  594. None, it will not show the default
  595. """
  596. opt = click.Option(
  597. ("--cache",),
  598. is_flag=True,
  599. show_default=True,
  600. default=default,
  601. help="Enable the cache.",
  602. )
  603. ctx = click.Context(click.Command("test"))
  604. message = opt.get_help_record(ctx)[1]
  605. assert "[default: " not in message
  606. def test_show_default_string(runner):
  607. """When show_default is a string show that value as default."""
  608. opt = click.Option(["--limit"], show_default="unlimited")
  609. ctx = click.Context(click.Command("cli"))
  610. message = opt.get_help_record(ctx)[1]
  611. assert "[default: (unlimited)]" in message
  612. def test_do_not_show_no_default(runner):
  613. """When show_default is True and no default is set do not show None."""
  614. opt = click.Option(["--limit"], show_default=True)
  615. ctx = click.Context(click.Command("cli"))
  616. message = opt.get_help_record(ctx)[1]
  617. assert "[default: None]" not in message
  618. def test_do_not_show_default_empty_multiple():
  619. """When show_default is True and multiple=True is set, it should not
  620. print empty default value in --help output.
  621. """
  622. opt = click.Option(["-a"], multiple=True, help="values", show_default=True)
  623. ctx = click.Context(click.Command("cli"))
  624. message = opt.get_help_record(ctx)[1]
  625. assert message == "values"
  626. @pytest.mark.parametrize(
  627. ("ctx_value", "opt_value", "expect"),
  628. [
  629. (None, None, False),
  630. (None, False, False),
  631. (None, True, True),
  632. (False, None, False),
  633. (False, False, False),
  634. (False, True, True),
  635. (True, None, True),
  636. (True, False, False),
  637. (True, True, True),
  638. (False, "one", True),
  639. ],
  640. )
  641. def test_show_default_precedence(ctx_value, opt_value, expect):
  642. ctx = click.Context(click.Command("test"), show_default=ctx_value)
  643. opt = click.Option("-a", default=1, help="value", show_default=opt_value)
  644. help = opt.get_help_record(ctx)[1]
  645. assert ("default:" in help) is expect
  646. @pytest.mark.parametrize(
  647. ("args", "expect"),
  648. [
  649. (None, (None, None, ())),
  650. (["--opt"], ("flag", None, ())),
  651. (["--opt", "-a", 42], ("flag", "42", ())),
  652. (["--opt", "test", "-a", 42], ("test", "42", ())),
  653. (["--opt=test", "-a", 42], ("test", "42", ())),
  654. (["-o"], ("flag", None, ())),
  655. (["-o", "-a", 42], ("flag", "42", ())),
  656. (["-o", "test", "-a", 42], ("test", "42", ())),
  657. (["-otest", "-a", 42], ("test", "42", ())),
  658. (["a", "b", "c"], (None, None, ("a", "b", "c"))),
  659. (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),
  660. (["--opt", "test"], ("test", None, ())),
  661. (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),
  662. (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),
  663. ],
  664. )
  665. def test_option_with_optional_value(runner, args, expect):
  666. @click.command()
  667. @click.option("-o", "--opt", is_flag=False, flag_value="flag")
  668. @click.option("-a")
  669. @click.argument("b", nargs=-1)
  670. def cli(opt, a, b):
  671. return opt, a, b
  672. result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)
  673. assert result.return_value == expect
  674. def test_multiple_option_with_optional_value(runner):
  675. cli = click.Command(
  676. "cli",
  677. params=[
  678. click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),
  679. click.Option(["-a"]),
  680. click.Argument(["b"], nargs=-1),
  681. ],
  682. callback=lambda **kwargs: kwargs,
  683. )
  684. result = runner.invoke(
  685. cli,
  686. ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],
  687. standalone_mode=False,
  688. catch_exceptions=False,
  689. )
  690. assert result.return_value == {
  691. "f": ("flag", "other", "flag"),
  692. "a": "1",
  693. "b": ("a", "b"),
  694. }
  695. def test_type_from_flag_value():
  696. param = click.Option(["-a", "x"], default=True, flag_value=4)
  697. assert param.type is click.INT
  698. param = click.Option(["-b", "x"], flag_value=8)
  699. assert param.type is click.INT
  700. @pytest.mark.parametrize(
  701. ("option", "expected"),
  702. [
  703. # Not boolean flags
  704. pytest.param(Option(["-a"], type=int), False, id="int option"),
  705. pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),
  706. pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),
  707. pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),
  708. pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),
  709. # Boolean flags
  710. pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),
  711. pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),
  712. pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),
  713. ],
  714. )
  715. def test_is_bool_flag_is_correctly_set(option, expected):
  716. assert option.is_bool_flag is expected
  717. @pytest.mark.parametrize(
  718. ("kwargs", "message"),
  719. [
  720. ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),
  721. ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),
  722. ],
  723. )
  724. def test_invalid_flag_combinations(runner, kwargs, message):
  725. with pytest.raises(TypeError) as e:
  726. click.Option(["-a"], **kwargs)
  727. assert message in str(e.value)