test_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import os
  2. import pathlib
  3. import stat
  4. import sys
  5. from io import StringIO
  6. import pytest
  7. import click._termui_impl
  8. import click.utils
  9. from click._compat import WIN
  10. def test_echo(runner):
  11. with runner.isolation() as outstreams:
  12. click.echo("\N{SNOWMAN}")
  13. click.echo(b"\x44\x44")
  14. click.echo(42, nl=False)
  15. click.echo(b"a", nl=False)
  16. click.echo("\x1b[31mx\x1b[39m", nl=False)
  17. bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")
  18. assert bytes == b"\xe2\x98\x83\nDD\n42ax"
  19. # if wrapped, we expect bytes to survive.
  20. @click.command()
  21. def cli():
  22. click.echo(b"\xf6")
  23. result = runner.invoke(cli, [])
  24. assert result.stdout_bytes == b"\xf6\n"
  25. # Ensure we do not strip for bytes.
  26. with runner.isolation() as outstreams:
  27. click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)
  28. assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"
  29. def test_echo_custom_file():
  30. import io
  31. f = io.StringIO()
  32. click.echo("hello", file=f)
  33. assert f.getvalue() == "hello\n"
  34. def test_echo_no_streams(monkeypatch, runner):
  35. """echo should not fail when stdout and stderr are None with pythonw on Windows."""
  36. with runner.isolation():
  37. sys.stdout = None
  38. sys.stderr = None
  39. click.echo("test")
  40. click.echo("test", err=True)
  41. @pytest.mark.parametrize(
  42. ("styles", "ref"),
  43. [
  44. ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),
  45. ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),
  46. ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),
  47. ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),
  48. ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),
  49. ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),
  50. ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),
  51. ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),
  52. ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),
  53. ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),
  54. ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),
  55. ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),
  56. ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),
  57. ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),
  58. ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),
  59. ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),
  60. ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),
  61. ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),
  62. ({"bold": True}, "\x1b[1mx y\x1b[0m"),
  63. ({"dim": True}, "\x1b[2mx y\x1b[0m"),
  64. ({"underline": True}, "\x1b[4mx y\x1b[0m"),
  65. ({"overline": True}, "\x1b[53mx y\x1b[0m"),
  66. ({"italic": True}, "\x1b[3mx y\x1b[0m"),
  67. ({"blink": True}, "\x1b[5mx y\x1b[0m"),
  68. ({"reverse": True}, "\x1b[7mx y\x1b[0m"),
  69. ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),
  70. ({"bold": False}, "\x1b[22mx y\x1b[0m"),
  71. ({"dim": False}, "\x1b[22mx y\x1b[0m"),
  72. ({"underline": False}, "\x1b[24mx y\x1b[0m"),
  73. ({"overline": False}, "\x1b[55mx y\x1b[0m"),
  74. ({"italic": False}, "\x1b[23mx y\x1b[0m"),
  75. ({"blink": False}, "\x1b[25mx y\x1b[0m"),
  76. ({"reverse": False}, "\x1b[27mx y\x1b[0m"),
  77. ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),
  78. ({"fg": "black", "reset": False}, "\x1b[30mx y"),
  79. ],
  80. )
  81. def test_styling(styles, ref):
  82. assert click.style("x y", **styles) == ref
  83. assert click.unstyle(ref) == "x y"
  84. @pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])
  85. def test_unstyle_other_ansi(text, expect):
  86. assert click.unstyle(text) == expect
  87. def test_filename_formatting():
  88. assert click.format_filename(b"foo.txt") == "foo.txt"
  89. assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"
  90. assert click.format_filename("/x/foo.txt") == "/x/foo.txt"
  91. assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"
  92. assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"
  93. def test_prompts(runner):
  94. @click.command()
  95. def test():
  96. if click.confirm("Foo"):
  97. click.echo("yes!")
  98. else:
  99. click.echo("no :(")
  100. result = runner.invoke(test, input="y\n")
  101. assert not result.exception
  102. assert result.output == "Foo [y/N]: y\nyes!\n"
  103. result = runner.invoke(test, input="\n")
  104. assert not result.exception
  105. assert result.output == "Foo [y/N]: \nno :(\n"
  106. result = runner.invoke(test, input="n\n")
  107. assert not result.exception
  108. assert result.output == "Foo [y/N]: n\nno :(\n"
  109. @click.command()
  110. def test_no():
  111. if click.confirm("Foo", default=True):
  112. click.echo("yes!")
  113. else:
  114. click.echo("no :(")
  115. result = runner.invoke(test_no, input="y\n")
  116. assert not result.exception
  117. assert result.output == "Foo [Y/n]: y\nyes!\n"
  118. result = runner.invoke(test_no, input="\n")
  119. assert not result.exception
  120. assert result.output == "Foo [Y/n]: \nyes!\n"
  121. result = runner.invoke(test_no, input="n\n")
  122. assert not result.exception
  123. assert result.output == "Foo [Y/n]: n\nno :(\n"
  124. def test_confirm_repeat(runner):
  125. cli = click.Command(
  126. "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]
  127. )
  128. result = runner.invoke(cli, input="\ny\n")
  129. assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"
  130. @pytest.mark.skipif(WIN, reason="Different behavior on windows.")
  131. def test_prompts_abort(monkeypatch, capsys):
  132. def f(_):
  133. raise KeyboardInterrupt()
  134. monkeypatch.setattr("click.termui.hidden_prompt_func", f)
  135. try:
  136. click.prompt("Password", hide_input=True)
  137. except click.Abort:
  138. click.echo("interrupted")
  139. out, err = capsys.readouterr()
  140. assert out == "Password:\ninterrupted\n"
  141. def _test_gen_func():
  142. yield "a"
  143. yield "b"
  144. yield "c"
  145. yield "abc"
  146. @pytest.mark.skipif(WIN, reason="Different behavior on windows.")
  147. @pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])
  148. @pytest.mark.parametrize(
  149. "test",
  150. [
  151. # We need lambda here, because pytest will
  152. # reuse the parameters, and then the generators
  153. # are already used and will not yield anymore
  154. ("just text\n", lambda: "just text"),
  155. ("iterable\n", lambda: ["itera", "ble"]),
  156. ("abcabc\n", lambda: _test_gen_func),
  157. ("abcabc\n", lambda: _test_gen_func()),
  158. ("012345\n", lambda: (c for c in range(6))),
  159. ],
  160. )
  161. def test_echo_via_pager(monkeypatch, capfd, cat, test):
  162. monkeypatch.setitem(os.environ, "PAGER", cat)
  163. monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)
  164. expected_output = test[0]
  165. test_input = test[1]()
  166. click.echo_via_pager(test_input)
  167. out, err = capfd.readouterr()
  168. assert out == expected_output
  169. @pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")
  170. def test_echo_color_flag(monkeypatch, capfd):
  171. isatty = True
  172. monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)
  173. text = "foo"
  174. styled_text = click.style(text, fg="red")
  175. assert styled_text == "\x1b[31mfoo\x1b[0m"
  176. click.echo(styled_text, color=False)
  177. out, err = capfd.readouterr()
  178. assert out == f"{text}\n"
  179. click.echo(styled_text, color=True)
  180. out, err = capfd.readouterr()
  181. assert out == f"{styled_text}\n"
  182. isatty = True
  183. click.echo(styled_text)
  184. out, err = capfd.readouterr()
  185. assert out == f"{styled_text}\n"
  186. isatty = False
  187. click.echo(styled_text)
  188. out, err = capfd.readouterr()
  189. assert out == f"{text}\n"
  190. def test_prompt_cast_default(capfd, monkeypatch):
  191. monkeypatch.setattr(sys, "stdin", StringIO("\n"))
  192. value = click.prompt("value", default="100", type=int)
  193. capfd.readouterr()
  194. assert type(value) is int
  195. @pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")
  196. def test_echo_writing_to_standard_error(capfd, monkeypatch):
  197. def emulate_input(text):
  198. """Emulate keyboard input."""
  199. monkeypatch.setattr(sys, "stdin", StringIO(text))
  200. click.echo("Echo to standard output")
  201. out, err = capfd.readouterr()
  202. assert out == "Echo to standard output\n"
  203. assert err == ""
  204. click.echo("Echo to standard error", err=True)
  205. out, err = capfd.readouterr()
  206. assert out == ""
  207. assert err == "Echo to standard error\n"
  208. emulate_input("asdlkj\n")
  209. click.prompt("Prompt to stdin")
  210. out, err = capfd.readouterr()
  211. assert out == "Prompt to stdin: "
  212. assert err == ""
  213. emulate_input("asdlkj\n")
  214. click.prompt("Prompt to stderr", err=True)
  215. out, err = capfd.readouterr()
  216. assert out == " "
  217. assert err == "Prompt to stderr:"
  218. emulate_input("y\n")
  219. click.confirm("Prompt to stdin")
  220. out, err = capfd.readouterr()
  221. assert out == "Prompt to stdin [y/N]: "
  222. assert err == ""
  223. emulate_input("y\n")
  224. click.confirm("Prompt to stderr", err=True)
  225. out, err = capfd.readouterr()
  226. assert out == " "
  227. assert err == "Prompt to stderr [y/N]:"
  228. monkeypatch.setattr(click.termui, "isatty", lambda x: True)
  229. monkeypatch.setattr(click.termui, "getchar", lambda: " ")
  230. click.pause("Pause to stdout")
  231. out, err = capfd.readouterr()
  232. assert out == "Pause to stdout\n"
  233. assert err == ""
  234. click.pause("Pause to stderr", err=True)
  235. out, err = capfd.readouterr()
  236. assert out == ""
  237. assert err == "Pause to stderr\n"
  238. def test_echo_with_capsys(capsys):
  239. click.echo("Capture me.")
  240. out, err = capsys.readouterr()
  241. assert out == "Capture me.\n"
  242. def test_open_file(runner):
  243. @click.command()
  244. @click.argument("filename")
  245. def cli(filename):
  246. with click.open_file(filename) as f:
  247. click.echo(f.read())
  248. click.echo("meep")
  249. with runner.isolated_filesystem():
  250. with open("hello.txt", "w") as f:
  251. f.write("Cool stuff")
  252. result = runner.invoke(cli, ["hello.txt"])
  253. assert result.exception is None
  254. assert result.output == "Cool stuff\nmeep\n"
  255. result = runner.invoke(cli, ["-"], input="foobar")
  256. assert result.exception is None
  257. assert result.output == "foobar\nmeep\n"
  258. def test_open_file_pathlib_dash(runner):
  259. @click.command()
  260. @click.argument(
  261. "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)
  262. )
  263. def cli(filename):
  264. click.echo(str(type(filename)))
  265. with click.open_file(filename) as f:
  266. click.echo(f.read())
  267. result = runner.invoke(cli, ["-"], input="value")
  268. assert result.exception is None
  269. assert result.output == "pathlib.Path\nvalue\n"
  270. def test_open_file_ignore_errors_stdin(runner):
  271. @click.command()
  272. @click.argument("filename")
  273. def cli(filename):
  274. with click.open_file(filename, errors="ignore") as f:
  275. click.echo(f.read())
  276. result = runner.invoke(cli, ["-"], input=os.urandom(16))
  277. assert result.exception is None
  278. def test_open_file_respects_ignore(runner):
  279. with runner.isolated_filesystem():
  280. with open("test.txt", "w") as f:
  281. f.write("Hello world!")
  282. with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:
  283. assert f.errors == "ignore"
  284. def test_open_file_ignore_invalid_utf8(runner):
  285. with runner.isolated_filesystem():
  286. with open("test.txt", "wb") as f:
  287. f.write(b"\xe2\x28\xa1")
  288. with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:
  289. f.read()
  290. def test_open_file_ignore_no_encoding(runner):
  291. with runner.isolated_filesystem():
  292. with open("test.bin", "wb") as f:
  293. f.write(os.urandom(16))
  294. with click.open_file("test.bin", errors="ignore") as f:
  295. f.read()
  296. @pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")
  297. @pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])
  298. def test_open_file_atomic_permissions_existing_file(runner, permissions):
  299. with runner.isolated_filesystem():
  300. with open("existing.txt", "w") as f:
  301. f.write("content")
  302. os.chmod("existing.txt", permissions)
  303. @click.command()
  304. @click.argument("filename")
  305. def cli(filename):
  306. click.open_file(filename, "w", atomic=True).close()
  307. result = runner.invoke(cli, ["existing.txt"])
  308. assert result.exception is None
  309. assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions
  310. @pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")
  311. def test_open_file_atomic_permissions_new_file(runner):
  312. with runner.isolated_filesystem():
  313. @click.command()
  314. @click.argument("filename")
  315. def cli(filename):
  316. click.open_file(filename, "w", atomic=True).close()
  317. # Create a test file to get the expected permissions for new files
  318. # according to the current umask.
  319. with open("test.txt", "w"):
  320. pass
  321. permissions = stat.S_IMODE(os.stat("test.txt").st_mode)
  322. result = runner.invoke(cli, ["new.txt"])
  323. assert result.exception is None
  324. assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions
  325. def test_iter_keepopenfile(tmpdir):
  326. expected = list(map(str, range(10)))
  327. p = tmpdir.mkdir("testdir").join("testfile")
  328. p.write("\n".join(expected))
  329. with p.open() as f:
  330. for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):
  331. assert e_line == a_line.strip()
  332. def test_iter_lazyfile(tmpdir):
  333. expected = list(map(str, range(10)))
  334. p = tmpdir.mkdir("testdir").join("testfile")
  335. p.write("\n".join(expected))
  336. with p.open() as f:
  337. with click.utils.LazyFile(f.name) as lf:
  338. for e_line, a_line in zip(expected, lf):
  339. assert e_line == a_line.strip()
  340. class MockMain:
  341. __slots__ = "__package__"
  342. def __init__(self, package_name):
  343. self.__package__ = package_name
  344. @pytest.mark.parametrize(
  345. ("path", "main", "expected"),
  346. [
  347. ("example.py", None, "example.py"),
  348. (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),
  349. ("example", None, "example"),
  350. (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),
  351. (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),
  352. (str(pathlib.Path("./example")), "", "example"),
  353. ],
  354. )
  355. def test_detect_program_name(path, main, expected):
  356. assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected
  357. def test_expand_args(monkeypatch):
  358. user = os.path.expanduser("~")
  359. assert user in click.utils._expand_args(["~"])
  360. monkeypatch.setenv("CLICK_TEST", "hello")
  361. assert "hello" in click.utils._expand_args(["$CLICK_TEST"])
  362. #assert "setup.cfg" in click.utils._expand_args(["*.cfg"])
  363. #assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])
  364. assert "*.not-found" in click.utils._expand_args(["*.not-found"])
  365. # a bad glob pattern, such as a pytest identifier, should return itself
  366. assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"
  367. @pytest.mark.parametrize(
  368. ("value", "max_length", "expect"),
  369. [
  370. pytest.param("", 10, "", id="empty"),
  371. pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),
  372. pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),
  373. pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),
  374. pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),
  375. pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),
  376. pytest.param(
  377. "token in ~/.netrc ciao ciao",
  378. 20,
  379. "token in ~/.netrc...",
  380. id="ignore dot in word",
  381. ),
  382. ],
  383. )
  384. @pytest.mark.parametrize(
  385. "alter",
  386. [
  387. pytest.param(None, id=""),
  388. pytest.param(
  389. lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"
  390. ),
  391. ],
  392. )
  393. def test_make_default_short_help(value, max_length, alter, expect):
  394. assert len(expect) <= max_length
  395. if alter:
  396. value = alter(value)
  397. out = click.utils.make_default_short_help(value, max_length)
  398. assert out == expect