Merge branch 'main' into fix-wrap-text-ansi
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents d946074, d959898 · Browse files · 11 files·+1749 added−147 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+1749 added−147 removed
- tests:+1291 added−16 removed
- other:+458 added−131 removed
Provenance
- Commit
587e3cc- Tree
27cc0ef- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
d946074- Parent 2
d959898
11 files changed+1749 added−147 removed
modified:docs/options.md+162 added-4 removed
228 unmodified lines229 230 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])231 ```232 233+## Combining short options234+235+Short options made of a single character can be combined into one argument: `-abc` is equivalent to `-a -b -c`. This is the standard POSIX behavior for short option stacking, and it is the reason a repeated flag like `-vvv` works with the [Counting](#counting) feature.236+237+```{eval-rst}238+.. click:example::239+240+ @click.command()241+ @click.option('-a', is_flag=True)242+ @click.option('-b', is_flag=True)243+ @click.option('-c', is_flag=True)244+ def cli(a, b, c):245+ click.echo(f"a={a} b={b} c={c}")246+247+.. click:run::248+249+ invoke(cli, args=['-a', '-b', '-c'])250+ invoke(cli, args=['-abc'])251+```252+253+If the last option in the combination takes a value, the value can either follow as the next argument or be attached directly:254+255+```{eval-rst}256+.. click:example::257+258+ @click.command()259+ @click.option('-v', is_flag=True)260+ @click.option('-n', type=int)261+ def cli(v, n):262+ click.echo(f"v={v} n={n}")263+264+.. click:run::265+266+ invoke(cli, args=['-v', '-n', '5'])267+ invoke(cli, args=['-vn', '5'])268+ invoke(cli, args=['-vn5'])269+```270+271+```{note}272+Multi-character short option names are not supported. An argument like `-dbg` is interpreted as the combination of `-d`, `-b`, and `-g`, so Click reports `No such option: -d` if `-d` is not declared. For longer option names, use a long option with the `--` prefix (like `--debug`).273+```274+275 ## Counting276 277 To count the occurrence of an option, set `count=True`. If the option is not278 passed on the command line, then the count is 0. Counting is commonly used for231 unmodified lines510 ```511 512 #### Feature switch groups (multiple flags sharing one variable)513 472-When multiple `flag_value` options target the same parameter473-name, `default=True` on one of them marks it as the default474-choice.514+Several `flag_value` options can target the same parameter name to form a515+feature switch group. The user picks one flag on the command line, and the516+function receives the corresponding `flag_value`. When the user picks none,517+Click falls back to whichever option claims the slot under the arbitration518+rules described below.519 520+##### Non-boolean groups521+522+For non-boolean `flag_value` (strings, enum members, classes, ...), place523+`default=True` on the option that should win when no flag is passed. The524+substitution rule above resolves it to that option's `flag_value`. Any other525+explicit `default` is passed through literally.526+527 | Definition | Not passed | `--upper` | `--lower` |528 |--------------------------------------------------------|------------|-----------|-----------|529 | `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |530 | `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |480-| Both without `default` | `None` | `"upper"` | `"lower"` |531+| `--upper` with `flag_value='upper'`, `default=None` | `None` | `"upper"` | `"lower"` |532+| Neither option carries a `default` | `None` | `"upper"` | `"lower"` |533 534+The third row is the three-state pattern: the function receives `None` when no535+flag is passed, distinguishable from either explicit choice.536+537+##### Boolean groups538+539+When `flag_value` is `True` or `False`, the substitution rule does not apply:540+`default=True` is the literal Python `True`. To make one flag in an541+enable/disable pair the default, set its `default=True` explicitly:542+543+```python544+@click.option("--without-xyz", "enable_xyz", flag_value=False)545+@click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)546+```547+548+| Definition | Not passed | `--with-xyz` | `--without-xyz` |549+|---------------------------------------------------------|------------|--------------|-----------------|550+| `--with-xyz` with `flag_value=True`, `default=True` | `True` | `True` | `False` |551+| `--without-xyz` with `flag_value=False`, `default=False`| `False` | `True` | `False` |552+| `--with-xyz` with `flag_value=True`, `default=None` | `None` | `True` | `False` |553+| Neither option carries a `default` | `False` | `True` | `False` |554+555+```{tip}556+For most enable/disable cases, the pair form `--with-xyz/--without-xyz` is557+shorter and equivalent. The multi-flag group form is useful when the on and off558+flags need distinct names without a shared stem, or when each flag needs its559+own help text.560+```561+562+##### Arbitration rules563+564+When several options in a group resolve their values simultaneously, only one565+wins the parameter slot. The full arbitration policy (source precedence,566+explicit-beats-auto tie-break, first-declared fallback) is enumerated under567+[Option value resolution](#option-value-resolution).568+569+## Option value resolution570+571+This section enumerates the rules Click applies when computing the value572+delivered to the decorated function for every option. Rules are listed in the573+order they fire during the parsing pipeline.574+575+### Type inference576+577+Without an explicit `type=`, Click infers the parameter type at construction:578+579+1. If `flag_value` is `True` or `False`, the type is {class}`BoolParamType`.580+2. If `flag_value` is an `int`, `float`, or `str`, the type is the matching581+ basic type.582+3. If `flag_value` is any other Python object (a class, an enum member, a583+ `frozenset`, ...), the type is {data}`UNPROCESSED` so the value passes584+ through unchanged.585+4. Otherwise, the type is inferred from `default` if set, falling back to586+ {class}`StringParamType` when neither hint is available.587+588+### `default` interpretation589+590+The literal value passed as `default=` is interpreted differently depending on591+whether the option is a flag and what `flag_value` it carries:592+593+1. `default=UNSET` (the absence sentinel) is treated as if `default` was not594+ passed at all. It does not count as "the user picked nothing", and it does595+ not count as an explicit default for arbitration purposes.596+2. For a bare boolean flag (no `flag_value`, or `flag_value` of `True` or597+ `False`), an unset `default` auto-derives to `False`.598+3. For a non-boolean flag with a `flag_value`, `default=True` is substituted599+ with `flag_value`. This is the "activate this flag by default" shorthand.600+ Any non-`True` `default` is passed through literally.601+4. For a boolean flag with `flag_value` set, `default=True` is the literal602+ Python `True`. The substitution from rule 3 does not apply.603+5. `default=None` is always a real explicit value, distinct from `UNSET`604+ absence.605+6. Any other `default` is delivered to the function unchanged after conversion606+ through the parameter's type.607+608+### Value sources609+610+Click resolves the value of every option from the following611+sources, in order of decreasing precedence:612+613+1. **command line input** ({attr}`ParameterSource.COMMANDLINE`),614+2. **environment variable** named in `envvar=` or derived from `auto_envvar_prefix`615+ ({attr}`ParameterSource.ENVIRONMENT`),616+3. **`default_map` entry** matching the parameter name on the active {class}`Context`617+ ({attr}`ParameterSource.DEFAULT_MAP`),618+4. **parameter default** ({attr}`ParameterSource.DEFAULT`).619+620+The first source that produces a value wins. Environment variables and621+`default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through622+to the next source rather than supplying `UNSET` to the function.623+624+### Slot arbitration625+626+Several options can target the same `name` to form a feature switch group. When627+they do, only one option's value reaches the function. Arbitration applies628+these rules, in order:629+630+1. **By source.** Whichever option resolved its value from the most explicit631+ source wins, regardless of decorator order. Any command-line input beats any632+ default, an environment variable beats a `default_map` entry, and so on.633+2. **Within the default tier, explicit beats auto-derived.** An option that634+ received an explicit `default=` keyword wins over one whose default came635+ from `default` interpretation.636+3. **Otherwise, last declared wins.** When all options in the group resolved637+ from the same source and tier (all auto-derived defaults, or all explicit638+ defaults), the option declared last in the source code keeps the slot.639+640 ## Values from Environment Variables641 642 To pass in a value from a specific environment variable use `envvar`.643 151 unmodified linesmodified:docs/testing.md+50 added-38 removed
202 unmodified lines203 Prompts will be emulated so they write the input data to204 the output stream as well. If hidden input is expected then this205 does not happen.206 207-## File Descriptors and Low-Level I/O207+## Capture modes208 209-{class}`CliRunner` captures output by replacing210-`sys.stdout` and `sys.stderr` with in-memory211-{class}`~io.BytesIO`-backed wrappers. This is212-Python-level redirection: calls to {func}`~click.echo`,213-{func}`print`, or `sys.stdout.write()` are captured, but214-the wrappers have no OS-level file descriptor.209+{class}`CliRunner` captures output by replacing `sys.stdout` and `sys.stderr`210+with in-memory wrappers. The `capture` parameter controls which strategy is211+used.212 216-Code that calls `fileno()` on `sys.stdout` or217-`sys.stderr`, like {mod}`faulthandler`,218-{mod}`subprocess`, or C extensions, would normally crash219-with {exc}`io.UnsupportedOperation` inside220-{class}`CliRunner`.213+### `capture="sys"` (default)214 222-To avoid this, {class}`CliRunner` preserves the original223-stream's file descriptor and exposes it via `fileno()` on224-the replacement wrapper.215+Captures Python-level writes (`print()`, `click.echo()`, `sys.stdout.write()`).216+It is fast and sufficient for most Click applications.217 226-This means:227-- **Python-level writes** (`print()`, `click.echo()`,228- ...) are captured as usual.229-- **fd-level writes** (C code writing directly to the230- file descriptor) go to the original terminal and are231- **not** captured.218+Code that holds a reference to the original `sys.stdout` (like a library that219+does `from sys import stdout` at import time) bypasses the capture and its220+output is lost.221 233-This is the same trade-off that234-[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)235-makes with its two capture modes:222+In this mode `sys.stdout.fileno()` and `sys.stderr.fileno()` raise223+{exc}`io.UnsupportedOperation`, matching the pre-`8.3.3` behavior. C-level224+consumers ({mod}`faulthandler`, {mod}`subprocess`, C extensions) that expect a225+real file descriptor must opt into the `capture="fd"` mode.226 237-- `capsys`, which captures Python-level output, where238- `fileno()` raises `UnsupportedOperation` and fd-level239- writes are not captured.240-- `capfd`, which captures fd-level output via241- `os.dup2()`, where `fileno()` works and fd-level242- writes *are* captured.227+### `capture="fd"`228 244-Rather than implementing a full `capfd`-style mechanism,245-{class}`CliRunner` takes the simpler path: expose the246-original `fd` so that standard library helpers keep247-working, while accepting that their output is not248-captured.229+Redirects OS file descriptors `1` and `2` to a temporary file via230+{func}`os.dup2`, inspired by [Pytest's231+`capfd`](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html).232+This catches output that bypasses `sys.stdout`, including:233 250-```{versionchanged} 8.3.3251-`fileno()` on the redirected streams now returns the252-original stream's file descriptor instead of raising.234+- Stale references to the original `sys.stdout` and `sys.stderr`.235+- Logging frameworks that cache the original stream (like `structlog` or the236+ stdlib's `logging` module).237+- C extensions and subprocesses that write directly to `fd 1` or `fd 2`.238+239+```python240+from click.testing import CliRunner241+from myapp import cli242+243+244+def test_captures_everything():245+ runner = CliRunner(capture="fd")246+ result = runner.invoke(cli)247+ # result.stdout contains both Python-level and fd-level output248+ assert "expected output" in result.stdout249 ```250+251+In this mode `sys.stdout.fileno()` returns the saved (pre-redirection) `fd`, so252+{mod}`faulthandler` and similar consumers keep working. Writes to `fd 1` and253+`fd 2` land in the capture tmpfile, so `os.dup2()` calls inside the CLI no254+longer leak into the host runner's stdout.255+256+```{note}257+`capture="fd"` is not available on Windows.258+```259+260+```{versionchanged} 8.4.0261+Added the `capture` parameter. The default `sys` mode no longer exposes the262+original `fd` through `fileno()`, reverting the change introduced in `8.3.3`263+that broke Pytest's `fd`-level capture teardown. Use `capture="fd"` to restore264+that behavior with proper isolation.265+```modified:src/click/core.py+72 added-39 removed
91 unmodified lines92 93 raise RuntimeError(message)94 95 96+def _format_deprecated_label(deprecated: bool | str) -> str:97+ """Return the parenthesized deprecation label shown in help text."""98+ label = _("deprecated").upper()99+ if isinstance(deprecated, str):100+ return f"({label}: {deprecated})"101+ return f"({label})"102+103+104+def _format_deprecated_suffix(deprecated: bool | str) -> str:105+ """Return the trailing reason for a ``DeprecationWarning`` message,106+ prefixed with a space, or an empty string when no reason was given.107+ """108+ if isinstance(deprecated, str):109+ return f" {deprecated}"110+ return ""111+112+113 def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:114 return list(zip(*repeat(iter(iterable), batch_size), strict=False))115 116 353 unmodified lines470 471 self._close_callbacks: list[t.Callable[[], t.Any]] = []472 self._depth = 0473 self._parameter_source: dict[str, ParameterSource] = {}474+ # Tracks whether the option that currently owns each parameter slot in475+ # :attr:`params` had its ``default`` set explicitly by the user. Used476+ # to tie-break feature-switch groups where multiple options share a477+ # parameter name and both fall back to their default value.478+ # Refs: https://github.com/pallets/click/issues/3403479+ self._param_default_explicit: dict[str, bool] = {}480 self._exit_stack = ExitStack()481 482 @property483 def protected_args(self) -> list[str]:674 unmodified lines1158 else:1159 text = ""1160 1161 if self.deprecated:1139- localised_deprectated = _("deprecated").upper()1140- deprecated_message = (1141- f"({localised_deprectated}: {self.deprecated})"1142- if isinstance(self.deprecated, str)1143- else f"({localised_deprectated})"1144- )1145- text = f"{_(text)} {deprecated_message}"1162+ text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"1163 1164 return text.strip()1165 1166 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:21 unmodified lines1188 else:1189 text = ""1190 1191 if self.deprecated:1175- localised_deprectated = _("deprecated").upper()1176- deprecated_message = (1177- f"({localised_deprectated}: {self.deprecated})"1178- if isinstance(self.deprecated, str)1179- else f"({localised_deprectated})"1180- )1181- text = f"{_(text)} {deprecated_message}"1192+ text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"1193 1194 if text:1195 formatter.write_paragraph()1196 98 unmodified lines1295 """Given a context, this invokes the attached callback (if it exists)1296 in the right way.1297 """1298 if self.deprecated:1288- extra_message = (1289- f" {self.deprecated}" if isinstance(self.deprecated, str) else ""1290- )1299 message = _(1300 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"1293- ).format(name=self.name, extra_message=extra_message)1301+ ).format(1302+ name=self.name,1303+ extra_message=_format_deprecated_suffix(self.deprecated),1304+ )1305 echo(style(message, fg="red"), err=True)1306 1307 if self.callback is not None:1308 return ctx.invoke(self.callback, **ctx.params)896 unmodified lines2205 self.nargs = nargs2206 self.multiple = multiple2207 self.expose_value = expose_value2208 self.default: t.Any | t.Callable[[], t.Any] | None = default2209+ # Whether the user passed ``default`` explicitly to the constructor.2210+ # Captured before any auto-derived default (like ``False`` for boolean2211+ # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2212+ # remains ``False`` when the default was inferred rather than chosen.2213+ # Refs: https://github.com/pallets/click/issues/34032214+ self._default_explicit: bool = default is not UNSET2215 self.is_eager = is_eager2216 self.metavar = metavar2217 self.envvar = envvar2218 self._custom_shell_complete = shell_complete378 unmodified lines2597 a default).2598 2599 :meta private:2600 """2601+ # Capture the slot's existing state before we mutate2602+ # ``_parameter_source`` so the write decision below can compare our2603+ # incoming source against the source of the option that already wrote2604+ # the slot (if any).2605+ existing_value = ctx.params.get(self.name, UNSET)2606+ existing_source = ctx.get_parameter_source(self.name)2607+ existing_default_explicit = ctx._param_default_explicit.get(self.name, False)2608+2609 with augment_usage_errors(ctx, param=self):2610 value, source = self.consume_value(ctx, opts)2611 2587- ctx.set_parameter_source(self.name, source)2588-2612 # Display a deprecation warning if necessary.2613 if (2614 self.deprecated2615 and value is not UNSET2616 and source < ParameterSource.DEFAULT_MAP2617 ):2595- extra_message = (2596- f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2597- )2618 message = _(2619 "DeprecationWarning: The {param_type} {name!r} is deprecated."2620 "{extra_message}"2621 ).format(2622 param_type=self.param_type_name,2623 name=self.human_readable_name,2604- extra_message=extra_message,2624+ extra_message=_format_deprecated_suffix(self.deprecated),2625 )2626 echo(style(message, fg="red"), err=True)2627 2628 # Process the value through the parameter's type.6 unmodified lines2635 # value is incompatible with the parameter type, so we reset the value2636 # to UNSET, which will be interpreted as a missing value.2637 value = UNSET2638 2619- # Add parameter's value to the context.2620- if (2621- self.expose_value2622- # We skip adding the value if it was previously set by another parameter2623- # targeting the same variable name. This prevents parameters competing for2624- # the same name to override each other.2625- and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2626- ):2627- ctx.params[self.name] = value2639+ # Arbitrate the slot when several parameters target the same variable2640+ # name (feature-switch groups). See: https://github.com/pallets/click/issues/34032641+ slot_empty = existing_value is UNSET2642+ more_explicit = existing_source is not None and source < existing_source2643+ same_source = existing_source is not None and source == existing_source2644+ auto_would_downgrade_explicit = (2645+ same_source2646+ and source == ParameterSource.DEFAULT2647+ and existing_default_explicit2648+ and not self._default_explicit2649+ )2650+ is_winner = (2651+ slot_empty2652+ or more_explicit2653+ or (same_source and not auto_would_downgrade_explicit)2654+ )2655 2656+ if is_winner:2657+ ctx.set_parameter_source(self.name, source)2658+ if self.expose_value:2659+ ctx.params[self.name] = value2660+ ctx._param_default_explicit[self.name] = self._default_explicit2661+ elif existing_source is None:2662+ # Nothing has claimed the slot yet. Record at least our source so downstream2663+ # lookups don't return ``None``.2664+ ctx.set_parameter_source(self.name, source)2665+2666 return value, args2667 2668 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2669 return None147 unmodified lines2817 else:2818 prompt_text = prompt2819 2820 if deprecated:2784- deprecated_message = (2785- f"(DEPRECATED: {deprecated})"2786- if isinstance(deprecated, str)2787- else "(DEPRECATED)"2788- )2789- help = help + deprecated_message if help is not None else deprecated_message2821+ label = _format_deprecated_label(deprecated)2822+ help = f"{help} {label}" if help is not None else label2823 2824 self.prompt = prompt_text2825 self.confirmation_prompt = confirmation_prompt2826 self.prompt_required = prompt_required709 unmodified linesmodified:src/click/shell_completion.py+9 added-8 removed
419 unmodified lines420 421 return args, incomplete422 423 def format_completion(self, item: CompletionItem) -> str:424- """Format completion item for Fish shell.425-426- Escapes newlines in both value and help text to prevent427- Fish shell parsing errors.428-429- .. versionchanged:: 8.3430- Escape newlines in help text to fix completion errors431- with multi-line help strings.424 """425+ .. versionchanged:: 8.4426+ Escape newlines in value and help to fix completion errors with427+ multi-line help strings.428+ """429+ # The fish completion script splits each response line on literal430+ # newlines, so any newline in the value or help would corrupt the431+ # frame. Replace them with the two-character escape "\n" so the text432+ # round-trips through fish without breaking the format. The "_"433+ # sentinel for missing help mirrors :class:`ZshComplete`.434 help_ = item.help or "_"435 value = item.value.replace("\n", r"\n")436 help_escaped = help_.replace("\n", r"\n")437 return f"{item.type}\n{value}\n{help_escaped}"242 unmodified linesmodified:src/click/termui.py+24 added-4 removed
2 unmodified lines3 import collections.abc as cabc4 import inspect5 import io6 import itertools7+import re8 import sys9 import typing as t10 from contextlib import AbstractContextManager11 from contextlib import redirect_stdout41 unmodified lines53 }54 _ansi_reset_all = "\033[0m"55 56 57+_HIDDEN_INPUT_MASK = "'***'"58+59+60+def _mask_hidden_input(message: str, value: str) -> str:61+ """Replace occurrences of ``value`` in ``message`` with a fixed mask.62+63+ Both ``repr(value)`` (the form built-in :class:`ParamType` errors use64+ via ``{value!r}``) and the raw value are masked. The raw-value pass65+ uses word-boundary lookarounds so a substring like ``"1"`` does not66+ match inside ``"10"``, and ``"ent"`` does not match inside67+ ``"Authentication"``. The empty string is skipped to avoid matching68+ at every boundary.69+ """70+ message = message.replace(repr(value), _HIDDEN_INPUT_MASK)71+ if value:72+ message = re.sub(73+ rf"(?<!\w){re.escape(value)}(?!\w)", _HIDDEN_INPUT_MASK, message74+ )75+ return message76+77+78 def hidden_prompt_func(prompt: str) -> str:79 import getpass80 81 return getpass.getpass(prompt)141 unmodified lines223 break224 try:225 result = value_proc(value)226 except UsageError as e:205- if hide_input:206- echo(_("Error: The value you entered was invalid."), err=err)207- else:208- echo(_("Error: {e.message}").format(e=e), err=err)227+ message = _mask_hidden_input(e.message, value) if hide_input else e.message228+ echo(_("Error: {message}").format(message=message), err=err)229 continue230 if not confirmation_prompt:231 return result232 while True:709 unmodified linesmodified:src/click/testing.py+103 added-36 removed
20 unmodified lines21 from _typeshed import ReadableBuffer22 23 from .core import Command24 25+CaptureMode = t.Literal["sys", "fd"]26 27+28 class EchoingStdin:29 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:30 self._input = input31 self._output = output36 unmodified lines68 yield69 stream._paused = False70 71 72+class _FDCapture:73+ """Redirect a file descriptor to a temporary file for capture.74+75+ Saves the current target of *targetfd* via :func:`os.dup`, then76+ redirects it to a temporary file via :func:`os.dup2`. On77+ :meth:`stop`, restores the original ``fd`` and returns the captured78+ bytes. Inspired by Pytest's ``FDCapture``.79+80+ .. versionadded:: 8.4.081+ """82+83+ def __init__(self, targetfd: int) -> None:84+ self._targetfd = targetfd85+ self.saved_fd: int = -186+ self._tmpfile: t.BinaryIO | None = None87+88+ def start(self) -> None:89+ self.saved_fd = os.dup(self._targetfd)90+ self._tmpfile = tempfile.TemporaryFile(buffering=0)91+ os.dup2(self._tmpfile.fileno(), self._targetfd)92+93+ def stop(self) -> bytes:94+ assert self._tmpfile is not None, "_FDCapture.start() was not called"95+ os.dup2(self.saved_fd, self._targetfd)96+ os.close(self.saved_fd)97+ self.saved_fd = -198+ self._tmpfile.seek(0)99+ data = self._tmpfile.read()100+ self._tmpfile.close()101+ self._tmpfile = None102+ return data103+104+105 class BytesIOCopy(io.BytesIO):106 """Patch ``io.BytesIO`` to let the written stream be copied to another.107 108 .. versionadded:: 8.229 unmodified lines138 class _NamedTextIOWrapper(io.TextIOWrapper):139 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``140 that does not close its underlying buffer.141 107- An optional ``original_fd`` preserves the file descriptor of the108- stream being replaced, so that C-level consumers that call109- :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.110- Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`111- for details.112-113- .. versionchanged:: 8.3.3114- Added ``original_fd`` parameter and :meth:`fileno` override.142+ When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to143+ point at the saved (pre-redirection) ``fd``, so C-level consumers that call144+ :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In145+ the default ``sys`` mode ``_original_fd`` stays at ``-1`` and146+ :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the147+ pre-``8.3.3`` behavior.148 """149 150 def __init__(151 self,152 buffer: t.BinaryIO,153 name: str,154 mode: str,122- *,123- original_fd: int = -1,155 **kwargs: t.Any,156 ) -> None:157 super().__init__(buffer, **kwargs)158 self._name = name159 self._mode = mode129- self._original_fd = original_fd160+ self._original_fd: int = -1161 162 def close(self) -> None:163 """The buffer this object contains belongs to some other object,164 so prevent the default ``__del__`` implementation from closing2 unmodified lines167 .. versionadded:: 8.3.2168 """169 170 def fileno(self) -> int:140- """Return the file descriptor of the original stream, if one was141- provided at construction time.142-143- This allows C-level consumers (``faulthandler``, ``subprocess``,144- signal handlers, ...) to obtain a valid fd without crashing, even145- though the Python-level writes are redirected to an in-memory146- buffer.147-148- .. versionadded:: 8.3.3171+ """Return the file descriptor of the saved original stream when172+ ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to173+ :class:`~io.TextIOWrapper`, which raises174+ :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer.175 """176 if self._original_fd >= 0:177 return self._original_fd178 return super().fileno()118 unmodified lines297 some circumstances. Note that regular prompts298 will automatically echo the input.299 :param catch_exceptions: Whether to catch any exceptions other than300 ``SystemExit`` when running :meth:`~CliRunner.invoke`.301+ :param capture: Selects the output capture strategy. ``sys`` (default)302+ captures Python-level writes only and leaves303+ :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so304+ user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot305+ clobber the host runner's stdout. ``fd`` redirects file descriptors306+ ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching307+ output from stale stream references, C extensions, and subprocesses.308+ ``fd`` is not supported on Windows.309 310+ .. versionchanged:: 8.4.0311+ Added the ``capture`` parameter. The default ``sys`` mode no longer312+ exposes the original fd through :meth:`fileno`, reverting the change313+ introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture314+ teardown. Use ``capture="fd"`` to restore that behavior with proper315+ isolation. :issue:`3384`316+317 .. versionchanged:: 8.2318 Added the ``catch_exceptions`` parameter.319 320 .. versionchanged:: 8.25 unmodified lines326 charset: str = "utf-8",327 env: cabc.Mapping[str, str | None] | None = None,328 echo_stdin: bool = False,329 catch_exceptions: bool = True,330+ capture: CaptureMode = "sys",331 ) -> None:332+ if capture not in {"sys", "fd"}:333+ raise ValueError(334+ f"capture={capture!r} is not valid. Choose from 'sys' or 'fd'."335+ )336+ if capture == "fd" and sys.platform == "win32":337+ raise ValueError(338+ f"capture={capture!r} is not supported on Windows. Use 'sys'."339+ )340 self.charset = charset341 self.env: cabc.Mapping[str, str | None] = env or {}342 self.echo_stdin = echo_stdin343 self.catch_exceptions = catch_exceptions344+ self.capture: CaptureMode = capture345 346 def get_default_prog_name(self, cli: Command) -> str:347 """Given a command object it will return the default program name348 for it. The default is the `name` attribute or ``"root"`` if not56 unmodified lines405 env = self.make_env(env)406 407 stream_mixer = StreamMixer()408 358- # Preserve the original file descriptors so that C-level359- # consumers (faulthandler, subprocess, etc.) can still obtain a360- # valid fd from the redirected streams. The original streams361- # may themselves lack a fileno() (e.g. when CliRunner is used362- # inside pytest's capsys), so we fall back to -1.363- def _safe_fileno(stream: t.IO[t.Any]) -> int:364- try:365- return stream.fileno()366- except (AttributeError, io.UnsupportedOperation):367- return -1368-369- old_stdout_fd = _safe_fileno(old_stdout)370- old_stderr_fd = _safe_fileno(old_stderr)371-409 if self.echo_stdin:410 bytes_input = echo_input = t.cast(411 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)412 )11 unmodified lines424 stream_mixer.stdout,425 encoding=self.charset,426 name="<stdout>",427 mode="w",391- original_fd=old_stdout_fd,428 )429 430 sys.stderr = _NamedTextIOWrapper(431 stream_mixer.stderr,432 encoding=self.charset,433 name="<stderr>",434 mode="w",435 errors="backslashreplace",400- original_fd=old_stderr_fd,436 )437 438 @_pause_echo(echo_input) # type: ignore439 def visible_input(prompt: str | None = None) -> str:173 unmodified lines613 exc_info = None614 if catch_exceptions is None:615 catch_exceptions = self.catch_exceptions616 617+ # Set up fd capture before isolation replaces sys.stdout and sys.stderr.618+ cap_out: _FDCapture | None = None619+ cap_err: _FDCapture | None = None620+621+ if self.capture == "fd":622+ cap_out = _FDCapture(1)623+ cap_err = _FDCapture(2)624+ try:625+ cap_out.start()626+ cap_err.start()627+ except OSError:628+ cap_out = cap_err = None629+630 with self.isolation(input=input, env=env, color=color) as outstreams:631+ # Point the captured streams' fileno() at the saved (original)632+ # fd so that C-level consumers like faulthandler keep working633+ # while fd 1/2 are redirected to the capture tmpfile.634+ if cap_out is not None and cap_err is not None:635+ sys.stdout._original_fd = cap_out.saved_fd # type: ignore[union-attr]636+ sys.stderr._original_fd = cap_err.saved_fd # type: ignore[union-attr]637+638 return_value = None639 exception: BaseException | None = None640 exit_code = 0641 32 unmodified lines674 exc_info = sys.exc_info()675 finally:676 sys.stdout.flush()677 sys.stderr.flush()678+679+ # Stop fd capture and merge the captured bytes into680+ # the stdout/stderr BytesIO streams. BytesIOCopy mirrors681+ # those writes into outstreams[2] automatically.682+ if cap_out is not None and cap_err is not None:683+ fd_out = cap_out.stop()684+ fd_err = cap_err.stop()685+ if fd_out:686+ outstreams[0].write(fd_out)687+ if fd_err:688+ outstreams[1].write(fd_err)689+690 stdout = outstreams[0].getvalue()691 stderr = outstreams[1].getvalue()692 output = outstreams[2].getvalue()693 43 unmodified linesmodified:tests/test_options.py+817 added
2580 unmodified lines2581 assert result.output == repr(expected)2582 2583 2584 @pytest.mark.parametrize(2585+ ("opts", "args", "expected"),2586+ [2587+ # #3403 reproducer: enable/disable pair with explicit ``default=True``2588+ # on the positive flag, declared after (inner decorator) the negative.2589+ # https://github.com/pallets/click/issues/34032590+ pytest.param(2591+ [2592+ ("--without-xyz", {"flag_value": False}),2593+ ("--with-xyz", {"flag_value": True, "default": True}),2594+ ],2595+ [],2596+ True,2597+ id="3403-reproducer-no-args",2598+ ),2599+ pytest.param(2600+ [2601+ ("--without-xyz", {"flag_value": False}),2602+ ("--with-xyz", {"flag_value": True, "default": True}),2603+ ],2604+ ["--with-xyz"],2605+ True,2606+ id="3403-reproducer-with-only",2607+ ),2608+ pytest.param(2609+ [2610+ ("--without-xyz", {"flag_value": False}),2611+ ("--with-xyz", {"flag_value": True, "default": True}),2612+ ],2613+ ["--without-xyz"],2614+ False,2615+ id="3403-reproducer-without-only",2616+ ),2617+ # When both flags are passed, the parser keeps the last value seen.2618+ pytest.param(2619+ [2620+ ("--without-xyz", {"flag_value": False}),2621+ ("--with-xyz", {"flag_value": True, "default": True}),2622+ ],2623+ ["--with-xyz", "--without-xyz"],2624+ False,2625+ id="3403-reproducer-with-then-without",2626+ ),2627+ pytest.param(2628+ [2629+ ("--without-xyz", {"flag_value": False}),2630+ ("--with-xyz", {"flag_value": True, "default": True}),2631+ ],2632+ ["--without-xyz", "--with-xyz"],2633+ True,2634+ id="3403-reproducer-without-then-with",2635+ ),2636+ # Order-independence: explicit ``default=True`` on the OUTER2637+ # decorator (declared first) must produce the same behavior.2638+ pytest.param(2639+ [2640+ ("--with-xyz", {"flag_value": True, "default": True}),2641+ ("--without-xyz", {"flag_value": False}),2642+ ],2643+ [],2644+ True,2645+ id="explicit-default-outer-no-args",2646+ ),2647+ pytest.param(2648+ [2649+ ("--with-xyz", {"flag_value": True, "default": True}),2650+ ("--without-xyz", {"flag_value": False}),2651+ ],2652+ ["--without-xyz"],2653+ False,2654+ id="explicit-default-outer-cmdline-overrides",2655+ ),2656+ # Explicit ``default=False`` on the negative flag wins over the2657+ # auto-derived default of the positive one. Result value is False2658+ # either way, but the assertion still guards source tracking.2659+ pytest.param(2660+ [2661+ ("--with-xyz", {"flag_value": True}),2662+ ("--without-xyz", {"flag_value": False, "default": False}),2663+ ],2664+ [],2665+ False,2666+ id="explicit-default-false-on-negative",2667+ ),2668+ # Explicit ``default=True`` on the negative flag is unusual but2669+ # legal: post-#3239, it is a literal Python value, not a sentinel.2670+ pytest.param(2671+ [2672+ ("--with-xyz", {"flag_value": True}),2673+ ("--without-xyz", {"flag_value": False, "default": True}),2674+ ],2675+ [],2676+ True,2677+ id="explicit-default-true-on-negative",2678+ ),2679+ # Both options carry an explicit default: last-wins, so the option2680+ # declared last in the source code keeps the slot. Confirms the2681+ # explicit-beats-auto tie-break does not also promote first-declared2682+ # over a later explicit default.2683+ pytest.param(2684+ [2685+ ("--with-xyz", {"flag_value": True, "default": True}),2686+ ("--without-xyz", {"flag_value": False, "default": False}),2687+ ],2688+ [],2689+ False,2690+ id="both-explicit-defaults-last-wins",2691+ ),2692+ pytest.param(2693+ [2694+ ("--without-xyz", {"flag_value": False, "default": False}),2695+ ("--with-xyz", {"flag_value": True, "default": True}),2696+ ],2697+ [],2698+ True,2699+ id="both-explicit-defaults-last-wins-swapped",2700+ ),2701+ # No option has an explicit default: every boolean flag2702+ # auto-derives ``default=False`` regardless of its ``flag_value``,2703+ # so the slot is False either way. Last-wins applies under the hood2704+ # but is not observable because both values are equal.2705+ pytest.param(2706+ [2707+ ("--with-xyz", {"flag_value": True}),2708+ ("--without-xyz", {"flag_value": False}),2709+ ],2710+ [],2711+ False,2712+ id="both-auto-defaults-positive-first",2713+ ),2714+ pytest.param(2715+ [2716+ ("--without-xyz", {"flag_value": False}),2717+ ("--with-xyz", {"flag_value": True}),2718+ ],2719+ [],2720+ False,2721+ id="both-auto-defaults-negative-first",2722+ ),2723+ # Explicit ``default=False`` matching the auto-derived value:2724+ # the explicit option still wins the slot. Confirms tracking is2725+ # source-based and not value-based.2726+ pytest.param(2727+ [2728+ ("--with-xyz", {"flag_value": True, "default": False}),2729+ ("--without-xyz", {"flag_value": False}),2730+ ],2731+ [],2732+ False,2733+ id="explicit-default-matches-auto-still-wins",2734+ ),2735+ # Three-flag group: the explicit default wins regardless of its2736+ # position in the decorator stack.2737+ pytest.param(2738+ [2739+ ("--auto-a", {"flag_value": True}),2740+ ("--explicit", {"flag_value": False, "default": False}),2741+ ("--auto-b", {"flag_value": True}),2742+ ],2743+ [],2744+ False,2745+ id="three-flags-explicit-in-middle",2746+ ),2747+ pytest.param(2748+ [2749+ ("--auto-a", {"flag_value": True}),2750+ ("--auto-b", {"flag_value": False}),2751+ ("--explicit", {"flag_value": True, "default": True}),2752+ ],2753+ [],2754+ True,2755+ id="three-flags-explicit-last",2756+ ),2757+ pytest.param(2758+ [2759+ ("--explicit", {"flag_value": False, "default": False}),2760+ ("--auto-a", {"flag_value": True}),2761+ ("--auto-b", {"flag_value": True}),2762+ ],2763+ [],2764+ False,2765+ id="three-flags-explicit-first",2766+ ),2767+ # Three-state pattern: explicit ``default=None`` on one option2768+ # must beat a sibling's auto-derived ``False``.2769+ pytest.param(2770+ [2771+ ("--without-xyz", {"flag_value": False}),2772+ ("--with-xyz", {"flag_value": True, "default": None}),2773+ ],2774+ [],2775+ None,2776+ id="explicit-default-none-three-state",2777+ ),2778+ pytest.param(2779+ [2780+ ("--without-xyz", {"flag_value": False}),2781+ ("--with-xyz", {"flag_value": True, "default": None}),2782+ ],2783+ ["--with-xyz"],2784+ True,2785+ id="explicit-default-none-three-state-with",2786+ ),2787+ pytest.param(2788+ [2789+ ("--without-xyz", {"flag_value": False}),2790+ ("--with-xyz", {"flag_value": True, "default": None}),2791+ ],2792+ ["--without-xyz"],2793+ False,2794+ id="explicit-default-none-three-state-without",2795+ ),2796+ # Command-line input always beats any default, regardless of2797+ # which option carried the explicit default.2798+ pytest.param(2799+ [2800+ ("--with-xyz", {"flag_value": True, "default": True}),2801+ ("--without-xyz", {"flag_value": False}),2802+ ],2803+ ["--without-xyz"],2804+ False,2805+ id="cmdline-beats-explicit-default",2806+ ),2807+ pytest.param(2808+ [2809+ ("--without-xyz", {"flag_value": False, "default": False}),2810+ ("--with-xyz", {"flag_value": True}),2811+ ],2812+ ["--with-xyz"],2813+ True,2814+ id="cmdline-beats-explicit-default-symmetric",2815+ ),2816+ ],2817+)2818+def test_bool_flag_group_competition(runner, opts, args, expected):2819+ """Competing boolean flags sharing a single parameter name.2820+2821+ Verifies the arbitration rules between options that target the same2822+ variable name in a feature-switch group.2823+2824+ Regression test for https://github.com/pallets/click/issues/34032825+ """2826+2827+ @click.command()2828+ def cli(enable_xyz):2829+ click.echo(repr(enable_xyz), nl=False)2830+2831+ for opt_name, opt_kwargs in opts:2832+ cli = click.option(opt_name, "enable_xyz", **opt_kwargs)(cli)2833+2834+ result = runner.invoke(cli, args)2835+ assert result.exit_code == 0, result.output2836+ assert result.output == repr(expected)2837+2838+2839+@pytest.mark.parametrize(2840+ ("envvar_value", "args", "expected"),2841+ [2842+ # An env var on one option in the group provides ENVIRONMENT source,2843+ # which beats any sibling's DEFAULT regardless of explicit-default.2844+ ("1", [], True),2845+ ("0", [], False),2846+ # Command-line still beats the env var.2847+ ("0", ["--with-xyz"], True),2848+ ("1", ["--without-xyz"], False),2849+ ],2850+)2851+def test_bool_flag_group_competition_with_envvar(2852+ runner, monkeypatch, envvar_value, args, expected2853+):2854+ monkeypatch.setenv("XYZ", envvar_value)2855+2856+ @click.command()2857+ @click.option("--without-xyz", "enable_xyz", flag_value=False)2858+ @click.option(2859+ "--with-xyz",2860+ "enable_xyz",2861+ flag_value=True,2862+ default=False,2863+ envvar="XYZ",2864+ )2865+ def cli(enable_xyz):2866+ click.echo(repr(enable_xyz), nl=False)2867+2868+ result = runner.invoke(cli, args)2869+ assert result.exit_code == 0, result.output2870+ assert result.output == repr(expected)2871+2872+2873+@pytest.mark.parametrize(2874+ ("default_map", "args", "expected"),2875+ [2876+ # ``default_map`` provides DEFAULT_MAP source, beating either default.2877+ ({"enable_xyz": True}, [], True),2878+ ({"enable_xyz": False}, [], False),2879+ # Command-line still beats default_map.2880+ ({"enable_xyz": False}, ["--with-xyz"], True),2881+ ({"enable_xyz": True}, ["--without-xyz"], False),2882+ ],2883+)2884+def test_bool_flag_group_competition_with_default_map(2885+ runner, default_map, args, expected2886+):2887+ @click.command()2888+ @click.option("--without-xyz", "enable_xyz", flag_value=False)2889+ @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)2890+ def cli(enable_xyz):2891+ click.echo(repr(enable_xyz), nl=False)2892+2893+ result = runner.invoke(cli, args, default_map=default_map)2894+ assert result.exit_code == 0, result.output2895+ assert result.output == repr(expected)2896+2897+2898+@pytest.mark.parametrize(2899+ ("opts", "args", "expected"),2900+ [2901+ # Non-boolean feature switch group: classic --upper/--lower2902+ # pattern. The option with ``default=True`` acts as the default2903+ # via the substitution rule (#3239) for non-boolean ``flag_value``.2904+ pytest.param(2905+ [2906+ ("--upper", {"flag_value": "upper", "default": True}),2907+ ("--lower", {"flag_value": "lower"}),2908+ ],2909+ [],2910+ "upper",2911+ id="string-default-true-substitutes-to-flag-value",2912+ ),2913+ pytest.param(2914+ [2915+ ("--upper", {"flag_value": "upper", "default": True}),2916+ ("--lower", {"flag_value": "lower"}),2917+ ],2918+ ["--upper"],2919+ "upper",2920+ id="string-default-true-cmdline-positive",2921+ ),2922+ pytest.param(2923+ [2924+ ("--upper", {"flag_value": "upper", "default": True}),2925+ ("--lower", {"flag_value": "lower"}),2926+ ],2927+ ["--lower"],2928+ "lower",2929+ id="string-default-true-cmdline-overrides",2930+ ),2931+ # Explicit literal string default beats sibling's absent default.2932+ # Confirms the explicit-beats-absent rule applies regardless of type.2933+ pytest.param(2934+ [2935+ ("--upper", {"flag_value": "upper", "default": "lower"}),2936+ ("--lower", {"flag_value": "lower"}),2937+ ],2938+ [],2939+ "lower",2940+ id="string-explicit-default-wins-over-absent",2941+ ),2942+ pytest.param(2943+ [2944+ ("--upper", {"flag_value": "upper"}),2945+ ("--lower", {"flag_value": "lower", "default": "upper"}),2946+ ],2947+ [],2948+ "upper",2949+ id="string-explicit-default-wins-from-second-position",2950+ ),2951+ # Empty string as ``flag_value``: still a legal value, including2952+ # under the ``default=True`` substitution rule.2953+ pytest.param(2954+ [2955+ ("--empty", {"flag_value": "", "default": True}),2956+ ("--filled", {"flag_value": "filled"}),2957+ ],2958+ [],2959+ "",2960+ id="empty-string-flag-value-default-true",2961+ ),2962+ pytest.param(2963+ [2964+ ("--empty", {"flag_value": "", "default": True}),2965+ ("--filled", {"flag_value": "filled"}),2966+ ],2967+ ["--empty"],2968+ "",2969+ id="empty-string-flag-value-cmdline",2970+ ),2971+ # Empty string as ``default``: explicit empty string beats2972+ # the sibling's absent default.2973+ pytest.param(2974+ [2975+ ("--upper", {"flag_value": "upper", "default": ""}),2976+ ("--lower", {"flag_value": "lower"}),2977+ ],2978+ [],2979+ "",2980+ id="empty-string-explicit-default",2981+ ),2982+ # ``flag_value=None`` is a legal flag value: when the option is2983+ # activated, the function receives ``None``.2984+ pytest.param(2985+ [2986+ ("--none", {"flag_value": None, "default": "fallback"}),2987+ ("--other", {"flag_value": "other"}),2988+ ],2989+ [],2990+ "fallback",2991+ id="none-flag-value-default-fallback",2992+ ),2993+ pytest.param(2994+ [2995+ ("--none", {"flag_value": None, "default": "fallback"}),2996+ ("--other", {"flag_value": "other"}),2997+ ],2998+ ["--none"],2999+ None,3000+ id="none-flag-value-cmdline-passes-none",3001+ ),3002+ pytest.param(3003+ [3004+ ("--none", {"flag_value": None, "default": "fallback"}),3005+ ("--other", {"flag_value": "other"}),3006+ ],3007+ ["--other"],3008+ "other",3009+ id="none-flag-value-cmdline-passes-other",3010+ ),3011+ # Explicit ``default=None`` is a real value (not absence) and3012+ # must beat a sibling's absent default. Three-state pattern for3013+ # non-boolean flag groups.3014+ pytest.param(3015+ [3016+ ("--upper", {"flag_value": "upper", "default": None}),3017+ ("--lower", {"flag_value": "lower"}),3018+ ],3019+ [],3020+ None,3021+ id="explicit-default-none-three-state",3022+ ),3023+ pytest.param(3024+ [3025+ ("--upper", {"flag_value": "upper", "default": None}),3026+ ("--lower", {"flag_value": "lower"}),3027+ ],3028+ ["--upper"],3029+ "upper",3030+ id="explicit-default-none-cmdline-upper",3031+ ),3032+ pytest.param(3033+ [3034+ ("--upper", {"flag_value": "upper", "default": None}),3035+ ("--lower", {"flag_value": "lower"}),3036+ ],3037+ ["--lower"],3038+ "lower",3039+ id="explicit-default-none-cmdline-lower",3040+ ),3041+ # Passing ``default=UNSET`` explicitly is the same as not passing3042+ # ``default`` at all, so the sibling's explicit default wins.3043+ pytest.param(3044+ [3045+ ("--upper", {"flag_value": "upper", "default": UNSET}),3046+ ("--lower", {"flag_value": "lower", "default": "lower"}),3047+ ],3048+ [],3049+ "lower",3050+ id="unset-default-equivalent-to-absent",3051+ ),3052+ pytest.param(3053+ [3054+ ("--upper", {"flag_value": "upper", "default": UNSET}),3055+ ("--lower", {"flag_value": "lower", "default": "lower"}),3056+ ],3057+ ["--upper"],3058+ "upper",3059+ id="unset-default-cmdline-still-works",3060+ ),3061+ # Neither option has a default: the slot resolves to ``None``3062+ # because non-boolean flags do not auto-derive a default.3063+ pytest.param(3064+ [3065+ ("--upper", {"flag_value": "upper"}),3066+ ("--lower", {"flag_value": "lower"}),3067+ ],3068+ [],3069+ None,3070+ id="non-boolean-no-defaults-resolves-to-none",3071+ ),3072+ pytest.param(3073+ [3074+ ("--upper", {"flag_value": "upper"}),3075+ ("--lower", {"flag_value": "lower"}),3076+ ],3077+ ["--upper"],3078+ "upper",3079+ id="non-boolean-no-defaults-cmdline-still-works",3080+ ),3081+ # Three-flag string group: explicit default wins from any3082+ # position in the decorator stack.3083+ pytest.param(3084+ [3085+ ("--upper", {"flag_value": "upper"}),3086+ ("--mixed", {"flag_value": "MiXeD", "default": "MiXeD"}),3087+ ("--lower", {"flag_value": "lower"}),3088+ ],3089+ [],3090+ "MiXeD",3091+ id="three-flags-explicit-default-in-middle",3092+ ),3093+ pytest.param(3094+ [3095+ ("--upper", {"flag_value": "upper"}),3096+ ("--lower", {"flag_value": "lower"}),3097+ ("--default-choice", {"flag_value": "chosen", "default": True}),3098+ ],3099+ [],3100+ "chosen",3101+ id="three-flags-default-true-substitution-last",3102+ ),3103+ # Both options have explicit defaults: last-wins, so the option3104+ # declared last keeps the slot, regardless of value type.3105+ pytest.param(3106+ [3107+ ("--upper", {"flag_value": "upper", "default": "first"}),3108+ ("--lower", {"flag_value": "lower", "default": "second"}),3109+ ],3110+ [],3111+ "second",3112+ id="both-explicit-defaults-string-last-wins",3113+ ),3114+ # Mixed boolean and non-boolean ``flag_value`` in the same group3115+ # is allowed. Both options here carry an explicit default, so last-wins3116+ # picks the option declared last regardless of value type. The boolean3117+ # ``default=False`` is a literal value (post-#3239), not a sentinel.3118+ pytest.param(3119+ [3120+ ("--bool-flag", {"flag_value": True, "default": False}),3121+ ("--str-flag", {"flag_value": "named", "default": "explicit"}),3122+ ],3123+ [],3124+ "explicit",3125+ id="mixed-bool-and-string-last-wins",3126+ ),3127+ pytest.param(3128+ [3129+ ("--str-flag", {"flag_value": "named", "default": "explicit"}),3130+ ("--bool-flag", {"flag_value": True, "default": False}),3131+ ],3132+ [],3133+ False,3134+ id="mixed-bool-and-string-last-wins-swapped",3135+ ),3136+ # Empty string default coexisting with ``default=True``3137+ # substitution: ``default=""`` is explicit, ``default=True`` is also3138+ # explicit (and substitutes to the option's ``flag_value``). Last-wins3139+ # picks the option declared last.3140+ pytest.param(3141+ [3142+ ("--upper", {"flag_value": "upper", "default": True}),3143+ ("--blank", {"flag_value": "blank", "default": ""}),3144+ ],3145+ [],3146+ "",3147+ id="default-true-vs-empty-string-last-wins",3148+ ),3149+ pytest.param(3150+ [3151+ ("--blank", {"flag_value": "blank", "default": ""}),3152+ ("--upper", {"flag_value": "upper", "default": True}),3153+ ],3154+ [],3155+ "upper",3156+ id="default-true-vs-empty-string-last-wins-swapped",3157+ ),3158+ ],3159+)3160+def test_flag_group_competition_non_boolean(runner, opts, args, expected):3161+ """Same arbitration rules as :func:`test_bool_flag_group_competition`,3162+ but for feature-switch groups with non-boolean ``flag_value``.3163+ """3164+3165+ @click.command()3166+ def cli(case):3167+ click.echo(repr(case), nl=False)3168+3169+ for opt_name, opt_kwargs in opts:3170+ cli = click.option(opt_name, "case", **opt_kwargs)(cli)3171+3172+ result = runner.invoke(cli, args)3173+ assert result.exit_code == 0, result.output3174+ assert result.output == repr(expected)3175+3176+3177+@pytest.mark.parametrize(3178+ ("default_a", "default_b", "args", "expected"),3179+ [3180+ # ``default=UNSET`` and an absent ``default`` keyword must produce3181+ # identical behavior. Both options here are bare boolean flags, so3182+ # both auto-derive ``False`` and last-wins applies (``--a`` is3183+ # processed last); the value is ``False`` either way.3184+ (UNSET, UNSET, [], False),3185+ # ``default=UNSET`` on one side, explicit on the other: the explicit3186+ # one wins regardless of decorator order.3187+ (UNSET, True, [], True),3188+ (True, UNSET, [], True),3189+ (UNSET, False, [], False),3190+ (False, UNSET, [], False),3191+ # ``default=None`` is a real value, distinct from ``UNSET``, and3192+ # remains explicit even when the sibling carries an explicit3193+ # boolean default (3-state).3194+ (None, UNSET, [], None),3195+ (UNSET, None, [], None),3196+ # Explicit ``None`` competing with explicit boolean. The decorator3197+ # order in this test puts ``--a`` last in ``params``, so the value3198+ # carried by ``default_a`` wins these "both explicit" ties under3199+ # last-wins.3200+ (None, True, [], None),3201+ (True, None, [], True),3202+ ],3203+)3204+def test_flag_group_unset_vs_none_vs_explicit(3205+ runner, default_a, default_b, args, expected3206+):3207+ """``UNSET`` as an explicit ``default`` must be indistinguishable from3208+ omitting ``default`` entirely, while ``None`` is a real explicit value.3209+ """3210+ a_kwargs = {"flag_value": True}3211+ if default_a is not UNSET:3212+ a_kwargs["default"] = default_a3213+ elif default_a is UNSET:3214+ # Pass UNSET explicitly to verify it's treated as absent. Skip when3215+ # the test wants the absent-keyword case (matches default behavior3216+ # because ``Parameter.__init__`` defaults ``default`` to ``UNSET``).3217+ a_kwargs["default"] = UNSET3218+3219+ b_kwargs = {"flag_value": False}3220+ if default_b is not UNSET:3221+ b_kwargs["default"] = default_b3222+ elif default_b is UNSET:3223+ b_kwargs["default"] = UNSET3224+3225+ @click.command()3226+ @click.option("--b", "state", **b_kwargs)3227+ @click.option("--a", "state", **a_kwargs)3228+ def cli(state):3229+ click.echo(repr(state), nl=False)3230+3231+ result = runner.invoke(cli, args)3232+ assert result.exit_code == 0, result.output3233+ assert result.output == repr(expected)3234+3235+3236+def test_flag_group_competition_duplicate_option_name(runner):3237+ """The same option name declared twice on the same command is a user3238+ error.3239+ """3240+3241+ @click.command()3242+ @click.option("--xyz", default="first")3243+ @click.option("--xyz", default="second")3244+ def cli(xyz):3245+ click.echo(repr(xyz), nl=False)3246+3247+ result = runner.invoke(cli, [])3248+ assert result.exit_code == 13249+ assert isinstance(result.exception, UserWarning)3250+ assert "used more than once" in str(result.exception)3251+3252+3253+@pytest.mark.parametrize(3254+ ("args", "expected"),3255+ [3256+ (["--with-xyz", "--with-xyz"], True),3257+ (["--without-xyz", "--without-xyz"], False),3258+ (["--with-xyz", "--without-xyz", "--with-xyz"], True),3259+ (["--without-xyz", "--with-xyz", "--without-xyz"], False),3260+ ],3261+)3262+def test_flag_group_competition_repeated_cmdline(runner, args, expected):3263+ """Duplicate flags passed in different order to the CLI."""3264+3265+ @click.command()3266+ @click.option("--without-xyz", "enable_xyz", flag_value=False)3267+ @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3268+ def cli(enable_xyz):3269+ click.echo(repr(enable_xyz), nl=False)3270+3271+ result = runner.invoke(cli, args)3272+ assert result.exit_code == 0, result.output3273+ assert result.output == repr(expected)3274+3275+3276+@pytest.mark.parametrize(3277+ ("opts", "args", "expected"),3278+ [3279+ pytest.param(3280+ [3281+ ("--a", {"flag_value": "a"}),3282+ ("--b", {"flag_value": "b"}),3283+ ("--c", {"flag_value": "c"}),3284+ ("--d", {"flag_value": "d"}),3285+ ],3286+ [],3287+ None,3288+ id="four-flags-no-defaults-resolves-to-none",3289+ ),3290+ pytest.param(3291+ [3292+ ("--a", {"flag_value": "a"}),3293+ ("--b", {"flag_value": "b", "default": "from-b"}),3294+ ("--c", {"flag_value": "c"}),3295+ ("--d", {"flag_value": "d"}),3296+ ],3297+ [],3298+ "from-b",3299+ id="four-flags-only-second-explicit-wins",3300+ ),3301+ pytest.param(3302+ [3303+ ("--a", {"flag_value": "a"}),3304+ ("--b", {"flag_value": "b", "default": "from-b"}),3305+ ("--c", {"flag_value": "c"}),3306+ ("--d", {"flag_value": "d", "default": "from-d"}),3307+ ],3308+ [],3309+ "from-d",3310+ id="four-flags-two-explicit-last-wins",3311+ ),3312+ pytest.param(3313+ [3314+ ("--a", {"flag_value": "a"}),3315+ ("--b", {"flag_value": "b"}),3316+ ("--c", {"flag_value": "c"}),3317+ ("--d", {"flag_value": "d"}),3318+ ],3319+ ["--c"],3320+ "c",3321+ id="four-flags-cmdline-beats-everything",3322+ ),3323+ ],3324+)3325+def test_flag_group_competition_four_flags(runner, opts, args, expected):3326+ """Arbitration rules applies to groups of any size."""3327+3328+ @click.command()3329+ def cli(case):3330+ click.echo(repr(case), nl=False)3331+3332+ for opt_name, opt_kwargs in opts:3333+ cli = click.option(opt_name, "case", **opt_kwargs)(cli)3334+3335+ result = runner.invoke(cli, args)3336+ assert result.exit_code == 0, result.output3337+ assert result.output == repr(expected)3338+3339+3340+@pytest.mark.parametrize(3341+ ("env", "default_map", "args", "expected"),3342+ [3343+ # ``auto_envvar_prefix`` produces an ``ENVIRONMENT`` source through a3344+ # different code path than an explicit ``envvar=`` keyword. It still3345+ # must beat any sibling default and be beaten by command-line input.3346+ pytest.param(3347+ {"AUTO_ENABLE_XYZ": "1"},3348+ None,3349+ [],3350+ True,3351+ id="auto-envvar-prefix-beats-default",3352+ ),3353+ pytest.param(3354+ {"AUTO_ENABLE_XYZ": "1"},3355+ None,3356+ ["--without-xyz"],3357+ False,3358+ id="auto-envvar-prefix-loses-to-cmdline",3359+ ),3360+ # ``Sentinel.UNSET`` in ``default_map`` must be skipped (#32243361+ # carve-out): the lookup falls through to the parameter default.3362+ # Inside a feature switch group, the explicit ``default=True`` on3363+ # ``--with-xyz`` then wins over the sibling's auto-``False``.3364+ pytest.param(3365+ {},3366+ {"enable_xyz": UNSET},3367+ [],3368+ True,3369+ id="unset-default-map-falls-through-to-explicit-default",3370+ ),3371+ pytest.param(3372+ {},3373+ {"enable_xyz": False},3374+ [],3375+ False,3376+ id="real-default-map-beats-explicit-default",3377+ ),3378+ ],3379+)3380+def test_flag_group_competition_envvar_prefix_and_unset_default_map(3381+ runner, monkeypatch, env, default_map, args, expected3382+):3383+ for name, value in env.items():3384+ monkeypatch.setenv(name, value)3385+3386+ @click.command()3387+ @click.option("--without-xyz", "enable_xyz", flag_value=False)3388+ @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3389+ def cli(enable_xyz):3390+ click.echo(repr(enable_xyz), nl=False)3391+3392+ invoke_kwargs = {"auto_envvar_prefix": "AUTO"}3393+ if default_map is not None:3394+ invoke_kwargs["default_map"] = default_map3395+3396+ result = runner.invoke(cli, args, **invoke_kwargs)3397+ assert result.exit_code == 0, result.output3398+ assert result.output == repr(expected)3399+3400+3401+@pytest.mark.parametrize(3402 ("flag_type", "args", "expect_output"),3403 [3404 (str, [], "Default\n"),3405 (str, ["--theflag"], "FlagValue\n"),36 unmodified linesmodified:tests/test_termui.py+256 added
986 unmodified lines987 988 assert result.output == expected_output989 assert not result.stderr990 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1991+992+993+class _CustomTypeNoValue(click.ParamType):994+ name = "custom"995+996+ def convert(self, value, param, ctx):997+ if len(value) < 4:998+ self.fail("Password must be at least 4 characters", param, ctx)999+ return value1000+1001+1002+class _CustomTypeWithRawValue(click.ParamType):1003+ name = "custom_raw"1004+1005+ def convert(self, value, param, ctx):1006+ if value == "bad":1007+ self.fail(f"rejected: {value}", param, ctx)1008+ return value1009+1010+1011+class _PasswordLengthType(click.ParamType):1012+ """Mirrors the issue's original use case: a password validator1013+ that references the user-typed value in its error message without1014+ quoting it.1015+ """1016+1017+ name = "password"1018+1019+ def convert(self, value, param, ctx):1020+ if len(value) < 10:1021+ self.fail(f"{value} is too short", param, ctx)1022+ return value1023+1024+1025+class _MixedQuotedAndRawType(click.ParamType):1026+ """Custom type that mentions the user input both quoted (built-in1027+ pattern) and raw within the same message.1028+ """1029+1030+ name = "mixed"1031+1032+ def convert(self, value, param, ctx):1033+ self.fail(f"got {value!r} which is the same as {value}", param, ctx)1034+1035+1036+class _StaticMessageType(click.ParamType):1037+ """Custom type whose error message never references the value."""1038+1039+ name = "static"1040+1041+ def convert(self, value, param, ctx):1042+ self.fail("Authentication failed for this account", param, ctx)1043+1044+1045+class _RejectAllRawType(click.ParamType):1046+ """Always rejects, with the raw value (unquoted) in the message."""1047+1048+ name = "reject_all_raw"1049+1050+ def convert(self, value, param, ctx):1051+ self.fail(f"rejected: {value}", param, ctx)1052+1053+1054+class _MultiRawType(click.ParamType):1055+ """Mentions the raw value multiple times in the same message."""1056+1057+ name = "multi_raw"1058+1059+ def convert(self, value, param, ctx):1060+ self.fail(f"got {value} but {value} is bad", param, ctx)1061+1062+1063+class _MultiReprType(click.ParamType):1064+ """Mentions ``repr(value)`` multiple times in the same message."""1065+1066+ name = "multi_repr"1067+1068+ def convert(self, value, param, ctx):1069+ self.fail(f"got {value!r} and {value!r}", param, ctx)1070+1071+1072+class _ApostropheReprType(click.ParamType):1073+ """Custom type whose ``repr(value)`` switches to double quotes when1074+ the value itself contains a single quote.1075+ """1076+1077+ name = "apostrophe_repr"1078+1079+ def convert(self, value, param, ctx):1080+ self.fail(f"rejected {value!r}", param, ctx)1081+1082+1083+@pytest.mark.parametrize(1084+ ("type", "user_input", "expected_fragment", "unexpected_fragment"),1085+ [1086+ pytest.param(1087+ click.INT,1088+ "bad",1089+ "'***' is not a valid integer",1090+ "bad",1091+ id="builtin-int-masks-repr-value",1092+ ),1093+ pytest.param(1094+ _CustomTypeNoValue(),1095+ "bad",1096+ "Password must be at least 4 characters",1097+ None,1098+ id="custom-no-value-shows-message",1099+ ),1100+ pytest.param(1101+ _CustomTypeWithRawValue(),1102+ "bad",1103+ "rejected: '***'",1104+ "bad",1105+ id="custom-raw-value-masked",1106+ ),1107+ pytest.param(1108+ _PasswordLengthType(),1109+ "PASSWORD",1110+ "'***' is too short",1111+ "PASSWORD",1112+ id="unquoted-custom-message-should-mask-not-fallback",1113+ ),1114+ pytest.param(1115+ _MixedQuotedAndRawType(),1116+ "leakybits",1117+ "got '***' which is the same as '***'",1118+ "leakybits",1119+ id="mixed-quoted-and-raw-both-masked-at-source",1120+ ),1121+ pytest.param(1122+ click.IntRange(min=10, max=99),1123+ "1",1124+ "is not in the range",1125+ None,1126+ id="intrange-numeric-substring-falls-back-to-generic",1127+ ),1128+ pytest.param(1129+ _StaticMessageType(),1130+ "ent",1131+ "Authentication failed for this account",1132+ None,1133+ id="partial-word-match-falls-back-to-generic",1134+ ),1135+ # When the raw (unquoted) value appears in the message, mask it instead1136+ # of replacing the whole message with a generic fallback that throws1137+ # useful information away.1138+ pytest.param(1139+ _RejectAllRawType(),1140+ "secret",1141+ "rejected: '***'",1142+ "secret",1143+ id="raw-value-should-be-masked-not-fallback",1144+ ),1145+ # When the raw value occurs more than1146+ # once unquoted, every occurrence must be masked.1147+ pytest.param(1148+ _MultiRawType(),1149+ "secret",1150+ "got '***' but '***' is bad",1151+ "secret",1152+ id="multi-occurrence-raw-mask-all",1153+ ),1154+ pytest.param(1155+ _MultiReprType(),1156+ "secret",1157+ "got '***' and '***'",1158+ "secret",1159+ id="multi-occurrence-repr-mask-all",1160+ ),1161+ pytest.param(1162+ _PasswordLengthType(),1163+ "a.b*c+",1164+ "'***' is too short",1165+ "a.b*c+",1166+ id="regex-special-chars-must-be-escaped",1167+ ),1168+ pytest.param(1169+ _PasswordLengthType(),1170+ "пароль",1171+ "'***' is too short",1172+ "пароль",1173+ id="unicode-value-masked",1174+ ),1175+ pytest.param(1176+ _ApostropheReprType(),1177+ "it's",1178+ "rejected '***'",1179+ "it's",1180+ id="apostrophe-in-value-uses-double-quote-repr",1181+ ),1182+ pytest.param(1183+ _MixedQuotedAndRawType(),1184+ "leakybits",1185+ "got '***' which is the same as '***'",1186+ "leakybits",1187+ id="mixed-quoted-and-raw-mask-both",1188+ ),1189+ ],1190+)1191+def test_hide_input_error_message(1192+ runner, type, user_input, expected_fragment, unexpected_fragment1193+):1194+ """https://github.com/pallets/click/issues/2809"""1195+1196+ @click.command()1197+ @click.option("--password", prompt=True, hide_input=True, type=type)1198+ def cli(password):1199+ click.echo(password)1200+1201+ result = runner.invoke(cli, input=user_input)1202+ assert expected_fragment in result.output1203+ if unexpected_fragment is not None:1204+ assert unexpected_fragment not in result.output1205+1206+1207+def test_hide_input_confirmation_prompt_mismatch_unaffected(runner):1208+ """The ``hide_input`` mask logic only applies to ``value_proc``1209+ failures. The separate ``confirmation_prompt`` mismatch path must1210+ keep emitting its own message, with no value leak from either entry.1211+ """1212+1213+ @click.command()1214+ @click.option("--password", prompt=True, confirmation_prompt=True, hide_input=True)1215+ def cli(password):1216+ click.echo(f"got: {password}")1217+1218+ # First pair mismatches, second pair matches.1219+ result = runner.invoke(cli, input="firstone\nsecondone\nfinalone\nfinalone\n")1220+ assert "Error: The two entered values do not match." in result.output1221+ assert "firstone" not in result.output1222+ assert "secondone" not in result.output1223+ # Successful prompt echoes the final value back via the command body.1224+ assert "got: finalone" in result.output1225+ assert result.exit_code == 01226+1227+1228+def test_hide_input_value_never_leaks_when_err_true(runner):1229+ """``click.prompt(..., err=True)`` routes its error message to1230+ stderr. The masking logic must apply on that path too: the raw1231+ input must not appear on either stream.1232+ """1233+1234+ @click.command()1235+ def cli():1236+ value = click.prompt(1237+ "Password",1238+ hide_input=True,1239+ type=_PasswordLengthType(),1240+ err=True,1241+ )1242+ click.echo(value)1243+1244+ result = runner.invoke(cli, input="leaky\n", mix_stderr=False)1245+ assert "leaky" not in result.stdout1246+ assert "leaky" not in result.stderrmodified:tests/test_testing.py+218 added-16 removed
1 import faulthandler2+import io3 import os4 import pdb5 import sys6 from io import BytesIO515 unmodified lines522 523 assert pdb.Pdb.__init__ is original524 525 525-def test_faulthandler_enable(runner):526- """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527- ``io.UnsupportedOperation: fileno``.526+needs_fd_capture = pytest.mark.skipif(527+ sys.platform == "win32",528+ reason="fd capture not supported on Windows",529+)530 529- ``faulthandler.enable()`` needs a real OS file descriptor to register530- its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531- ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.531 533- Reproduce:https://github.com/pallets/click/issues/2865532+def test_capture_invalid_mode():533+ """Invalid capture mode raises ValueError."""534+ with pytest.raises(ValueError, match="capture"):535+ CliRunner(capture="invalid") # type: ignore[arg-type]536+537+538+@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")539+def test_capture_fd_windows_error():540+ """fd capture raises ValueError on Windows."""541+ with pytest.raises(ValueError, match="not supported on Windows"):542+ CliRunner(capture="fd")543+544+545+@needs_fd_capture546+def test_capture_fd_os_write():547+ """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""548+549+ @click.command()550+ def cli():551+ click.echo("python stdout")552+ os.write(1, b"fd stdout\n")553+ os.write(2, b"fd stderr\n")554+555+ runner = CliRunner(capture="fd")556+ result = runner.invoke(cli)557+ assert "python stdout" in result.stdout558+ assert "fd stdout" in result.stdout559+ assert "fd stderr" in result.stderr560+561+562+@needs_fd_capture563+def test_capture_fd_stale_reference():564+ """capture='fd' captures writes from stale stdout references (issue #2874).565+566+ Simulates ``from sys import stdout`` at import time, which grabs567+ the real stdout connected to fd 1. The stale object's underlying568+ FileIO uses fd 1, so redirecting fd 1 captures its writes.569 """570+ # open(1, ..., closefd=False) creates a writer whose underlying571+ # FileIO uses fd 1 directly. This mirrors the real scenario:572+ # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->573+ # FileIO(fd=1).574+ stale_stdout = open(1, "w", closefd=False) # noqa: SIM115575 576 @click.command()537- @click.option("--flag", type=bool, default=True)538- def cli(flag):539- click.echo("Executing main function...")540- if flag:541- click.echo("Registering faulthandler")542- faulthandler.enable()543- click.echo("Finished executing main function.")577+ def cli():578+ stale_stdout.write("stale write\n")579+ stale_stdout.flush()580+ click.echo("normal write")581 582+ runner = CliRunner(capture="fd")545- result = runner.invoke(cli, ["--flag", True])583+ result = runner.invoke(cli)584+ assert "normal write" in result.stdout585+ assert "stale write" in result.stdout586+587+588+@needs_fd_capture589+def test_capture_fd_logging_handler(tmp_path):590+ """capture='fd' captures logging output from a handler holding a stale591+ stderr reference (issue #2827).592+593+ stdlib logging.StreamHandler grabs sys.stderr at configuration time.594+ Under normal CliRunner (sys-level capture), the handler still writes595+ to the original stream object and output is lost. fd-level capture596+ redirects the underlying file descriptor, so the writes are captured.597+ """598+ import logging599+600+ # Create a writer backed by the real fd 2, simulating a handler601+ # configured at import time before pytest or CliRunner replaced602+ # sys.stderr. open(2, closefd=False) mirrors the real scenario:603+ # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->604+ # FileIO(fd=2).605+ stale_stderr = open(2, "w", closefd=False) # noqa: SIM115606+ handler = logging.StreamHandler(stale_stderr)607+ handler.setFormatter(logging.Formatter("%(message)s"))608+609+ logger = logging.getLogger(f"click_test_{tmp_path.name}")610+ logger.addHandler(handler)611+ logger.setLevel(logging.INFO)612+ logger.propagate = False613+614+ @click.command()615+ def cli():616+ logger.info("log from stale handler")617+ click.echo("normal echo")618+619+ # sys-level capture misses the log line (it bypasses sys.stderr).620+ runner_sys = CliRunner(capture="sys")621+ result_sys = runner_sys.invoke(cli)622+ assert "normal echo" in result_sys.output623+ assert "log from stale handler" not in result_sys.output624+625+ # fd-level capture catches it by redirecting fd 2.626+ runner_fd = CliRunner(capture="fd")627+ result_fd = runner_fd.invoke(cli)628+ assert "normal echo" in result_fd.output629+ assert "log from stale handler" in result_fd.output630+631+ logger.removeHandler(handler)632+633+634+@needs_fd_capture635+def test_capture_fd_faulthandler():636+ """faulthandler.enable() works with capture='fd' (issue #2865)."""637+638+ @click.command()639+ def cli():640+ faulthandler.enable()641+ click.echo("after faulthandler")642+643+ runner = CliRunner(capture="fd")644+ result = runner.invoke(cli)645+ assert result.exit_code == 0646+ assert "after faulthandler" in result.output647+648+649+def test_capture_sys_fileno_raises():650+ """capture='sys' leaves fileno() raising UnsupportedOperation, so user651+ code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host652+ runner's stdout (issue #3384).653+ """654+655+ @click.command()656+ def cli():657+ with pytest.raises(io.UnsupportedOperation):658+ sys.stdout.fileno()659+ with pytest.raises(io.UnsupportedOperation):660+ sys.stderr.fileno()661+ click.echo("ok")662+663+ runner = CliRunner(capture="sys")664+ result = runner.invoke(cli)665 assert result.exit_code == 0, result.output547- assert "Finished executing main function." in result.output666+ assert "ok" in result.stdout667+668+669+@needs_fd_capture670+def test_capture_fd_stderr_separation():671+ """capture='fd' properly separates fd-level stdout and stderr."""672+673+ @click.command()674+ def cli():675+ click.echo("py-out")676+ click.echo("py-err", err=True)677+ os.write(1, b"fd-out\n")678+ os.write(2, b"fd-err\n")679+680+ runner = CliRunner(capture="fd")681+ result = runner.invoke(cli)682+ assert "py-out" in result.stdout683+ assert "fd-out" in result.stdout684+ assert "py-err" in result.stderr685+ assert "fd-err" in result.stderr686+ # Mixed output has all of them687+ assert "py-out" in result.output688+ assert "py-err" in result.output689+ assert "fd-out" in result.output690+ assert "fd-err" in result.output691+692+693+@needs_fd_capture694+def test_capture_fd_nesting():695+ """Nested CliRunner.invoke() with fd capture works correctly."""696+697+ @click.command("inner")698+ def inner_cli():699+ click.echo("inner")700+701+ @click.command("outer")702+ def outer_cli():703+ click.echo("outer")704+ os.write(1, b"outer fd\n")705+ inner_runner = CliRunner(capture="fd")706+ inner_result = inner_runner.invoke(inner_cli)707+ click.echo(f"inner captured: {inner_result.stdout.strip()}")708+709+ runner = CliRunner(capture="fd")710+ result = runner.invoke(outer_cli)711+ assert "outer" in result.stdout712+ assert "outer fd" in result.stdout713+ assert "inner captured: inner" in result.stdout714+715+716+@needs_fd_capture717+@pytest.mark.parametrize("runner_capture", ["sys", "fd"])718+@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])719+def test_capture_pytest_matrix(720+ request: pytest.FixtureRequest,721+ runner_capture: str,722+ pytest_fixture: str,723+) -> None:724+ """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""725+ pytest_cap = request.getfixturevalue(pytest_fixture)726+727+ @click.command()728+ def cli() -> None:729+ click.echo("inside-stdout")730+ click.echo("inside-stderr", err=True)731+732+ runner = CliRunner(capture=runner_capture)733+ result = runner.invoke(cli)734+735+ # CliRunner sees Click's output.736+ assert result.exit_code == 0737+ assert "inside-stdout" in result.stdout738+ assert "inside-stderr" in result.stderr739+740+ # Pytest capture machinery is still working after invoke().741+ print("post-invoke-stdout")742+ print("post-invoke-stderr", file=sys.stderr)743+ captured = pytest_cap.readouterr()744+ assert "post-invoke-stdout" in captured.out745+ assert "post-invoke-stderr" in captured.err746+747+ # Click output is not leaking into Pytest.748+ assert "inside-stdout" not in captured.out749+ assert "inside-stderr" not in captured.errmodified:.gitignore+1 added-1 removed
4 unmodified lines5 .coverage*6 htmlcov/7 .tox/8 docs/_build/9-.venv9+.venv/modified:CHANGES.rst+37 added-1 removed
15 unmodified lines16 :class:`~typing.TypedDict` subclasses instead of17 ``dict[str, Any]``.18 - :class:`CompositeParamType` and the number-range base are now19 generic with abstract methods.20+- Refactor ``convert_type`` to extract type inference into a private21+ ``_guess_type`` helper, and add :func:`typing.overload` signatures.22+ :pr:`3372`23 - :class:`Parameter` typing improvements. :pr:`2805`24 25 - :class:`Parameter` is now an abstract base class, making explicit26 that it cannot be instantiated directly.21 unmodified lines48 - Use :func:`os.startfile` on Windows to open URLs in :func:`open_url`,49 replacing the ``start`` built-in which cannot be invoked without50 ``shell=True``. :issue:`3164` :pr:`3186`51 - Fix Fish shell completion errors when option help text contains newlines.49- :issue:`3043`52+ :issue:`3043` :pr:`3126`53 - Add :class:`NoSuchCommand` exception with suggestions for misspelled54 commands. :issue:`3107` :pr:`3228`55 - Use :class:`ValueError` message when conversion in :class:`FuncParamType` would56 fail. :issue:`3105` :pr:`3211`1 unmodified line58 pager. :pr:`1572`59 - :class:`~click.formatting.TextWrapper` and60 :func:`~click.formatting.wrap_text` now measure line width in visible61 characters, ignoring ANSI escape sequences. :pr:`3420`62+- Show custom error messages from types when :func:`prompt` with63+ ``hide_input=True`` fails validation, instead of always showing a64+ generic message. Built-in type messages mask the input value.65+ :issue:`2809` :pr:`3256`66+- Add ``capture`` parameter to :class:`CliRunner` with two modes: ``sys``67+ (default) and ``fd``. ``fd`` redirects file descriptors ``1`` and ``2``68+ via :func:`os.dup2` so output that bypasses ``sys.stdout`` (stale stream69+ references, C extensions, subprocesses, ``faulthandler``) is captured70+ with proper isolation. :issue:`854` :issue:`2412` :issue:`2468`71+ :issue:`2497` :issue:`2761` :issue:`2827` :issue:`2865`72+- Revert the ``8.3.3`` change that exposed the original file descriptor73+ via ``fileno()`` on the redirected ``CliRunner`` streams in the default74+ capture mode. ``os.dup2(w, sys.stdout.fileno())`` calls inside a CLI no75+ longer mutate the host runner's stdout, which broke Pytest's ``fd``-level76+ capture teardown. C-level consumers that need a real ``fd`` should use77+ ``capture="fd"``. :issue:`3384` :pr:`3391`78+- Mark additional built-in strings with ``gettext()`` to extend translation79+ coverage. :pr:`2902`80+- Fix feature switch groups (several ``flag_value`` options sharing one81+ parameter name) silently dropping an explicit ``default`` when a sibling82+ option without an explicit default was declared first. Arbitration is now83+ source-aware: a more explicit :class:`ParameterSource` always wins, and84+ within ``ParameterSource.DEFAULT``, an option that received an explicit85+ ``default=`` keyword wins over a sibling whose default was auto-derived.86+ The 8.3.x first-wins fallback for remaining ties was reverted to the87+ pre-8.3.x last-wins fallback. :issue:`3403` :pr:`3404`88+- Fix missing space between option help text and the ``(DEPRECATED)``89+ label, and localize the option label so it matches the command label.90+ The label and the ``DeprecationWarning`` reason suffix are now produced91+ by shared helpers. :pr:`3423`92+- Document short option stacking (``-abc`` is parsed as ``-a -b -c``) and93+ clarify that multi-character short option names are not supported.94+ :issue:`2779` :pr:`3431`95 96 Version 8.3.397 -------------98 1364 unmodified lines