Skip to content
Myr

Merge branch 'stable' into docs/breifcase-click-standalone-app

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by John Aziz · committed by GitHub · parents b0cab0e, 878de46 · Browse files · 17 files+718 added−252 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+718 added−252 removed

  • tests:+301 added−9 removed
  • other:+417 added−243 removed

17 files+718 added−252 removed

added:docs/arguments.md+166 added
1(arguments)=23# Arguments45```{currentmodule} click6```78Arguments are:910* Are positional in nature.11* Similar to a limited version of {ref}`options <options>` that can take an arbitrary number of inputs12* {ref}`Documented manually <documenting-arguments>`.1314Useful and often used kwargs are:1516* `default`: Passes a default.17* `nargs`: Sets the number of arguments. Set to -1 to take an arbitrary number.1819## Basic Arguments2021A minimal {class}`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type `str`.2223Example:2425```{eval-rst}26.. click:example::2728 @click.command()29 @click.argument('filename')30 def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)3334And from the command line:3536.. click:run::3738 invoke(touch, args=['foo.txt'])39```4041An argument may be assigned a {ref}`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be {data}`STRING`.4243```{admonition} Note on Required Arguments44:class: note4546 It is possible to make an argument required by setting `required=True`. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.47```4849## Multiple Arguments5051To set the number of argument use the `nargs` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.5253```{eval-rst}54.. click:example::5556 @click.command()57 @click.argument('src', nargs=1)58 @click.argument('dsts', nargs=-1)59 def copy(src: str, dsts: tuple[str, ...]):60 """Move file SRC to DST."""61 for destination in dsts:62 click.echo(f"Copy {src} to folder {destination}")6364And from the command line:6566.. click:run::6768 invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])69```7071```{admonition} Note on Handling Files72:class: note7374 This is not how you should handle files and files paths. This merely used as a simple example. See {ref}`handling-files` to learn more about how to handle files in parameters.75```7677## Argument Escape Sequences7879If you want to process arguments that look like options, like a file named `-foo.txt` or `--foo.txt` , you must pass the `--` separator first. After you pass the `--`, you may only pass arguments. This is a common feature for POSIX command line tools.8081Example usage:8283```{eval-rst}84.. click:example::8586 @click.command()87 @click.argument('files', nargs=-1, type=click.Path())88 def touch(files):89 """Print all FILES file names."""90 for filename in files:91 click.echo(filename)9293And from the command line:9495.. click:run::9697 invoke(touch, ['--', '-foo.txt', 'bar.txt'])98```99100If you don't like the `--` marker, you can set ignore_unknown_options to True to avoid checking unknown options:101102```{eval-rst}103.. click:example::104105 @click.command(context_settings={"ignore_unknown_options": True})106 @click.argument('files', nargs=-1, type=click.Path())107 def touch(files):108 """Print all FILES file names."""109 for filename in files:110 click.echo(filename)111112And from the command line:113114.. click:run::115116 invoke(touch, ['-foo.txt', 'bar.txt'])117```118119(environment-variables)=120121## Environment Variables122123Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in `click.argument`.124125Checking one environment variable:126127```{eval-rst}128.. click:example::129130 @click.command()131 @click.argument('src', envvar='SRC', type=click.File('r'))132 def echo(src):133 """Print value of SRC environment variable."""134 click.echo(src.read())135136And from the command line:137138.. click:run::139140 with isolated_filesystem():141 # Writing the file in the filesystem.142 with open('hello.txt', 'w') as f:143 f.write('Hello World!')144 invoke(echo, env={'SRC': 'hello.txt'})145146147Checking multiple environment variables:148149.. click:example::150151 @click.command()152 @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))153 def echo(src):154 """Print value of SRC environment variable."""155 click.echo(src.read())156157And from the command line:158159.. click:run::160161 with isolated_filesystem():162 # Writing the file in the filesystem.163 with open('hello.txt', 'w') as f:164 f.write('Hello World from second variable!')165 invoke(echo, env={'SRC_2': 'hello.txt'})166```
deleted:docs/arguments.rst-158 removed
1.. _arguments:23Arguments4=========56.. currentmodule:: click78Arguments are:910* Are positional in nature.11* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs12* :ref:`Documented manually <documenting-arguments>`.1314Useful and often used kwargs are:1516* ``default``: Passes a default.17* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.1819Basic Arguments20---------------2122A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``.2324Example:2526.. click:example::2728 @click.command()29 @click.argument('filename')30 def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)3334And from the command line:3536.. click:run::3738 invoke(touch, args=['foo.txt'])394041An argument may be assigned a :ref:`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`.4243.. admonition:: Note on Required Arguments4445 It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.4647Multiple Arguments48-----------------------------------4950To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.5152.. click:example::5354 @click.command()55 @click.argument('src', nargs=1)56 @click.argument('dsts', nargs=-1)57 def copy(src: str, dsts: tuple[str, ...]):58 """Move file SRC to DST."""59 for destination in dsts:60 click.echo(f"Copy {src} to folder {destination}")6162And from the command line:6364.. click:run::6566 invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])6768.. admonition:: Note on Handling Files6970 This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters.7172Argument Escape Sequences73---------------------------7475If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools.7677Example usage:7879.. click:example::8081 @click.command()82 @click.argument('files', nargs=-1, type=click.Path())83 def touch(files):84 """Print all FILES file names."""85 for filename in files:86 click.echo(filename)8788And from the command line:8990.. click:run::9192 invoke(touch, ['--', '-foo.txt', 'bar.txt'])9394If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:9596.. click:example::9798 @click.command(context_settings={"ignore_unknown_options": True})99 @click.argument('files', nargs=-1, type=click.Path())100 def touch(files):101 """Print all FILES file names."""102 for filename in files:103 click.echo(filename)104105And from the command line:106107.. click:run::108109 invoke(touch, ['-foo.txt', 'bar.txt'])110111112.. _environment-variables:113114Environment Variables115---------------------116117Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118119Checking one environment variable:120121.. click:example::122123 @click.command()124 @click.argument('src', envvar='SRC', type=click.File('r'))125 def echo(src):126 """Print value of SRC environment variable."""127 click.echo(src.read())128129And from the command line:130131.. click:run::132133 with isolated_filesystem():134 # Writing the file in the filesystem.135 with open('hello.txt', 'w') as f:136 f.write('Hello World!')137 invoke(echo, env={'SRC': 'hello.txt'})138139140Checking multiple environment variables:141142.. click:example::143144 @click.command()145 @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))146 def echo(src):147 """Print value of SRC environment variable."""148 click.echo(src.read())149150And from the command line:151152.. click:run::153154 with isolated_filesystem():155 # Writing the file in the filesystem.156 with open('hello.txt', 'w') as f:157 f.write('Hello World from second variable!')158 invoke(echo, env={'SRC_2': 'hello.txt'})
added:docs/click-concepts.md+68 added
deleted:docs/click-concepts.rst-67 removed
1Click Concepts2================34This section covers concepts about Click's design.56.. contents::7 :depth: 18 :local:910.. _callback-evaluation-order:1112Callback Evaluation Order13-------------------------1415Click works a bit differently than some other command line parsers in that16it attempts to reconcile the order of arguments as defined by the17programmer with the order of arguments as defined by the user before18invoking any callbacks.1920This is an important concept to understand when porting complex21patterns to Click from optparse or other systems. A parameter22callback invocation in optparse happens as part of the parsing step,23whereas a callback invocation in Click happens after the parsing.2425The main difference is that in optparse, callbacks are invoked with the raw26value as it happens, whereas a callback in Click is invoked after the27value has been fully converted.2829Generally, the order of invocation is driven by the order in which the user30provides the arguments to the script; if there is an option called ``--foo``31and an option called ``--bar`` and the user calls it as ``--bar32--foo``, then the callback for ``bar`` will fire before the one for ``foo``.3334There are three exceptions to this rule which are important to know:3536Eagerness:37 An option can be set to be "eager". All eager parameters are38 evaluated before all non-eager parameters, but again in the order as39 they were provided on the command line by the user.4041 This is important for parameters that execute and exit like ``--help``42 and ``--version``. Both are eager parameters, but whatever parameter43 comes first on the command line will win and exit the program.4445Repeated parameters:46 If an option or argument is split up on the command line into multiple47 places because it is repeated -- for instance, ``--exclude foo --include48 baz --exclude bar`` -- the callback will fire based on the position of49 the first option. In this case, the callback will fire for50 ``exclude`` and it will be passed both options (``foo`` and51 ``bar``), then the callback for ``include`` will fire with ``baz``52 only.5354 Note that even if a parameter does not allow multiple versions, Click55 will still accept the position of the first, but it will ignore every56 value except the last. The reason for this is to allow composability57 through shell aliases that set defaults.5859Missing parameters:60 If a parameter is not defined on the command line, the callback will61 still fire. This is different from how it works in optparse where62 undefined values do not fire the callback. Missing parameters fire63 their callbacks at the very end which makes it possible for them to64 default to values from a parameter that came before.6566Most of the time you do not need to be concerned about any of this,67but it is important to know how it works for some advanced cases.
added:docs/contributing.md+21 added
modified:docs/index.rst+1 added-2 removed
132 unmodified lines
133* This documentation is structured according to `Diataxis <https://diataxis.fr/>`_ and written with `MyST <https://myst-parser.readthedocs.io/en/latest/>`_134135* `Version Policy <https://palletsprojects.com/versions>`_136137* `Contributing <https://palletsprojects.com/contributing/>`_138137* `Donate <https://palletsprojects.com/donate>`_138139.. toctree::140 :maxdepth: 1141142 contributing143 contrib144 license145 changes
modified:src/click/_termui_impl.py+32 added-13 removed
376 unmodified lines
377378 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)380381 # Split and normalize the pager command into parts.382 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False)381 # Split using POSIX mode (the default) so that quote characters are382 # stripped from tokens and quoted Windows paths are preserved.383 # posix=False was rejected (PR #1477) because it retains quotes in384 # tokens, and the shlex.quote approach was also reverted (PR #1543).385 # See also: issue #1026, PR #2775.386 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))387 if pager_cmd_parts:388 if WIN:389 if _tempfilepager(generator, pager_cmd_parts, color):390 return
23 unmodified lines
414415def _pipepager(416 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None417) -> bool:414 """Page through text by feeding it to another program. Invoking a415 pager through this might support colors.418 """Page through text by feeding it to another program.419417 Returns `True` if the command was found, `False` otherwise and thus another418 pager should be attempted.420 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list421 produced by :func:`shlex.split`. The command is resolved to an absolute422 path with :func:`shutil.which` as recommended by the423 :mod:`subprocess` docs for Windows compatibility.424425 Invoking a pager through this might support colors: if piping to426 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set427 automatically.428429 Returns ``True`` if the command was found and executed, ``False``430 otherwise so another pager can be attempted.431 """432 # Split the command into the invoked CLI and its parameters.433 if not cmd_parts:434 return False
85 unmodified lines
520 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None521) -> bool:522 """Page through text by invoking a program on a temporary file.523512 Returns `True` if the command was found, `False` otherwise and thus another513 pager should be attempted.524 Used as the primary pager strategy on Windows (where piping to525 ``more`` adds spurious ``\\r\\n``), and as a fallback on other526 platforms. The command is resolved to an absolute path with527 :func:`shutil.which`.528529 Returns ``True`` if the command was found and executed, ``False``530 otherwise so another pager can be attempted.531 """532 # Split the command into the invoked CLI and its parameters.533 if not cmd_parts:534 return False
73 unmodified lines
608 return editor609 return "vi"610611 def edit_files(self, filenames: cabc.Iterable[str]) -> None:612 """Open files in the user's editor."""613 import shlex614 import subprocess615616 editor = self.get_editor()617 environ: dict[str, str] | None = None
1 unmodified line
619 if self.env:620 environ = os.environ.copy()621 environ.update(self.env)622604 exc_filename = " ".join(f'"{filename}"' for filename in filenames)605623 try:624 # Split in POSIX mode (the default) for the same reasons as625 # in pager(): strips quotes from tokens and preserves quoted626 # Windows paths. See issue #1026, PR #1477.627 c = subprocess.Popen(608 args=f"{editor} {exc_filename}", env=environ, shell=True628 args=shlex.split(editor) + list(filenames),629 env=environ,630 )631 exit_code = c.wait()632 if exit_code != 0:633 raise ClickException(
140 unmodified lines
774775 if ch == "\x1a" and WIN: # Windows, Ctrl+Z776 raise EOFError()777757 return None778759779if sys.platform == "win32":780 import msvcrt781782 @contextlib.contextmanager
89 unmodified lines
modified:src/click/core.py+1 added-1 removed
3108 unmodified lines
3109 (self.opts if default_value else self.secondary_opts)[0]3110 )[1]3111 elif self.is_bool_flag and not self.secondary_opts and not default_value:3112 default_string = ""3113 elif default_value == "":3113 elif isinstance(default_value, str) and default_value == "":3114 default_string = '""'3115 else:3116 default_string = str(default_value)3117
320 unmodified lines
modified:src/click/testing.py+45 added
2 unmodified lines
3import collections.abc as cabc4import contextlib5import io6import os7import pdb8import shlex9import sys10import tempfile11import typing as t
378 unmodified lines
390 old_hidden_prompt_func = termui.hidden_prompt_func391 old__getchar_func = termui._getchar392 old_should_strip_ansi = utils.should_strip_ansi # type: ignore393 old__compat_should_strip_ansi = _compat.should_strip_ansi394 old_pdb_init = pdb.Pdb.__init__395 termui.visible_prompt_func = visible_input396 termui.hidden_prompt_func = hidden_input397 termui._getchar = _getchar398 utils.should_strip_ansi = should_strip_ansi # type: ignore399 _compat.should_strip_ansi = should_strip_ansi400401 def _patched_pdb_init(402 self: pdb.Pdb,403 completekey: str = "tab",404 stdin: t.IO[str] | None = None,405 stdout: t.IO[str] | None = None,406 **kwargs: t.Any,407 ) -> None:408 """Default ``pdb.Pdb`` to real terminal streams during409 ``CliRunner`` isolation.410411 Without this patch, ``pdb.Pdb.__init__`` inherits from412 ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout``413 when no explicit streams are provided. During isolation414 those are ``BytesIO``-backed wrappers, so the debugger415 reads from an empty buffer and writes to captured output,416 making interactive debugging impossible.417418 By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the419 original terminal streams Python preserves regardless of420 redirection), debuggers can interact with the user while421 ``click.echo`` output is still captured normally.422423 This covers ``pdb.set_trace()``, ``breakpoint()``,424 ``pdb.post_mortem()``, and debuggers that subclass425 ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``426 arguments are honored and not overridden. Debuggers that427 do not subclass ``pdb.Pdb`` (pudb, debugpy) are not428 covered.429430 See: https://github.com/pallets/click/issues/654 and431 https://github.com/pallets/click/issues/824432 """433 if stdin is None:434 stdin = sys.__stdin__435 if stdout is None:436 stdout = sys.__stdout__437 old_pdb_init(438 self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs439 )440441 pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]442443 old_env = {}444 try:445 for key, value in env.items():446 old_env[key] = os.environ.get(key)
22 unmodified lines
469 termui._getchar = old__getchar_func470 utils.should_strip_ansi = old_should_strip_ansi # type: ignore471 _compat.should_strip_ansi = old__compat_should_strip_ansi472 formatting.FORCED_WIDTH = old_forced_width473 pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign]474475 def invoke(476 self,477 cli: Command,
142 unmodified lines
modified:tests/test_options.py+28 added-4 removed
1257 unmodified lines
1258 message = opt.get_help_record(ctx)[1]1259 assert "[default: (unlimited)]" in message126012611262def test_show_default_with_empty_string(runner):1263 """When show_default is True and default is set to an empty string."""1264 opt = click.Option(["--limit"], default="", show_default=True)1262class _StrictEq:1263 """Object whose ``__eq__`` raises on string comparison (like semver.Version)."""12641265 def __eq__(self, other):1266 if isinstance(other, str):1267 raise ValueError("cannot compare to string")1268 return NotImplemented12691270 def __str__(self):1271 return "strict"127212731274@pytest.mark.parametrize(1275 ("default", "expected"),1276 [1277 ("", '[default: ""]'),1278 (_StrictEq(), "[default: strict]"),1279 ],1280 ids=["empty-string", "non-string-comparable-object"],1281)1282def test_show_default_with_empty_string(runner, default, expected):1283 """The empty-string check in help rendering must not break on objects1284 whose ``__eq__`` raises for string operands.12851286 Regression test for https://github.com/pallets/click/issues/3298.1287 """1288 opt = click.Option(["--limit"], default=default, show_default=True)1289 ctx = click.Context(click.Command("cli"))1290 message = opt.get_help_record(ctx)[1]1267 assert '[default: ""]' in message1291 assert expected in message129212931294def test_do_not_show_no_default(runner):1295 """When show_default is True and no default is set do not show None."""
1232 unmodified lines
modified:tests/test_termui.py+221 added
1import platform2import shlex3import tempfile4import time5from unittest.mock import patch67import pytest89import click._termui_impl10from click._compat import WIN11from click._termui_impl import Editor12from click.exceptions import BadParameter13from click.exceptions import MissingParameter1415
391 unmodified lines
407 assert reopened_file.read() == "aTest\nbTest\n"408409410@pytest.mark.parametrize(411 ("editor_cmd", "filenames", "expected_args"),412 [413 pytest.param(414 "myeditor --wait --flag",415 ["file1.txt", "file2.txt"],416 ["myeditor", "--wait", "--flag", "file1.txt", "file2.txt"],417 id="editor with args",418 ),419 pytest.param(420 "vi",421 ['file"; rm -rf / ; echo "'],422 ["vi", 'file"; rm -rf / ; echo "'],423 id="shell metacharacters in filename",424 ),425 # Issue #1026: editor path with spaces must be quoted.426 pytest.param(427 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',428 ["f.txt"],429 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],430 id="quoted windows path with spaces",431 ),432 # PR #1477: pager/editor command with flags, like ``less -FRSX``.433 pytest.param(434 "less -FRSX",435 ["f.txt"],436 ["less", "-FRSX", "f.txt"],437 id="command with flags",438 ),439 # Issue #1026: quoted command with ``--wait`` flag.440 pytest.param(441 '"my command" --option value arg',442 ["f.txt"],443 ["my command", "--option", "value", "arg", "f.txt"],444 id="quoted command with args",445 ),446 # PR #1477: unquoted unix path.447 pytest.param(448 "/usr/bin/vim",449 ["f.txt"],450 ["/usr/bin/vim", "f.txt"],451 id="unix absolute path",452 ),453 # Issue #1026: macOS path with escaped space.454 pytest.param(455 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",456 ["f.txt"],457 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],458 id="escaped space in unix path",459 ),460 pytest.param(461 " vim ",462 ["f.txt"],463 ["vim", "f.txt"],464 id="leading and trailing whitespace",465 ),466 pytest.param(467 "vim\tf.txt",468 [],469 ["vim", "f.txt"],470 id="tab-separated tokens",471 ),472 pytest.param(473 "'/Applications/My Editor.app/Contents/MacOS/editor'",474 ["f.txt"],475 ["/Applications/My Editor.app/Contents/MacOS/editor", "f.txt"],476 id="single-quoted path with spaces",477 ),478 pytest.param(479 '"my editor" --wait --new-window',480 ["file 1.txt", "file 2.txt"],481 ["my editor", "--wait", "--new-window", "file 1.txt", "file 2.txt"],482 id="quoted editor with multiple flags and filenames with spaces",483 ),484 pytest.param(485 "vim -u NONE -N",486 ["f.txt"],487 ["vim", "-u", "NONE", "-N", "f.txt"],488 id="multiple short flags",489 ),490 pytest.param(491 "editor",492 ['file"name.txt'],493 ["editor", 'file"name.txt'],494 id="filename with double quote",495 ),496 pytest.param(497 "editor",498 ["file'name.txt"],499 ["editor", "file'name.txt"],500 id="filename with single quote",501 ),502 ],503)504def test_editor_path_normalization(editor_cmd, filenames, expected_args):505 with patch("subprocess.Popen") as mock_popen:506 mock_popen.return_value.wait.return_value = 0507 Editor(editor=editor_cmd).edit_files(filenames)508509 mock_popen.assert_called_once()510 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]511 assert args == expected_args512 assert mock_popen.call_args[1].get("shell") is None513514515@pytest.mark.skipif(not WIN, reason="Windows-specific editor paths")516@pytest.mark.parametrize(517 ("editor_cmd", "expected_cmd"),518 [519 pytest.param(520 "notepad",521 ["notepad"],522 id="plain notepad",523 ),524 pytest.param(525 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe" --wait',526 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "--wait"],527 id="quoted path with flag",528 ),529 ],530)531def test_editor_windows_path_normalization(editor_cmd, expected_cmd):532 """Windows-specific tests: verify ``Popen`` receives unquoted paths that533 ``subprocess.list2cmdline`` can re-quote for ``CreateProcess``."""534 with patch("subprocess.Popen") as mock_popen:535 mock_popen.return_value.wait.return_value = 0536 Editor(editor=editor_cmd).edit_files(["f.txt"])537538 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]539 assert args == expected_cmd + ["f.txt"]540 assert mock_popen.call_args[1].get("shell") is None541542543def test_editor_env_passed_through():544 with patch("subprocess.Popen") as mock_popen:545 mock_popen.return_value.wait.return_value = 0546 Editor(editor="vi", env={"MY_VAR": "1"}).edit_files(["f.txt"])547548 env = mock_popen.call_args[1].get("env")549 assert env is not None550 assert env["MY_VAR"] == "1"551552553def test_editor_failure_exception():554 with patch("subprocess.Popen") as mock_popen:555 mock_popen.return_value.wait.return_value = 1556 with pytest.raises(click.ClickException, match="Editing failed"):557 Editor(editor="vi").edit_files(["f.txt"])558559560def test_editor_nonexistent_exception():561 with patch("subprocess.Popen", side_effect=OSError("not found")):562 with pytest.raises(click.ClickException, match="not found"):563 Editor(editor="nonexistent").edit_files(["f.txt"])564565566@pytest.mark.parametrize(567 ("pager_env", "expected_parts"),568 [569 # Simple commands.570 pytest.param("cat", ["cat"], id="simple command"),571 pytest.param("less", ["less"], id="less"),572 pytest.param("less -FRSX", ["less", "-FRSX"], id="command with flags"),573 # Whitespace handling.574 pytest.param("", [], id="empty string"),575 pytest.param(" ", [], id="whitespace only"),576 pytest.param(" less ", ["less"], id="leading and trailing spaces"),577 pytest.param("less\t-R", ["less", "-R"], id="tab as separator"),578 # Quoted Windows paths: quotes are stripped in POSIX mode (the579 # default), preserving backslashes inside quoted tokens (issue #1026).580 pytest.param(581 '"C:\\Program Files\\Git\\usr\\bin\\less.exe"',582 ["C:\\Program Files\\Git\\usr\\bin\\less.exe"],583 id="quoted windows path with spaces",584 ),585 pytest.param(586 '"C:\\Program Files\\Git\\usr\\bin\\less.exe" -R',587 ["C:\\Program Files\\Git\\usr\\bin\\less.exe", "-R"],588 id="quoted windows path with flag",589 ),590 # Single-quoted path.591 pytest.param(592 "'/usr/local/bin/my pager'",593 ["/usr/local/bin/my pager"],594 id="single-quoted path with spaces",595 ),596 # Unix paths.597 pytest.param("/usr/bin/less", ["/usr/bin/less"], id="unix absolute path"),598 pytest.param(599 "/usr/bin/my\\ pager",600 ["/usr/bin/my pager"],601 id="escaped space in unix path",602 ),603 # PR #1477: POSIX mode (the default) eats unquoted backslashes.604 # On Windows, users must quote paths that contain backslashes.605 pytest.param(606 "C:\\path\\to\\exe /test other\\path",607 ["C:pathtoexe", "/test", "otherpath"],608 id="unquoted backslashes eaten in POSIX mode",609 ),610 ],611)612def test_pager_shlex_split(pager_env, expected_parts):613 """Verify shlex.split produces the expected argv for PAGER values.614615 Tests the splitting logic used by :func:`click._termui_impl.pager` to616 turn the ``PAGER`` environment variable into an ``argv`` list. See617 issue #1026, PR #1477, PR #1543, PR #2775.618 """619 assert shlex.split(pager_env) == expected_parts620621622def test_editor_unclosed_quote():623 """An unclosed quote in the editor command raises ValueError."""624 with pytest.raises(ValueError, match="No closing quotation"):625 Editor(editor='"unclosed').edit_files(["f.txt"])626627628@pytest.mark.parametrize(629 ("prompt_required", "required", "args", "expect"),630 [631 (True, False, None, "prompt"),632 (True, False, ["-v"], "Option '-v' requires an argument."),
301 unmodified lines
modified:tests/test_testing.py+50 added
1import os2import pdb3import sys4from io import BytesIO56import pytest
462 unmodified lines
469 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)470471 result = runner.invoke(cli)472 assert result.stderr == "gyarados gyarados gyarados"473474475def test_pdb_uses_real_streams():476 """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams477 so that interactive debuggers work instead of reading from the478 captured ``BytesIO`` stdin.479 """480481 @click.command()482 def cli():483 debugger = pdb.Pdb()484 assert debugger.stdin is sys.__stdin__485 assert debugger.stdout is sys.__stdout__486 click.echo("after debugger")487488 runner = CliRunner()489 result = runner.invoke(cli, catch_exceptions=False)490 assert result.output == "after debugger\n"491492493def test_pdb_explicit_streams_honored():494 """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not495 overridden by the ``CliRunner`` patch.496 """497498 @click.command()499 def cli():500 custom_in = sys.stdin501 custom_out = sys.stdout502 debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)503 assert debugger.stdin is custom_in504 assert debugger.stdout is custom_out505506 runner = CliRunner()507 runner.invoke(cli, catch_exceptions=False)508509510def test_pdb_init_restored_after_invoke():511 """``pdb.Pdb.__init__`` is restored to its original after invoke."""512 original = pdb.Pdb.__init__513514 @click.command()515 def cli():516 pass517518 runner = CliRunner()519 runner.invoke(cli)520521 assert pdb.Pdb.__init__ is original
modified:tests/test_utils.py+2 added-5 removed
7 unmodified lines
8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import StringIO12from pathlib import Path13from tempfile import tempdir12from unittest.mock import patch1314import pytest15
360 unmodified lines
376 expected_error=None,377 ),378 ],379)382def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):380def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):381 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)382 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)383384 test_input = test.test_input()
3 unmodified lines
388 expected_error = test.expected_error389390 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()391394 pager_out_tmp = Path(tempdir) / "pager_out.txt"395 pager_out_tmp.unlink(missing_ok=True)392 pager_out_tmp = tmp_path / "pager_out.txt"393 with pager_out_tmp.open("w") as f:394 force_subprocess_stdout = patch.object(395 subprocess,396 "Popen",
349 unmodified lines
modified:.pre-commit-config.yaml+1 added
11 unmodified lines
12 rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.013 hooks:14 - id: check-merge-conflict15 - id: debug-statements16 exclude: ^(src/click/testing\.py|tests/test_testing\.py)$17 - id: fix-byte-order-marker18 - id: trailing-whitespace19 - id: end-of-file-fixer
modified:CHANGES.rst+24 added-2 removed
1.. currentmodule:: click23Version 8.3.34-------------56Unreleased78- Use :func:`shlex.split` to split pager and editor commands into ``argv``9 lists for :class:`subprocess.Popen`, removing ``shell=True``.10 :issue:`1026` :pr:`1477` :pr:`2775`11- Fix ``TypeError`` when rendering help for an option whose default value is12 an object that doesn't support equality comparison with strings, such as13 ``semver.Version``. :issue:`3298` :pr:`3299`14- Fix pager test pollution under parallel execution by using pytest's15 ``tmp_path`` fixture instead of a shared temporary file path. :pr:`3238`16- Patch ``pdb.Pdb`` in ``CliRunner`` isolation so ``pdb.set_trace()``,17 ``breakpoint()``, and debuggers subclassing ``pdb.Pdb`` (ipdb, pdbpp) can18 interact with the real terminal instead of the captured I/O streams.19 :issue:`654` :issue:`824` :issue:`843` :pr:`951` :pr:`3235`20- Add optional randomized parallel test execution using ``pytest-randomly`` and21 ``pytest-xdist`` to detect test pollution and race conditions. :pr:`3151`22- Add contributor documentation for running stress tests, randomized23 parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`2425Version 8.3.24--------------26-------------2728Released 2026-04-022930- Fix handling of ``flag_value`` when ``is_flag=False`` to allow such options to be
9 unmodified lines
40- Fix callable ``flag_value`` being instantiated when used as a default via41 ``default=True``. :issue:`3121` :pr:`3201` :pr:`3213` :pr:`3225`4243Version 8.3.122--------------44-------------4546Released 2025-11-154748- Don't discard pager arguments by correctly using ``subprocess.Popen``. :issue:`3039`
1302 unmodified lines
modified:pyproject.toml+14 added
49 unmodified lines
50]51tests = [52 "pytest",53]54tests-random = [55 "pytest",56 "pytest-randomly",57 "pytest-xdist",58]59typing = [60 "mypy",61 "pyright",62 "pytest",
106 unmodified lines
169 "pytest", "-v", "--tb=short", "--basetemp={env_tmp_dir}",170 {replace = "posargs", default = [], extend = true},171]]172173[tool.tox.env.random]174description = "randomized parallel tests to detect test pollution and race conditions"175dependency_groups = ["tests-random"]176commands = [[177 "pytest", "-v", "--tb=short", "--numprocesses=auto",178 "--basetemp={env_tmp_dir}",179 {replace = "posargs", default = [], extend = true},180]]181182[tool.tox.env.stress]183description = "stress tests for stream lifecycle race conditions"184commands = [[185 "pytest", "-v", "--tb=short", "-x", "-m", "stress",
51 unmodified lines
modified:uv.lock+44 added
207 unmodified lines
208]209tests = [210 { name = "pytest" },211]212tests-random = [213 { name = "pytest" },214 { name = "pytest-randomly" },215 { name = "pytest-xdist" },216]217typing = [218 { name = "mypy" },219 { name = "pyright" },220 { name = "pytest" },
21 unmodified lines
242 { name = "pre-commit" },243 { name = "pre-commit-uv" },244]245tests = [{ name = "pytest" }]246tests-random = [247 { name = "pytest" },248 { name = "pytest-randomly" },249 { name = "pytest-xdist" },250]251typing = [252 { name = "mypy" },253 { name = "pyright" },254 { name = "pytest" },
54 unmodified lines
309 { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },310]311312[[package]]313name = "execnet"314version = "2.1.2"315source = { registry = "https://pypi.org/simple" }316sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" }317wheels = [318 { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" },319]320321[[package]]322name = "filelock"323version = "3.25.2"324source = { registry = "https://pypi.org/simple" }325sdist = { url = "https://files.pythonhosted.org/packages/94/b8/00651a0f559862f3bb7d6f7477b192afe3f583cc5e26403b44e59a55ab34/filelock-3.25.2.tar.gz", hash = "sha256:b64ece2b38f4ca29dd3e810287aa8c48182bbecd1ae6e9ae126c9b35f1382694", size = 40480, upload-time = "2026-03-11T20:45:38.487Z" }
587 unmodified lines
913 { url = "https://files.pythonhosted.org/packages/67/0f/019d3949a40280f6193b62bc010177d4ce702d0fce424322286488569cd3/python_discovery-1.2.1-py3-none-any.whl", hash = "sha256:b6a957b24c1cd79252484d3566d1b49527581d46e789aaf43181005e56201502", size = 31674, upload-time = "2026-03-26T22:30:43.396Z" },914]915916[[package]]917name = "pytest-randomly"918version = "4.0.1"919source = { registry = "https://pypi.org/simple" }920dependencies = [921 { name = "pytest" },922]923sdist = { url = "https://files.pythonhosted.org/packages/c4/1d/258a4bf1109258c00c35043f40433be5c16647387b6e7cd5582d638c116b/pytest_randomly-4.0.1.tar.gz", hash = "sha256:174e57bb12ac2c26f3578188490bd333f0e80620c3f47340158a86eca0593cd8", size = 14130, upload-time = "2025-09-12T15:23:00.085Z" }924wheels = [925 { url = "https://files.pythonhosted.org/packages/33/3e/a4a9227807b56869790aad3e24472a554b585974fe7e551ea350f50897ae/pytest_randomly-4.0.1-py3-none-any.whl", hash = "sha256:e0dfad2fd4f35e07beff1e47c17fbafcf98f9bf4531fd369d9260e2f858bfcb7", size = 8304, upload-time = "2025-09-12T15:22:58.946Z" },926]927928[[package]]929name = "pytest-xdist"930version = "3.8.0"931source = { registry = "https://pypi.org/simple" }932dependencies = [933 { name = "execnet" },934 { name = "pytest" },935]936sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" }937wheels = [938 { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" },939]940941[[package]]942name = "pyyaml"943version = "6.0.3"944source = { registry = "https://pypi.org/simple" }945sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
720 unmodified lines