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
Provenance
- Commit
3da1f43- Tree
90a8f14- Author
John Aziz <johnaziz269@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
b0cab0e- Parent 2
878de46
17 files changed+718 added−252 removed
added:docs/arguments.md+166 added
1+(arguments)=2+3+# Arguments4+5+```{currentmodule} click6+```7+8+Arguments are:9+10+* 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>`.13+14+Useful and often used kwargs are:15+16+* `default`: Passes a default.17+* `nargs`: Sets the number of arguments. Set to -1 to take an arbitrary number.18+19+## Basic Arguments20+21+A 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`.22+23+Example:24+25+```{eval-rst}26+.. click:example::27+28+ @click.command()29+ @click.argument('filename')30+ def touch(filename: str):31+ """Print FILENAME."""32+ click.echo(filename)33+34+And from the command line:35+36+.. click:run::37+38+ invoke(touch, args=['foo.txt'])39+```40+41+An 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`.42+43+```{admonition} Note on Required Arguments44+:class: note45+46+ 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+```48+49+## Multiple Arguments50+51+To 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.52+53+```{eval-rst}54+.. click:example::55+56+ @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}")63+64+And from the command line:65+66+.. click:run::67+68+ invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])69+```70+71+```{admonition} Note on Handling Files72+:class: note73+74+ 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+```76+77+## Argument Escape Sequences78+79+If 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.80+81+Example usage:82+83+```{eval-rst}84+.. click:example::85+86+ @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)92+93+And from the command line:94+95+.. click:run::96+97+ invoke(touch, ['--', '-foo.txt', 'bar.txt'])98+```99+100+If you don't like the `--` marker, you can set ignore_unknown_options to True to avoid checking unknown options:101+102+```{eval-rst}103+.. click:example::104+105+ @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)111+112+And from the command line:113+114+.. click:run::115+116+ invoke(touch, ['-foo.txt', 'bar.txt'])117+```118+119+(environment-variables)=120+121+## Environment Variables122+123+Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in `click.argument`.124+125+Checking one environment variable:126+127+```{eval-rst}128+.. click:example::129+130+ @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())135+136+And from the command line:137+138+.. click:run::139+140+ 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'})145+146+147+Checking multiple environment variables:148+149+.. click:example::150+151+ @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())156+157+And from the command line:158+159+.. click:run::160+161+ 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:2-3-Arguments4-=========5-6-.. currentmodule:: click7-8-Arguments are:9-10-* 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>`.13-14-Useful and often used kwargs are:15-16-* ``default``: Passes a default.17-* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.18-19-Basic Arguments20----------------21-22-A 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``.23-24-Example:25-26-.. click:example::27-28- @click.command()29- @click.argument('filename')30- def touch(filename: str):31- """Print FILENAME."""32- click.echo(filename)33-34-And from the command line:35-36-.. click:run::37-38- invoke(touch, args=['foo.txt'])39-40-41-An 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`.42-43-.. admonition:: Note on Required Arguments44-45- 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.46-47-Multiple Arguments48------------------------------------49-50-To 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.51-52-.. click:example::53-54- @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}")61-62-And from the command line:63-64-.. click:run::65-66- invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])67-68-.. admonition:: Note on Handling Files69-70- 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.71-72-Argument Escape Sequences73----------------------------74-75-If 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.76-77-Example usage:78-79-.. click:example::80-81- @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)87-88-And from the command line:89-90-.. click:run::91-92- invoke(touch, ['--', '-foo.txt', 'bar.txt'])93-94-If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:95-96-.. click:example::97-98- @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)104-105-And from the command line:106-107-.. click:run::108-109- invoke(touch, ['-foo.txt', 'bar.txt'])110-111-112-.. _environment-variables:113-114-Environment Variables115----------------------116-117-Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118-119-Checking one environment variable:120-121-.. click:example::122-123- @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())128-129-And from the command line:130-131-.. click:run::132-133- 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'})138-139-140-Checking multiple environment variables:141-142-.. click:example::143-144- @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())149-150-And from the command line:151-152-.. click:run::153-154- 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Click Concepts
This section covers concepts about Click's design.
```{contents}---depth: 1local: true---```
(callback-evaluation-order)=
## Callback Evaluation Order
Click works a bit differently than some other command line parsers in thatit attempts to reconcile the order of arguments as defined by theprogrammer with the order of arguments as defined by the user beforeinvoking any callbacks.
This is an important concept to understand when porting complexpatterns to Click from optparse or other systems. A parametercallback invocation in optparse happens as part of the parsing step,whereas a callback invocation in Click happens after the parsing.
The main difference is that in optparse, callbacks are invoked with the rawvalue as it happens, whereas a callback in Click is invoked after thevalue has been fully converted.
Generally, the order of invocation is driven by the order in which the userprovides the arguments to the script; if there is an option called `--foo`and an option called `--bar` and the user calls it as `--bar --foo`, thenthe callback for `bar` will fire before the one for `foo`.
There are three exceptions to this rule which are important to know:
Eagerness:> An option can be set to be "eager". All eager parameters are> evaluated before all non-eager parameters, but again in the order as> they were provided on the command line by the user.
> This is important for parameters that execute and exit like `--help`> and `--version`. Both are eager parameters, but whatever parameter> comes first on the command line will win and exit the program.
Repeated parameters:> If an option or argument is split up on the command line into multiple> places because it is repeated -- for instance, `--exclude foo --include> baz --exclude bar` -- the callback will fire based on the position of> the first option. In this case, the callback will fire for> `exclude` and it will be passed both options (`foo` and> `bar`), then the callback for `include` will fire with `baz`> only.
> Note that even if a parameter does not allow multiple versions, Click> will still accept the position of the first, but it will ignore every> value except the last. The reason for this is to allow composability> through shell aliases that set defaults.
Missing parameters:> If a parameter is not defined on the command line, the callback will> still fire. This is different from how it works in optparse where> undefined values do not fire the callback. Missing parameters fire> their callbacks at the very end which makes it possible for them to> default to values from a parameter that came before.
Most of the time you do not need to be concerned about any of this,but it is important to know how it works for some advanced cases.deleted:docs/click-concepts.rst-67 removed
1-Click Concepts2-================3-4-This section covers concepts about Click's design.5-6-.. contents::7- :depth: 18- :local:9-10-.. _callback-evaluation-order:11-12-Callback Evaluation Order13--------------------------14-15-Click works a bit differently than some other command line parsers in that16-it attempts to reconcile the order of arguments as defined by the17-programmer with the order of arguments as defined by the user before18-invoking any callbacks.19-20-This is an important concept to understand when porting complex21-patterns to Click from optparse or other systems. A parameter22-callback invocation in optparse happens as part of the parsing step,23-whereas a callback invocation in Click happens after the parsing.24-25-The main difference is that in optparse, callbacks are invoked with the raw26-value as it happens, whereas a callback in Click is invoked after the27-value has been fully converted.28-29-Generally, the order of invocation is driven by the order in which the user30-provides the arguments to the script; if there is an option called ``--foo``31-and an option called ``--bar`` and the user calls it as ``--bar32---foo``, then the callback for ``bar`` will fire before the one for ``foo``.33-34-There are three exceptions to this rule which are important to know:35-36-Eagerness: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.40-41- 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.44-45-Repeated 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.53-54- 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.58-59-Missing 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.65-66-Most of the time you do not need to be concerned about any of this,67-but it is important to know how it works for some advanced cases.added:docs/contributing.md+21 added
123456789101112131415161718192021# Contributing
This is a quick reference for Click-specific development tasks. For setting up the development environment and the general contribution workflow, see the Pallets [quick reference](https://palletsprojects.com/contributing/quick/) and the [detailed contributing guide](https://palletsprojects.com/contributing/).
## Extra Test Environments
Click includes some extra test environments:
- `tox r -e stress` runs stress tests for race conditions in Click's test runner.
```shell-session $ tox r -e stress ```
- `tox r -e random` runs tests in parallel in a random order to detect test pollution.
```shell-session $ tox r -e random ```
- A CI workflow (`.github/workflows/test-flask.yaml`) runs Flask's test suite to catch downstream regressions.modified:docs/index.rst+1 added-2 removed
132 unmodified lines133 * This documentation is structured according to `Diataxis <https://diataxis.fr/>`_ and written with `MyST <https://myst-parser.readthedocs.io/en/latest/>`_134 135 * `Version Policy <https://palletsprojects.com/versions>`_136 137-* `Contributing <https://palletsprojects.com/contributing/>`_138-137 * `Donate <https://palletsprojects.com/donate>`_138 139 .. toctree::140 :maxdepth: 1141 142+ contributing143 contrib144 license145 changesmodified:src/click/_termui_impl.py+32 added-13 removed
376 unmodified lines377 378 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)380 381- # 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 return23 unmodified lines414 415 def _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.419 417- 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.424+425+ 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.428+429+ 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 False85 unmodified lines520 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None521 ) -> bool:522 """Page through text by invoking a program on a temporary file.523 512- 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`.528+529+ 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 False73 unmodified lines608 return editor609 return "vi"610 611 def edit_files(self, filenames: cabc.Iterable[str]) -> None:612+ """Open files in the user's editor."""613+ import shlex614 import subprocess615 616 editor = self.get_editor()617 environ: dict[str, str] | None = None1 unmodified line619 if self.env:620 environ = os.environ.copy()621 environ.update(self.env)622 604- exc_filename = " ".join(f'"{filename}"' for filename in filenames)605-623 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 lines774 775 if ch == "\x1a" and WIN: # Windows, Ctrl+Z776 raise EOFError()777 757- return None778 759-779 if sys.platform == "win32":780 import msvcrt781 782 @contextlib.contextmanager89 unmodified linesmodified:src/click/core.py+1 added-1 removed
3108 unmodified lines3109 (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 linesmodified:src/click/testing.py+45 added
2 unmodified lines3 import collections.abc as cabc4 import contextlib5 import io6 import os7+import pdb8 import shlex9 import sys10 import tempfile11 import typing as t378 unmodified lines390 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_ansi400 401+ 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.410+411+ 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.417+418+ 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.422+423+ 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.429+430+ 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+ )440+441+ pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]442+443 old_env = {}444 try:445 for key, value in env.items():446 old_env[key] = os.environ.get(key)22 unmodified lines469 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]474 475 def invoke(476 self,477 cli: Command,142 unmodified linesmodified:tests/test_options.py+28 added-4 removed
1257 unmodified lines1258 message = opt.get_help_record(ctx)[1]1259 assert "[default: (unlimited)]" in message1260 1261 1262-def 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)1262+class _StrictEq:1263+ """Object whose ``__eq__`` raises on string comparison (like semver.Version)."""1264+1265+ def __eq__(self, other):1266+ if isinstance(other, str):1267+ raise ValueError("cannot compare to string")1268+ return NotImplemented1269+1270+ def __str__(self):1271+ return "strict"1272+1273+1274+@pytest.mark.parametrize(1275+ ("default", "expected"),1276+ [1277+ ("", '[default: ""]'),1278+ (_StrictEq(), "[default: strict]"),1279+ ],1280+ ids=["empty-string", "non-string-comparable-object"],1281+)1282+def 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.1285+1286+ 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 message1292 1293 1294 def test_do_not_show_no_default(runner):1295 """When show_default is True and no default is set do not show None."""1232 unmodified linesmodified:tests/test_termui.py+221 added
1 import platform2+import shlex3 import tempfile4 import time5+from unittest.mock import patch6 7 import pytest8 9 import click._termui_impl10 from click._compat import WIN11+from click._termui_impl import Editor12 from click.exceptions import BadParameter13 from click.exceptions import MissingParameter14 15 391 unmodified lines407 assert reopened_file.read() == "aTest\nbTest\n"408 409 410 @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+)504+def 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)508+509+ 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 None513+514+515+@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+)531+def 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"])537+538+ 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 None541+542+543+def 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"])547+548+ env = mock_popen.call_args[1].get("env")549+ assert env is not None550+ assert env["MY_VAR"] == "1"551+552+553+def 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"])558+559+560+def 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"])564+565+566+@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+)612+def test_pager_shlex_split(pager_env, expected_parts):613+ """Verify shlex.split produces the expected argv for PAGER values.614+615+ 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_parts620+621+622+def 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"])626+627+628+@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 linesmodified:tests/test_testing.py+50 added
1 import os2+import pdb3 import sys4 from io import BytesIO5 6 import pytest462 unmodified lines469 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)470 471 result = runner.invoke(cli)472 assert result.stderr == "gyarados gyarados gyarados"473+474+475+def 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+ """480+481+ @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")487+488+ runner = CliRunner()489+ result = runner.invoke(cli, catch_exceptions=False)490+ assert result.output == "after debugger\n"491+492+493+def test_pdb_explicit_streams_honored():494+ """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not495+ overridden by the ``CliRunner`` patch.496+ """497+498+ @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_out505+506+ runner = CliRunner()507+ runner.invoke(cli, catch_exceptions=False)508+509+510+def test_pdb_init_restored_after_invoke():511+ """``pdb.Pdb.__init__`` is restored to its original after invoke."""512+ original = pdb.Pdb.__init__513+514+ @click.command()515+ def cli():516+ pass517+518+ runner = CliRunner()519+ runner.invoke(cli)520+521+ assert pdb.Pdb.__init__ is originalmodified:tests/test_utils.py+2 added-5 removed
7 unmodified lines8 from decimal import Decimal9 from fractions import Fraction10 from functools import partial11 from io import StringIO12-from pathlib import Path13-from tempfile import tempdir12 from unittest.mock import patch13 14 import pytest15 360 unmodified lines376 expected_error=None,377 ),378 ],379 )382-def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):380+def 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)383 384 test_input = test.test_input()3 unmodified lines388 expected_error = test.expected_error389 390 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()391 394- 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 linesmodified:.pre-commit-config.yaml+1 added
11 unmodified lines12 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-fixermodified:CHANGES.rst+24 added-2 removed
1 .. currentmodule:: click2 3+Version 8.3.34+-------------5+6+Unreleased7+8+- 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`24+25 Version 8.3.24---------------26+-------------27 28 Released 2026-04-0229 30 - Fix handling of ``flag_value`` when ``is_flag=False`` to allow such options to be9 unmodified lines40 - Fix callable ``flag_value`` being instantiated when used as a default via41 ``default=True``. :issue:`3121` :pr:`3201` :pr:`3213` :pr:`3225`42 43 Version 8.3.122---------------44+-------------45 46 Released 2025-11-1547 48 - Don't discard pager arguments by correctly using ``subprocess.Popen``. :issue:`3039`1302 unmodified linesmodified:pyproject.toml+14 added
49 unmodified lines50 ]51 tests = [52 "pytest",53 ]54+tests-random = [55+ "pytest",56+ "pytest-randomly",57+ "pytest-xdist",58+]59 typing = [60 "mypy",61 "pyright",62 "pytest",106 unmodified lines169 "pytest", "-v", "--tb=short", "--basetemp={env_tmp_dir}",170 {replace = "posargs", default = [], extend = true},171 ]]172 173+[tool.tox.env.random]174+description = "randomized parallel tests to detect test pollution and race conditions"175+dependency_groups = ["tests-random"]176+commands = [[177+ "pytest", "-v", "--tb=short", "--numprocesses=auto",178+ "--basetemp={env_tmp_dir}",179+ {replace = "posargs", default = [], extend = true},180+]]181+182 [tool.tox.env.stress]183 description = "stress tests for stream lifecycle race conditions"184 commands = [[185 "pytest", "-v", "--tb=short", "-x", "-m", "stress",51 unmodified linesmodified:uv.lock+44 added
207 unmodified lines208 ]209 tests = [210 { name = "pytest" },211 ]212+tests-random = [213+ { name = "pytest" },214+ { name = "pytest-randomly" },215+ { name = "pytest-xdist" },216+]217 typing = [218 { name = "mypy" },219 { name = "pyright" },220 { name = "pytest" },21 unmodified lines242 { name = "pre-commit" },243 { name = "pre-commit-uv" },244 ]245 tests = [{ name = "pytest" }]246+tests-random = [247+ { name = "pytest" },248+ { name = "pytest-randomly" },249+ { name = "pytest-xdist" },250+]251 typing = [252 { name = "mypy" },253 { name = "pyright" },254 { name = "pytest" },54 unmodified lines309 { 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 ]311 312 [[package]]313+name = "execnet"314+version = "2.1.2"315+source = { registry = "https://pypi.org/simple" }316+sdist = { 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" }317+wheels = [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+]320+321+[[package]]322 name = "filelock"323 version = "3.25.2"324 source = { registry = "https://pypi.org/simple" }325 sdist = { 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 lines913 { 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 ]915 916 [[package]]917+name = "pytest-randomly"918+version = "4.0.1"919+source = { registry = "https://pypi.org/simple" }920+dependencies = [921+ { name = "pytest" },922+]923+sdist = { 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" }924+wheels = [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+]927+928+[[package]]929+name = "pytest-xdist"930+version = "3.8.0"931+source = { registry = "https://pypi.org/simple" }932+dependencies = [933+ { name = "execnet" },934+ { name = "pytest" },935+]936+sdist = { 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" }937+wheels = [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+]940+941+[[package]]942 name = "pyyaml"943 version = "6.0.3"944 source = { registry = "https://pypi.org/simple" }945 sdist = { 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