From df7fe0b97297d07748dc2f88008e2bd136e0cf43 Mon Sep 17 00:00:00 2001 From: Kevin Deldycke Date: Thu, 5 Nov 2026 12:10:10 +0400 Subject: [PATCH] Remove issue and PR references outside the changelog --- .github/ISSUE_TEMPLATE/bug-report.md | 4 +- .github/ISSUE_TEMPLATE/config.yml | 3 - CHANGES.md | 3 +- docs/upgrade-guides.md | 2 +- src/click/_termui_impl.py | 8 +- src/click/core.py | 83 +++++-------- src/click/decorators.py | 14 +-- src/click/shell_completion.py | 27 ++-- src/click/testing.py | 26 ++-- tests/test_abort_interrupt.py | 30 ++--- tests/test_arguments.py | 1 - tests/test_basic.py | 16 +-- tests/test_commands.py | 11 +- tests/test_context.py | 2 - tests/test_defaults.py | 43 ++----- tests/test_formatting.py | 17 ++- tests/test_options.py | 157 ++++++++---------------- tests/test_stream_lifecycle.py | 51 +++++--- tests/test_termui.py | 108 ++++++++-------- tests/test_testing.py | 20 ++- tests/test_types/test_File.py | 7 +- tests/test_types/test_convert_type.py | 16 +-- tests/test_utils/test_echo.py | 8 +- tests/test_utils/test_echo_via_pager.py | 14 +-- tests/test_utils/test_prompt.py | 9 +- tests/test_utils/test_style.py | 5 +- 26 files changed, 266 insertions(+), 419 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index 7a42e5f37..1cd6364bb 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -4,8 +4,8 @@ about: Report a bug in Click (not other projects which depend on Click) --- diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 9d26be19b..c4fc392ee 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,8 +1,5 @@ blank_issues_enabled: false contact_links: - - name: Questions on Discussions - url: https://github.com/pallets/click/discussions/ - about: Ask questions about your own code on the Discussions tab. - name: Questions on Chat url: https://discord.gg/pallets about: Ask questions about your own code on our Discord chat. diff --git a/CHANGES.md b/CHANGES.md index 3918e4bee..988ecd1cc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -54,8 +54,7 @@ Released 2026-08-24 convention. {issue}`2877` {pr}`3642` - Add {func}`custom_version_option`, a `--version` option whose output is produced by a callback, covering cases {func}`version_option` intentionally - does not. The feature set of {func}`version_option` is now frozen; see - [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581` + does not. The feature set of {func}`version_option` is now frozen. {pr}`3581` - `style()` and `secho()` no longer silently drop the 256-color index `0` (black) passed as `fg` or `bg`, and now validate color arguments. Invalid colors raise a `ValueError` instead of a `TypeError`. {pr}`3677` diff --git a/docs/upgrade-guides.md b/docs/upgrade-guides.md index 91112876b..8f250cb21 100644 --- a/docs/upgrade-guides.md +++ b/docs/upgrade-guides.md @@ -13,7 +13,7 @@ This guide assumes the user is on version 8.3.X. ### Deprecations For each deprecation, provide a brief explanation, and direct users to new function / class if available. -- `CliRunner.isolated_filesystem()` is deprecated and will be removed in Click 9.0. The helper predates Python 3 and modern pytest, and it relies on `os.chdir`, which mutates process-global state and is therefore not thread-safe. Replace it with a temporary directory (`tempfile.TemporaryDirectory`, or pytest's `tmp_path` fixture) and pass absolute paths to the command instead of relying on the current working directory. To run commands in parallel, use process-based isolation (such as `pytest-xdist`) rather than threads, since `CliRunner.invoke()` also redirects the process-global standard streams and other interpreter-wide state. See [#3700](https://github.com/pallets/click/issues/3700), [#3501](https://github.com/pallets/click/issues/3501) and the [testing guide](testing.md#running-tests-in-parallel). +- `CliRunner.isolated_filesystem()` is deprecated and will be removed in Click 9.0. The helper predates Python 3 and modern pytest, and it relies on `os.chdir`, which mutates process-global state and is therefore not thread-safe. Replace it with a temporary directory (`tempfile.TemporaryDirectory`, or pytest's `tmp_path` fixture) and pass absolute paths to the command instead of relying on the current working directory. To run commands in parallel, use process-based isolation (such as `pytest-xdist`) rather than threads, since `CliRunner.invoke()` also redirects the process-global standard streams and other interpreter-wide state. See the [testing guide](testing.md#running-tests-in-parallel). ### Removals with prior deprecation diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py index 70aabf8f1..99ba7f9d2 100644 --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -440,11 +440,9 @@ def _resolve_pager_command(cmd_parts: list[str]) -> tuple[Path, list[str]] | Non if not cmd_filepath: return None - # Normalize to an absolute path without resolving symlinks: multi-call - # binaries such as busybox derive their identity from the link they are - # invoked through, so resolving less -> busybox makes them misbehave. - # See https://github.com/pallets/click/issues/2943 and - # https://github.com/pallets/click/pull/2944 + # Normalize to an absolute path without resolving symlinks: multi-call binaries such + # as busybox derive their identity from the link they are invoked through, so + # resolving less -> busybox makes them misbehave. return Path(cmd_filepath).absolute(), cmd_parts[1:] diff --git a/src/click/core.py b/src/click/core.py index a7d4a6f89..e4b6b57c4 100644 --- a/src/click/core.py +++ b/src/click/core.py @@ -511,10 +511,9 @@ def __init__( self._depth = 0 self._parameter_source = {} # Tracks whether the option that currently owns each parameter slot in - # :attr:`params` had its ``default`` set explicitly by the user. Used - # to tie-break feature-switch groups where multiple options share a - # parameter name and both fall back to their default value. - # Refs: https://github.com/pallets/click/issues/3403 + # :attr:`params` had its ``default`` set explicitly by the user. Used to + # tie-break feature-switch groups where multiple options share a parameter name + # and both fall back to their default value. self._param_default_explicit = {} self._exit_stack = ExitStack() @@ -897,10 +896,7 @@ def invoke( # We explicitly hide the :attr:`UNSET` value to the user, as we # choose to make it an implementation detail. And because ``invoke`` # has been designed as part of Click public API, we return ``None`` - # instead. Refs: - # https://github.com/pallets/click/issues/3066 - # https://github.com/pallets/click/issues/3065 - # https://github.com/pallets/click/pull/3068 + # instead. if default_value is UNSET: default_value = None kwargs[param.name] = param.type_cast_value(ctx, default_value) @@ -1384,9 +1380,6 @@ def parse_args(self, ctx: Context, args: list[str]) -> list[str]: # # Waiting until after the initial parse to convert allows us to treat `UNSET` # more like a missing value when multiple params use the same name. - # Refs: - # https://github.com/pallets/click/issues/3071 - # https://github.com/pallets/click/pull/3079 for name, value in ctx.params.items(): if value is UNSET: ctx.params[name] = None @@ -2342,11 +2335,9 @@ def __init__( # arbitrage the default value of coupled Parameters sharing the same # self.name, like flag options), # - and the actual value of the default. - # It is confusing and is the source of many issues discussed in: - # https://github.com/pallets/click/pull/3030 - # In the future, we might think of splitting it in two, not unlike - # Option.is_flag and Option.flag_value: we could have something like - # Parameter.is_default and Parameter.default_value. + # It is confusing and is the source of many issues. In the future, we might + # think of splitting it in two, not unlike Option.is_flag and Option.flag_value: + # we could have something like Parameter.is_default and Parameter.default_value. default: t.Any | t.Callable[[], t.Any] | None = UNSET, callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None, nargs: int | None = None, @@ -2381,11 +2372,10 @@ def __init__( self.multiple = multiple self.expose_value = expose_value self.default = default - # Whether the user passed ``default`` explicitly to the constructor. - # Captured before any auto-derived default (like ``False`` for boolean - # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it - # remains ``False`` when the default was inferred rather than chosen. - # Refs: https://github.com/pallets/click/issues/3403 + # Whether the user passed ``default`` explicitly to the constructor. Captured + # before any auto-derived default (like ``0`` for a ``count`` :class:`Option`) + # replaces the :data:`UNSET` sentinel, so it remains ``False`` when the default + # was inferred rather than chosen. self._default_explicit = default is not UNSET self.is_eager = is_eager self.metavar = metavar @@ -2661,10 +2651,10 @@ def process_value(self, ctx: Context, value: t.Any) -> t.Any: :meta private: """ # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the - # cases in which `UNSET` gets special treatment explicitly at this layer - # - # Refs: - # https://github.com/pallets/click/issues/3069 + # cases in which `UNSET` gets special treatment explicitly at this layer. + # Subclasses can override the public `type_cast_value`, so the internal sentinel + # must not reach it. A missing value skips the call rather than passing `None`, + # which `value_is_missing` would not detect. if value is UNSET: if self.multiple or self.nargs == -1: value = () @@ -2686,12 +2676,8 @@ def process_value(self, ctx: Context, value: t.Any) -> t.Any: if not unset_keys: value = self.callback(ctx, self, value) - # Legacy case: provide a temporarily manipulated context to the callback - # to hide UNSET values as None. - # - # Refs: - # https://github.com/pallets/click/issues/3136 - # https://github.com/pallets/click/pull/3137 + # Legacy case: provide a temporarily manipulated context to the callback to + # hide UNSET values as None. else: # Add another layer to the context stack to clearly hint that the # context is temporarily modified. @@ -2831,8 +2817,8 @@ def handle_parse_result( # to UNSET, which will be interpreted as a missing value. value = UNSET - # Arbitrate the slot when several parameters target the same variable - # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403 + # Arbitrate the slot when several parameters target the same variable name + # (feature-switch groups). slot_empty = existing_value is UNSET more_explicit = existing_source is not None and source < existing_source same_source = existing_source is not None and source == existing_source @@ -3056,9 +3042,8 @@ def __init__( # sentinel when the user didn't pass them. Auto-derived values are resolved # lazily in :meth:`_resolve_lazy_default` and :attr:`flag_activation_value`. # Keeping the raw values means ``is UNSET`` reliably answers "did the user pass - # this?": #3403 needs it for arbitration, and any future feature needing the - # same distinction can reuse it without reintroducing parallel "was it - # explicit?" tracking. + # this?", and any future feature needing the same distinction can reuse it + # without reintroducing parallel "was it explicit?" tracking. self.flag_value = flag_value self.count = count if count and self.default is UNSET: @@ -3100,11 +3085,11 @@ def _infer_flag_kind( """Resolve ``is_flag`` and the parser hint ``_flag_needs_value``. Returns ``(is_flag, flag_needs_value)``, where ``_flag_needs_value`` tells the - parser this option is a flag that cannot be used standalone and needs a value. - The parser uses it to decide whether to treat the next CLI token as the flag's - value or as a new option. If ``prompt`` is enabled with - ``prompt_required=False``, it opens the door for an interactive value, hence the - initial condition. Ref: https://github.com/pallets/click/issues/3084 + parser that the value of this option can be omitted: the option then prompts for + a value if ``prompt`` is set, and otherwise uses its flag value. The parser uses + it to decide whether to treat the next CLI token as the option's value or as a + new option. If ``prompt`` is enabled with ``prompt_required=False``, it opens + the door for an interactive value, hence the initial condition. """ needs_value = self.prompt is not None and not self.prompt_required @@ -3242,9 +3227,8 @@ def get_default( Several auto-derived defaults are resolved lazily here rather than eagerly in :meth:`__init__`. This keeps :attr:`default` raw at construction time, so ``self.default is UNSET`` reliably answers "did the user pass a default?" for - feature-switch-group arbitration and for anything else that needs to distinguish - "absent" from a chosen value. The resolution rules live in - :meth:`_resolve_lazy_default`. + anything that needs to distinguish "absent" from a chosen value. The resolution + rules live in :meth:`_resolve_lazy_default`. .. versionchanged:: 8.5.0 ``UNSET`` defaults for boolean and multi flags are now resolved here instead @@ -3262,8 +3246,7 @@ def get_default( # Only invoke the value as a callable when the lazy resolver passed it through # unchanged. If the resolver substituted ``True`` -> :attr:`flag_value`, the # result is the programmer-supplied ``flag_value`` (often a class or enum), - # which must NOT be instantiated here. See - # https://github.com/pallets/click/issues/3121. + # which must NOT be instantiated here. if value is raw and call and callable(value): value = value() return value @@ -3544,9 +3527,8 @@ def prompt_for_value(self, ctx: Context) -> t.Any: # 3) still declare a non-boolean default. # This forced casting into a boolean is necessary to align any non-boolean # default to the prompt, which is going to be a [y/n]-style confirmation - # because the option is still a boolean flag. That way, instead of [y/n], - # we get [Y/n] or [y/N] depending on the truthy value of the default. - # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 + # because the option is still a boolean flag. That way, instead of [y/n], we + # get [Y/n] or [y/N] depending on the truthy value of the default. else: default = bool(default) return confirm(self.prompt, default) @@ -3701,9 +3683,6 @@ def consume_value( def process_value(self, ctx: Context, value: t.Any) -> t.Any: # process_value has to be overridden on Options in order to capture # `value == UNSET` cases before `type_cast_value()` gets called. - # - # Refs: - # https://github.com/pallets/click/issues/3069 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: value = False diff --git a/src/click/decorators.py b/src/click/decorators.py index cc42e5d42..0c7b6c455 100644 --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -441,14 +441,12 @@ def version_option( resolves to the ``Pillow`` distribution. .. note:: - The parameters and message variables accepted by this option are - frozen: no new slots will be added, to keep the common case simple - and predictable. If you need values it does not expose, such as a - file path, the Python version, or git metadata, use - :func:`custom_version_option` to render the output yourself. - - Rationale: `discussion #3527 - `_. + The parameters and message variables accepted by this option are frozen: no new + slots will be added, to keep the common case simple and predictable. Extra + values have no single right format: a path can point to the entry point or to + the module, and a Python version can be the full string or only ``X.Y``. If you + need values it does not expose, such as a file path, the Python version, or git + metadata, use :func:`custom_version_option` to render the output yourself. :param version: The version number to show. If not provided, Click will try to detect it. diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py index 8a2668b09..9cf231499 100644 --- a/src/click/shell_completion.py +++ b/src/click/shell_completion.py @@ -134,12 +134,11 @@ def __getattr__(self, name: str) -> t.Any: %(complete_func)s_setup; """ -# See ZshComplete.format_completion below, and issue #2703, before -# changing this script. +# See ZshComplete.format_completion below before changing this script. # -# (TL;DR: _describe is picky about the format, but this Zsh script snippet -# is already widely deployed. So freeze this script, and use clever-ish -# handling of colons in ZshComplet.format_completion.) +# (TL;DR: _describe is picky about the format, but this Zsh script snippet is already +# widely deployed. So freeze this script, and use clever-ish handling of colons in +# ZshComplete.format_completion.) _SOURCE_ZSH = """\ #compdef %(prog_name)s @@ -465,18 +464,14 @@ def get_completion_args(self) -> tuple[list[str], str]: def format_completion(self, item: CompletionItem[str]) -> str: help_ = item.help or "_" - # The zsh completion script uses `_describe` on items with help - # texts (which splits the item help from the item value at the - # first unescaped colon) and `compadd` on items without help - # text (which uses the item value as-is and does not support - # colon escaping). So escape colons in the item value if and - # only if the item help is not the sentinel "_" value, as used - # by the completion script. + # The zsh completion script uses `_describe` on items with help texts (which + # splits the item help from the item value at the first unescaped colon) and + # `compadd` on items without help text (which uses the item value as-is and does + # not support colon escaping). So escape colons in the item value if and only if + # the item help is not the sentinel "_" value, as used by the completion script. # - # (The zsh completion script is potentially widely deployed, and - # thus harder to fix than this method.) - # - # See issue #1812 and issue #2703 for further context. + # (The zsh completion script is potentially widely deployed, and thus harder to + # fix than this method.) value = item.value.replace(":", r"\:") if help_ != "_" else item.value return f"{item.type}\n{value}\n{help_}" diff --git a/src/click/testing.py b/src/click/testing.py index cc123d4d1..58696e97e 100644 --- a/src/click/testing.py +++ b/src/click/testing.py @@ -338,11 +338,10 @@ class CliRunner: ``fd`` is not supported on Windows. .. versionchanged:: 8.4.0 - Added the ``capture`` parameter. The default ``sys`` mode no longer - exposes the original fd through :meth:`fileno`, reverting the change - introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture - teardown. Use ``capture="fd"`` to restore that behavior with proper - isolation. :issue:`3384` + Added the ``capture`` parameter. The default ``sys`` mode no longer exposes the + original fd through :meth:`fileno`, reverting the change introduced in ``8.3.3`` + that broke Pytest's ``fd``-level capture teardown. Use ``capture="fd"`` to + restore that behavior with proper isolation. .. versionchanged:: 8.2 Added the ``catch_exceptions`` parameter. @@ -748,15 +747,14 @@ def isolated_filesystem( interfering with each other. .. warning:: - This helper predates Python 3 and modern pytest, and is not - thread-safe: it relies on :func:`os.chdir`, which mutates - process-global state, and :meth:`invoke` swaps the - process-global standard streams too. Parallelize tests with - processes (``pytest-xdist``), not threads. Locking the - runner (:pr:`3511`, :pr:`3520`, :pr:`3530`) and a - ``set_filesystem()`` API (:issue:`3123`) were declined: - neither removes the global-state mutation. See :issue:`3700` - and :issue:`3501`. + This helper predates Python 3 and modern pytest, and is not thread-safe: it + relies on :func:`os.chdir`, which mutates process-global state, and + :meth:`invoke` swaps the process-global standard streams too. Parallelize + tests with processes (``pytest-xdist``), not threads. Locking the runner was + declined: a lock leaves the global-state mutation in place, and serializing + thread-unsafe tests is the job of the test framework. A ``set_filesystem()`` + API was declined as unneeded: pytest's ``tmp_path`` and + ``monkeypatch.chdir()`` cover that case. :param temp_dir: Create the temporary directory under this directory. If given, the created directory is not removed diff --git a/tests/test_abort_interrupt.py b/tests/test_abort_interrupt.py index 83a8fed3f..6d285d6d6 100644 --- a/tests/test_abort_interrupt.py +++ b/tests/test_abort_interrupt.py @@ -1,18 +1,14 @@ -"""A second Ctrl-C while ``Command.main()`` reported an abort or an error used -to escape as an unhandled traceback: the message and the exit both ran in -``except`` clauses, outside every ``try`` that caught ``KeyboardInterrupt``. -https://github.com/pallets/click/issues/3802 - -The fix holds one policy, the one the pager has followed since -https://github.com/pallets/click/pull/351: a late interrupt must not replace -the intended outcome. In standalone mode the collected exit code wins, for -aborts, errors and success alike, and the message is best effort. Without -standalone mode the interrupt propagates to the caller. Two settled contracts -stay in place: the first interrupt reaches a non-standalone caller as -``Abort`` (https://github.com/pallets/click/pull/2380), and the ``Aborted!`` -message stays as it is (declined in -https://github.com/pallets/click/issues/1447 and -https://github.com/pallets/click/issues/2584). +"""A second Ctrl-C while ``Command.main()`` reported an abort or an error used to escape +as an unhandled traceback: the message and the exit both ran in ``except`` clauses, +outside every ``try`` that caught ``KeyboardInterrupt``. + +The fix holds one policy, the one the pager already follows: a late interrupt must not +replace the intended outcome. In standalone mode the collected exit code wins, for +aborts, errors and success alike, and the message is best effort. Without standalone +mode the interrupt propagates to the caller. Two settled contracts stay in place: the +first interrupt reaches a non-standalone caller as ``Abort``, and the ``Aborted!`` +message stays as it is. A program that wants another message runs with +``standalone_mode=False`` and prints its own. """ import sys @@ -26,8 +22,8 @@ class RecordingStderr: """A stderr stand-in that records what is written to it. With ``interrupt_at=N``, the ``N``-th ``isatty()`` call raises - ``KeyboardInterrupt``. ``echo()`` calls ``isatty()`` before writing, which - is where the traceback in issue #3802 ended. + ``KeyboardInterrupt``. ``echo()`` calls ``isatty()`` before writing, which is where + the unhandled traceback ended. """ def __init__(self, interrupt_at=None): diff --git a/tests/test_arguments.py b/tests/test_arguments.py index ab4e22931..458c4d015 100644 --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -596,7 +596,6 @@ def cmd(a, b, c): # Arguments overrides the default. [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)], # Unbounded arguments are allowed to have a default. - # See: https://github.com/pallets/click/issues/2164 [{"nargs": -1, "default": [42]}, [], (42,)], [{"nargs": -1, "default": None}, [], ()], [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)], diff --git a/tests/test_basic.py b/tests/test_basic.py index 9fbb624fb..a18574fc4 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -44,10 +44,8 @@ def cli(): ids=["no-collision", "argument", "option", "custom-flags"], ) def test_param_named_help(runner, help_names, params, args, expected_output): - """User parameters never clash with the automatic help option, which - stores its value under the reserved ``_click_default_help`` name. - - https://github.com/pallets/click/issues/2819 + """User parameters never clash with the automatic help option, which stores its + value under the reserved ``_click_default_help`` name. """ cli = click.Command( "cli", @@ -88,10 +86,8 @@ def cli(_click_default_help): def test_option_reusing_help_flag(runner): - """An option reusing the ``--help`` flag replaces the automatic help - option entirely. - - https://github.com/pallets/click/issues/2819 + """An option reusing the ``--help`` flag replaces the automatic help option + entirely. """ @click.command() @@ -322,7 +318,6 @@ def cli(on): (False, ["--f"], True), (False, [], False), # Boolean flags have a 3-states logic. - # See: https://github.com/pallets/click/issues/3024#issue-3285556668 (None, ["--f"], True), (None, [], None), ), @@ -395,9 +390,6 @@ def cli(flag): def test_flag_value_dual_options(runner, default, args, expected): """Check how default is processed when options compete for the same variable name. - Covers the regression reported in - https://github.com/pallets/click/issues/3024#issuecomment-3146199461 - .. hint:: Similar to ``test_options.py::test_default_dual_option_callback``. diff --git a/tests/test_commands.py b/tests/test_commands.py index c55da8de1..81d600edb 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -460,20 +460,15 @@ def test_iter_params_for_processing( ], ) def test_get_help_option_names(help_option_names, params, expected): - """Check help option names are deduplicated but keep stable order. - - https://github.com/pallets/click/pull/3728 - """ + """Check help option names are deduplicated but keep stable order.""" cli = click.Command("cli", params=[click.Option(decls) for decls in params]) ctx = click.Context(cli, help_option_names=help_option_names) assert cli.get_help_option_names(ctx) == expected def test_help_param_priority(runner): - """Cover the edge-case in which the eagerness of help option was not - respected, because it was internally generated multiple times. - - See: https://github.com/pallets/click/pull/2811 + """Cover the edge-case in which the eagerness of help option was not respected, + because it was internally generated multiple times. """ def print_and_exit(ctx, param, value): diff --git a/tests/test_context.py b/tests/test_context.py index e35c53251..6f76e0ae7 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -182,8 +182,6 @@ def test_make_pass_meta_decorator_doc(): def test_hiding_of_unset_sentinel_in_callbacks(): - """Fix: https://github.com/pallets/click/issues/3136""" - def inspect_other_params(ctx, param, value): """A callback that inspects other parameters' values via the context.""" assert click.get_current_context() is ctx diff --git a/tests/test_defaults.py b/tests/test_defaults.py index 24f3cadc5..cba4b42b2 100644 --- a/tests/test_defaults.py +++ b/tests/test_defaults.py @@ -189,9 +189,8 @@ def prefers_red(color): ], ) def test_lookup_default_returns_hides_sentinel(default_map, key, expected): - """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`. - - Regression test for https://github.com/pallets/click/issues/3145. + """``lookup_default()`` should return ``None`` for missing keys, not + :attr:`UNSET`. """ cmd = click.Command("test") ctx = click.Context(cmd) @@ -273,10 +272,7 @@ def cli(ctx, name): def test_parameter_source_during_paramtype_convert(runner): - """``get_parameter_source()`` is available during ``ParamType.convert``. - - Uses the reproducer from https://github.com/pallets/click/issues/3458. - """ + """``get_parameter_source()`` is available during ``ParamType.convert``.""" class Source(click.ParamType): name = "source" @@ -316,10 +312,7 @@ def cli(default, nodefault): def test_parameter_source_during_eager_callback(runner): - """``get_parameter_source()`` is available during eager callbacks. - - Regression test for https://github.com/pallets/click/issues/3458. - """ + """``get_parameter_source()`` is available during eager callbacks.""" def eager_cb(ctx, param, value): source = ctx.get_parameter_source(param.name) @@ -351,8 +344,7 @@ def cli(): def test_flask_debug_env_not_stomped_by_default_flag(runner, monkeypatch): """Eager callback must not overwrite env when the flag used its default. - Covers the Flask ``_set_debug`` pattern (pallets/flask#6025). Regression test - for https://github.com/pallets/click/issues/3458. + Covers the Flask ``_set_debug`` pattern. """ monkeypatch.delenv("APP_DEBUG", raising=False) @@ -423,12 +415,8 @@ def test_lookup_default_override_respected(runner): """A subclass override of ``lookup_default()`` should be called by Click internals, not bypassed by a private method. - Reproduce exactly https://github.com/pallets/click/issues/3145 in which a - subclass that falls back to prefix-based lookup when the parent returns - ``None``. - - Previous attempts in https://github.com/pallets/click/pr/3199 were entirely - bypassing the user's overridden method. + Reproduce the case of a subclass that falls back to prefix-based lookup when the + parent returns ``None``. """ class CustomContext(click.Context): @@ -482,7 +470,7 @@ class _Marker: (None, ["--opt"], _Marker), # Static value in default_map overrides the auto-aligned flag_value. ({"value": "from-map"}, [], "from-map"), - # Callable in default_map is still invoked (not suppressed by the fix). + # Callable in default_map is still invoked, unlike the auto-aligned flag_value. ({"value": lambda: "lazy-map"}, [], "lazy-map"), # None in default_map overrides the flag_value. ({"value": None}, [], None), @@ -493,9 +481,6 @@ class _Marker: def test_default_map_with_callable_flag_value(runner, default_map, args, expected): """``default_map`` entries should override the auto-aligned callable ``flag_value``, and callable entries in ``default_map`` should still be invoked. - - Verifies the fix for https://github.com/pallets/click/issues/3121 does not - break ``default_map`` precedence. """ @click.command() @@ -532,10 +517,8 @@ def cli(value): ], ) def test_default_map_nargs(runner, default_map, option_kwargs, cli_args, expected): - """A string in ``default_map`` for an option with ``nargs > 1`` should be - split the same way an environment variable string is split. - - Regression test for https://github.com/pallets/click/issues/2745. + """A string in ``default_map`` for an option with ``nargs > 1`` should be split the + same way an environment variable string is split. """ @click.command() @@ -549,10 +532,8 @@ def cli(point): def test_unset_in_default_map(runner): - """An ``UNSET`` value in ``default_map`` should be treated as if - the key is absent, and so fallback to the parameter's own default. - - Refs: https://github.com/pallets/click/pull/3224#issuecomment-3968643305 + """An ``UNSET`` value in ``default_map`` should be treated as if the key is absent, + and so fallback to the parameter's own default. """ @click.command( diff --git a/tests/test_formatting.py b/tests/test_formatting.py index 272b075fe..5d70c6b39 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -164,7 +164,6 @@ def cmd(arg): def test_formatting_usage_error_metavar_missing_arg(runner): """ :author: @r-m-n - Including attribution to #612 """ @click.command() @@ -285,10 +284,8 @@ def cmd(arg): def test_formatting_usage_error_help_hint( runner, help_names, extra_options, expected_hint ): - """The error hint should only show non-shadowed help option names, - picking the longest for readability. - - https://github.com/pallets/click/issues/2790 + """The error hint should only show non-shadowed help option names, picking the + longest for readability. """ @click.group(context_settings={"help_option_names": help_names}) @@ -520,9 +517,9 @@ def test_write_usage_styled_prefix_keeps_options_on_one_line(): @pytest.mark.parametrize( ("formatter_kwargs", "current_indent", "prog", "args", "prefix", "expected"), [ - # Issue #3360: the default prefix used to emit only - # a blank line because ``wrap_text("", initial_indent=usage_prefix)`` - # returned ``""`` and discarded the prefix. + # The default prefix used to emit only a blank line because + # ``wrap_text("", initial_indent=usage_prefix)`` returned ``""`` and discarded + # the prefix. pytest.param( {}, 0, @@ -606,8 +603,8 @@ def test_help_formatter_write_usage_without_args_styled_prefix(): @pytest.mark.parametrize( ("command_kwargs", "expected_usage_line"), [ - # End-to-end regression for #3360: an empty ``options_metavar`` with - # no parameters used to render a blank usage line. + # End-to-end regression: an empty ``options_metavar`` with no parameters used to + # render a blank usage line. pytest.param( {"options_metavar": ""}, "Usage: cli", diff --git a/tests/test_options.py b/tests/test_options.py index b35277fcb..de00532d6 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -233,9 +233,8 @@ def cli(message): (True, 1, [1.1, 2.2], (1.1, 2.2)), (True, 1, ["1", "2"], ("1", "2")), (True, 1, [None, None], (None, None)), - # Contrary to list or tuples, native Python types not supported by Click are - # not recognized and are converted to the default format: tuple of strings. - # Refs: https://github.com/pallets/click/issues/3036 + # Contrary to list or tuples, native Python types not supported by Click are not + # recognized and are converted to the default format: tuple of strings. (True, 1, {1, 2}, ("1", "2")), (True, 1, frozenset([1, 2]), ("1", "2")), (True, 1, {1: "a", 2: "b"}, ("1", "2")), @@ -456,10 +455,7 @@ def cmd(arg): def test_envvar_container_type(runner): - """Env vars are plain strings, so a container type splits them character-wise. - - Refs: https://github.com/pallets/click/issues/3036 - """ + """Env vars are plain strings, so a container type splits them character-wise.""" @click.command() @click.option("--x", envvar="X", type=frozenset) @@ -636,10 +632,7 @@ def cmd(arg): def test_show_default_container_defaults(runner): - """Container defaults are rendered through ``str()`` in the help output. - - Refs: https://github.com/pallets/click/issues/3036 - """ + """Container defaults are rendered through ``str()`` in the help output.""" @click.command() @click.option("--a", default=frozenset(["git"]), type=frozenset, show_default=True) @@ -687,10 +680,8 @@ def test_multiple_default_composite_type(): def test_type_from_default_container(default): """Container defaults have no native Click type and fall back to STRING. - The documented "if no type is provided, the type of the default value is - used" rule does not apply to ``set``, ``frozenset`` or ``dict`` defaults. - - Refs: https://github.com/pallets/click/issues/3036 + This matches the documented rule: the type of the default value is used only if + Click recognizes it, and it does not recognize ``set``, ``frozenset`` or ``dict``. """ opt = click.Option(["-a"], default=default) assert opt.type is click.STRING @@ -1194,7 +1185,7 @@ def cmd(myparam): def test_option_custom_class_reusable(runner): - """Ensure we can reuse a custom class option. See Issue #926""" + """Ensure we can reuse a custom class option.""" class CustomOption(click.Option): def get_help_record(self, ctx): @@ -1426,10 +1417,8 @@ def __str__(self): ids=["empty-string", "non-string-comparable-object"], ) def test_show_default_with_empty_string(runner, default, expected): - """The empty-string check in help rendering must not break on objects - whose ``__eq__`` raises for string operands. - - Regression test for https://github.com/pallets/click/issues/3298. + """The empty-string check in help rendering must not break on objects whose + ``__eq__`` raises for string operands. """ opt = click.Option(["--limit"], default=default, show_default=True) ctx = click.Context(click.Command("cli")) @@ -1614,8 +1603,7 @@ def test_type_from_flag_value(): # Not passing --foo returns the default value as-is, in its Python type, then # converted by the option type. For boolean flags, default=True is a literal # value, not a sentinel meaning "activate flag". So it is NOT substituted with - # flag_value. See: https://github.com/pallets/click/issues/3111 - # https://github.com/pallets/click/pull/3239 + # flag_value. ({"type": bool, "default": True, "flag_value": True}, [], True), ({"type": bool, "default": True, "flag_value": False}, [], True), ({"type": bool, "default": False, "flag_value": True}, [], False), @@ -1724,9 +1712,6 @@ def test_default_dual_option_callback(runner, default, args, expected): """Check how default is processed by the callback when options compete for the same variable name. - Reproduction of the issue reported in - https://github.com/pallets/click/pull/3030#discussion_r2271571819 - .. hint:: Similar to ``test_basic.py::test_flag_value_dual_options``. @@ -2010,8 +1995,9 @@ def cli_without_choices(g): ([True, False], False, "False"), (["foo", 1], "foo", "foo"), (["foo", 1], 1, "1"), - # Enum choices are rendered as their names, not values. - # See: https://github.com/pallets/click/issues/2911 + # Enum choices are rendered as their names, not values, ``StrEnum`` included: a + # name is always a string, and using values for some enum kinds only would be + # inconsistent. (HashType, HashType.SHA1, "SHA1"), # Enum choices allow defaults strings that are their names. (HashType, HashType.SHA256, "SHA256"), @@ -2083,10 +2069,6 @@ class EnumSentinel(enum.Enum): def __bool__(self) -> Literal[False]: """Force the sentinel to be falsy to make sure it is not caught by Click internal implementation. - - Falsy sentinels have been discussed in: - https://github.com/pallets/click/pull/3030#pullrequestreview-3106604795 - https://github.com/pallets/click/pull/3030#pullrequestreview-3108471552 """ return False @@ -2158,12 +2140,8 @@ def __bool__(self) -> Literal[False]: ), ) def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected): - """Check that an object-based sentinel, used as a flag value, is returned as-is - to a custom type that is shared by two options, competing for the same variable - name. - - A reproduction of - https://github.com/pallets/click/issues/3024#issuecomment-3146511356 + """Check that an object-based sentinel, used as a flag value, is returned as-is to a + custom type that is shared by two options, competing for the same variable name. """ class ConfigParamType(click.ParamType): @@ -2298,12 +2276,7 @@ class Class2: ], ) def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected): - """Test how the type and flag_value influence the returned value. - - Cover cases reported in: - https://github.com/pallets/click/issues/3024#issuecomment-3146480714 - https://github.com/pallets/click/issues/2012#issuecomment-892437060 - """ + """Test how the type and flag_value influence the returned value.""" @click.command() @click.option("--pro", **opt_params) @@ -2341,10 +2314,8 @@ def scan(pro): ["--opt2"], EngineType.PRO, ), - # Exotic flag values like classes are passed through unchanged when no - # explicit type is given (UNPROCESSED is auto-detected). - # https://github.com/pallets/click/issues/2012 - # https://github.com/pallets/click/issues/3121 + # Exotic flag values like classes are passed through unchanged when no explicit + # type is given (UNPROCESSED is auto-detected). ( {"flag_value": Class1, "default": True}, {"flag_value": Class2}, @@ -2366,8 +2337,7 @@ def scan(pro): # String and None defaults pass through unchanged. ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"), ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None), - # To get the classes as-is, we need to specify the type as UNPROCESSED. - # https://github.com/pallets/click/issues/3121 + # An explicit ``type=UNPROCESSED`` gives the same result. ( {"flag_value": Class1, "type": UNPROCESSED, "default": True}, {"flag_value": Class2, "type": UNPROCESSED}, @@ -2433,11 +2403,6 @@ def test_custom_type_flag_value_dual_options( ): """Test how flag values are processed with dual options competing for the same variable name. - - Reproduce issues reported in: - https://github.com/pallets/click/issues/3024#issuecomment-3146508536 - https://github.com/pallets/click/issues/2012#issue-946471049 - https://github.com/pallets/click/issues/2012#issuecomment-892437060 """ @click.command() @@ -2457,8 +2422,7 @@ def cli(dual_option): ("opt_params", "args", "expected"), [ # Class flag_value with default=True and UNPROCESSED: the class itself is - # returned, NOT an instance. Regression test for - # https://github.com/pallets/click/issues/3121 + # returned, NOT an instance. ({"flag_value": Class1, "type": UNPROCESSED, "default": True}, [], Class1), ( {"flag_value": Class1, "type": UNPROCESSED, "default": True}, @@ -2486,15 +2450,14 @@ def cli(dual_option): [], re.compile(r""), ), - # Non-callable flag_value with default=True: unaffected by the fix. + # Non-callable flag_value with default=True: resolves to flag_value as usual. ({"flag_value": "upper", "default": True}, [], "upper"), ({"flag_value": "upper", "default": True}, ["--opt"], "upper"), ], ) def test_callable_flag_value_not_instantiated(runner, opt_params, args, expected): """A callable ``flag_value`` like a class, with ``default=True`` should not be - invoked when resolving the default. This is the single-option variant of - the regression reported in https://github.com/pallets/click/issues/3121. + invoked when resolving the default. """ @click.command() @@ -2528,7 +2491,7 @@ def cli(value): result = runner.invoke(cli, [], default_map={"value": "from-map"}) assert result.output == repr("from-map") - # Callable in default_map is still invoked (not suppressed by the fix). + # Callable in default_map is still invoked, unlike the auto-aligned flag_value. result = runner.invoke(cli, [], default_map={"value": lambda: "lazy-map"}) assert result.output == repr("lazy-map") @@ -2618,10 +2581,8 @@ def cli(value): def test_flag_value_not_stringified_for_custom_types(runner): - """Non-basic flag_value types are passed through unchanged without - requiring ``type=click.UNPROCESSED``. - - Regression test for https://github.com/pallets/click/issues/2012 + """Non-basic flag_value types are passed through unchanged without requiring + ``type=click.UNPROCESSED``. """ @click.command() @@ -2676,10 +2637,8 @@ def cli2(engine): def test_custom_type_container_flag_value( runner, container_type, flag_value, default, default_output, flag_output ): - """Check that container types are correctly handled as a type, a flag value - and a default. - - Reproduces https://github.com/pallets/click/issues/2610 + """Check that container types are correctly handled as a type, a flag value and a + default. """ @click.command() @@ -2707,12 +2666,10 @@ def rcli(scm_ignore_files): ("default", "args", "expected"), [ # default=None: 3-state pattern (e.g. Flask --reload/--no-reload). - # https://github.com/pallets/click/issues/3024 (None, [], None), (None, ["--flag"], True), (None, ["--no-flag"], False), # default=True: literal value, not substituted with flag_value. - # https://github.com/pallets/click/issues/3111 (True, [], True), (True, ["--flag"], True), (True, ["--no-flag"], False), @@ -2738,9 +2695,8 @@ def cli(flag): @pytest.mark.parametrize( ("opts", "args", "expected"), [ - # #3403 reproducer: enable/disable pair with explicit ``default=True`` - # on the positive flag, declared after (inner decorator) the negative. - # https://github.com/pallets/click/issues/3403 + # The documented enable/disable pair: explicit ``default=True`` on the positive + # flag, declared after (inner decorator) the negative. pytest.param( [ ("--without-xyz", {"flag_value": False}), @@ -2748,7 +2704,7 @@ def cli(flag): ], [], True, - id="3403-reproducer-no-args", + id="explicit-default-inner-no-args", ), pytest.param( [ @@ -2757,7 +2713,7 @@ def cli(flag): ], ["--with-xyz"], True, - id="3403-reproducer-with-only", + id="explicit-default-inner-with-only", ), pytest.param( [ @@ -2766,7 +2722,7 @@ def cli(flag): ], ["--without-xyz"], False, - id="3403-reproducer-without-only", + id="explicit-default-inner-without-only", ), # When both flags are passed, the parser keeps the last value seen. pytest.param( @@ -2776,7 +2732,7 @@ def cli(flag): ], ["--with-xyz", "--without-xyz"], False, - id="3403-reproducer-with-then-without", + id="explicit-default-inner-with-then-without", ), pytest.param( [ @@ -2785,7 +2741,7 @@ def cli(flag): ], ["--without-xyz", "--with-xyz"], True, - id="3403-reproducer-without-then-with", + id="explicit-default-inner-without-then-with", ), # Order-independence: explicit ``default=True`` on the OUTER # decorator (declared first) must produce the same behavior. @@ -2819,8 +2775,9 @@ def cli(flag): False, id="explicit-default-false-on-negative", ), - # Explicit ``default=True`` on the negative flag is unusual but - # legal: post-#3239, it is a literal Python value, not a sentinel. + # Explicit ``default=True`` on the negative flag is unusual but legal: for a + # boolean flag, ``default=True`` is a literal value, not substituted with + # ``flag_value``. pytest.param( [ ("--with-xyz", {"flag_value": True}), @@ -2972,10 +2929,8 @@ def cli(flag): def test_bool_flag_group_competition(runner, opts, args, expected): """Competing boolean flags sharing a single parameter name. - Verifies the arbitration rules between options that target the same - variable name in a feature-switch group. - - Regression test for https://github.com/pallets/click/issues/3403 + Verifies the arbitration rules between options that target the same variable name in + a feature-switch group. """ @click.command() @@ -3052,7 +3007,6 @@ def cli(enable_xyz): @pytest.mark.parametrize( ("opts", "args", "invoke_kwargs", "expected_value", "expected_source"), [ - # https://github.com/pallets/click/issues/3458 pytest.param( [ ("--without-xyz", {"flag_value": False}), @@ -3091,10 +3045,7 @@ def cli(enable_xyz): def test_bool_flag_group_parameter_source( runner, opts, args, invoke_kwargs, expected_value, expected_source ): - """``get_parameter_source()`` stays correct for feature-switch groups. - - Regression test for https://github.com/pallets/click/issues/3458. - """ + """``get_parameter_source()`` stays correct for feature-switch groups.""" @click.command() @click.pass_context @@ -3114,9 +3065,9 @@ def cli(ctx, enable_xyz): @pytest.mark.parametrize( ("opts", "args", "expected"), [ - # Non-boolean feature switch group: classic --upper/--lower - # pattern. The option with ``default=True`` acts as the default - # via the substitution rule (#3239) for non-boolean ``flag_value``. + # Non-boolean feature switch group: classic --upper/--lower pattern. The option + # with ``default=True`` acts as the default via the substitution rule for + # non-boolean ``flag_value``. pytest.param( [ ("--upper", {"flag_value": "upper", "default": True}), @@ -3327,10 +3278,10 @@ def cli(ctx, enable_xyz): "second", id="both-explicit-defaults-string-last-wins", ), - # Mixed boolean and non-boolean ``flag_value`` in the same group - # is allowed. Both options here carry an explicit default, so last-wins - # picks the option declared last regardless of value type. The boolean - # ``default=False`` is a literal value (post-#3239), not a sentinel. + # Mixed boolean and non-boolean ``flag_value`` in the same group is allowed. + # Both options here carry an explicit default, so last-wins picks the option + # declared last regardless of value type. The boolean ``default=False`` passes + # through literally, like the string default. pytest.param( [ ("--bool-flag", {"flag_value": True, "default": False}), @@ -3607,10 +3558,10 @@ def cli(case): False, id="auto-envvar-prefix-loses-to-cmdline", ), - # ``Sentinel.UNSET`` in ``default_map`` must be skipped (#3224 - # carve-out): the lookup falls through to the parameter default. - # Inside a feature switch group, the explicit ``default=True`` on - # ``--with-xyz`` then wins over the sibling's auto-``False``. + # ``Sentinel.UNSET`` in ``default_map`` must be skipped: the lookup falls + # through to the parameter default. Inside a feature switch group, the explicit + # ``default=True`` on ``--with-xyz`` then wins over the sibling's + # auto-``False``. pytest.param( {}, {"enable_xyz": UNSET}, @@ -3660,10 +3611,8 @@ def cli(enable_xyz): ], ) def test_flag_value_on_option_with_zero_or_one_args(flag_type, args, expect_output): - """An option with flag_value and is_flag=False can be - omitted or used with 0 or 1 args. - - Regression test for https://github.com/pallets/click/issues/3084 + """An option with flag_value and is_flag=False can be omitted or used with 0 or 1 + args. """ if flag_type is str: flagopt = click.option( diff --git a/tests/test_stream_lifecycle.py b/tests/test_stream_lifecycle.py index 9f4aa2086..b1c7de2be 100644 --- a/tests/test_stream_lifecycle.py +++ b/tests/test_stream_lifecycle.py @@ -1,10 +1,14 @@ """Tests for ``CliRunner`` stream lifecycle and ownership. -Covers the stream management bugs tracked across: -- Issue #824: ``ValueError`` on closed file when logging interacts with ``CliRunner`` -- Issue #2993: Race condition in ``StreamMixer`` finalization (multi-threaded) -- Issue #3110: Regression from PR #2991's ``__del__`` fix breaking logging -- PR #3139: The fix - prevent ``_NamedTextIOWrapper`` from closing owned buffers +Covers these stream management bugs: +- ``ValueError`` on closed file when logging interacts with ``CliRunner`` +- Race condition in ``StreamMixer`` finalization (multi-threaded) +- Regression from a ``StreamMixer.__del__`` fix breaking logging + +The fix prevents ``_NamedTextIOWrapper`` from closing owned buffers. + +The closed-file ``ValueError`` shows only when pytest displays live logs +(``--log-cli-level``): a default run passes the logging tests even without the fix. The tests are organized by category: @@ -155,7 +159,7 @@ def cli(): def test_no_streammixer_del(): """``StreamMixer`` should not have a ``__del__`` method. - PR #2991 added ``__del__`` which caused issue #3110. PR #3139 removes it. + A ``__del__`` used to close buffers that logging still referenced. """ has_del = hasattr(StreamMixer, "__del__") if has_del: @@ -182,7 +186,7 @@ def test_bytesiocopy_flush_propagates(): # --------------------------------------------------------------------------- -# Category 3: Logging interaction (issues #824, #3110) +# Category 3: Logging interaction # --------------------------------------------------------------------------- @@ -202,7 +206,7 @@ def cli(): def test_invoke_with_logger_and_prompt(): - """Logging + prompt (the exact #824 reproducer).""" + """Logging + prompt (the closed-file ``ValueError`` reproducer).""" logger = logging.getLogger("test_invoke_with_logger_and_prompt") @click.command() @@ -218,11 +222,11 @@ def hello(name): def test_sequential_invokes_with_logging(): - """Multiple sequential ``invoke()`` calls with logging (#3110 reproducer). + """Multiple sequential ``invoke()`` calls with logging. - Issue #3110: the ``__del__`` from PR #2991 caused logging failures on - the second invocation because the first ``StreamMixer``'s ``__del__`` would - close buffers that logging still referenced. + A former ``__del__`` caused logging failures on the second invocation because the + first ``StreamMixer``'s ``__del__`` would close buffers that logging still + referenced. """ logger = logging.getLogger("test_sequential_invokes_with_logging") @@ -261,11 +265,10 @@ def cli(): def test_logging_with_cli_log_level(): - """Simulate what ``--log-cli-level`` does: add a handler to root - before invoke. + """Add a handler to the root logger before ``invoke()``. - This reproduces the original #824 scenario without needing pytest - CLI flags. + This does not reproduce the closed-file ``ValueError`` by itself: that needs pytest + to display live logs (``--log-cli-level``). """ root_logger = logging.getLogger() handler = logging.StreamHandler(sys.stderr) @@ -290,7 +293,7 @@ def cli(): # --------------------------------------------------------------------------- -# Category 4: Multi-threaded safety (issue #2993) +# Category 4: Multi-threaded safety # --------------------------------------------------------------------------- @@ -335,7 +338,12 @@ def worker(n): def test_invoke_with_thread_pool_and_exit(): - """``ThreadPoolExecutor`` + ``SystemExit`` (the exact #2993 reproducer).""" + """``ThreadPoolExecutor`` + ``SystemExit`` (the finalization race reproducer). + + The race shows as a ``PytestUnraisableExceptionWarning`` from a + ``_NamedTextIOWrapper`` finalizer, not as a failed assertion: + ``filterwarnings = ["error"]`` in ``pyproject.toml`` turns it into a failure. + """ @click.command() @click.argument("args", nargs=-1) @@ -493,7 +501,10 @@ def cli(): @pytest.mark.stress @pytest.mark.parametrize("_", range(10_000)) def test_stress_thread_pool_with_exit(_): - """Exact #2993 reproducer: ``ThreadPoolExecutor`` + ``SystemExit``.""" + """Finalization race reproducer: ``ThreadPoolExecutor`` + ``SystemExit``. + + A free-threaded Python build hits the race much more often. + """ @click.command() @click.argument("args", nargs=-1) @@ -510,7 +521,7 @@ def cli(**_kw): @pytest.mark.stress @pytest.mark.parametrize("_", range(10_000)) def test_stress_logging_sequential_invocations(_): - """#3110/#824 reproducer: sequential invocations with logging.""" + """Sequential invocations with logging.""" logger = logging.getLogger("stress_sequential") @click.command() diff --git a/tests/test_termui.py b/tests/test_termui.py index 1825b1987..e4e0d6c0d 100644 --- a/tests/test_termui.py +++ b/tests/test_termui.py @@ -114,10 +114,10 @@ def cli(): def test_progressbar_lands_on_final_position(monkeypatch, update_min_steps, drive): """The bar reaches its total whatever the ``update_min_steps`` threshold. - Regression for issue #3571: a threshold that does not divide the length - left a remainder pending, so `show_pos` froze below completion, reporting - `14/20` for a length of 20 and a threshold of 7. Thresholds of 1 and 2 do - divide 20, and 25 exceeds it, so nothing is ever rendered until the end. + Regression: a threshold that does not divide the length left a remainder pending, so + `show_pos` froze below completion, reporting `14/20` for a length of 20 and a + threshold of 7. Thresholds of 1 and 2 do divide 20, and 25 exceeds it, so nothing is + ever rendered until the end. """ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) stream = io.StringIO() @@ -451,7 +451,7 @@ def test_edit(runner): @pytest.mark.skipif(WIN, reason="No sed on Windows.") @pytest.mark.parametrize("use_iterable", [False, True], ids=["single", "iterable"]) def test_edit_pathlib(runner, tmp_path, use_iterable): - """Issue #2869: ``filename`` accepts ``os.PathLike`` values.""" + """``filename`` accepts ``os.PathLike`` values.""" file_path = tmp_path / "file.txt" file_path.write_text("a\nb\n", encoding="UTF-8") filename = [file_path] if use_iterable else file_path @@ -476,35 +476,35 @@ def test_edit_pathlib(runner, tmp_path, use_iterable): ["vi", 'file"; rm -rf / ; echo "'], id="shell metacharacters in filename", ), - # Issue #1026: editor path with spaces must be quoted. + # Editor path with spaces must be quoted. pytest.param( '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"', ["f.txt"], ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"], id="quoted windows path with spaces", ), - # PR #1477: pager/editor command with flags, like ``less -FRSX``. + # Pager/editor command with flags, like ``less -FRSX``. pytest.param( "less -FRSX", ["f.txt"], ["less", "-FRSX", "f.txt"], id="command with flags", ), - # Issue #1026: quoted command with ``--wait`` flag. + # A command name with spaces must be quoted, as on a shell command line. pytest.param( '"my command" --option value arg', ["f.txt"], ["my command", "--option", "value", "arg", "f.txt"], id="quoted command with args", ), - # PR #1477: unquoted unix path. + # Unquoted unix path. pytest.param( "/usr/bin/vim", ["f.txt"], ["/usr/bin/vim", "f.txt"], id="unix absolute path", ), - # Issue #1026: macOS path with escaped space. + # macOS path with escaped space. pytest.param( "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl", ["f.txt"], @@ -629,8 +629,8 @@ def test_editor_nonexistent_exception(): pytest.param(" ", [], id="whitespace only"), pytest.param(" less ", ["less"], id="leading and trailing spaces"), pytest.param("less\t-R", ["less", "-R"], id="tab as separator"), - # Quoted Windows paths: quotes are stripped in POSIX mode (the - # default), preserving backslashes inside quoted tokens (issue #1026). + # Quoted Windows paths: quotes are stripped in POSIX mode (the default), + # preserving backslashes inside quoted tokens. pytest.param( '"C:\\Program Files\\Git\\usr\\bin\\less.exe"', ["C:\\Program Files\\Git\\usr\\bin\\less.exe"], @@ -654,8 +654,8 @@ def test_editor_nonexistent_exception(): ["/usr/bin/my pager"], id="escaped space in unix path", ), - # PR #1477: POSIX mode (the default) eats unquoted backslashes. - # On Windows, users must quote paths that contain backslashes. + # POSIX mode (the default) eats unquoted backslashes. On Windows, users must + # quote paths that contain backslashes. pytest.param( "C:\\path\\to\\exe /test other\\path", ["C:pathtoexe", "/test", "otherpath"], @@ -666,9 +666,8 @@ def test_editor_nonexistent_exception(): def test_pager_shlex_split(pager_env, expected_parts): """Verify shlex.split produces the expected argv for PAGER values. - Tests the splitting logic used by :func:`click._termui_impl.pager` to - turn the ``PAGER`` environment variable into an ``argv`` list. See - issue #1026, PR #1477, PR #1543, PR #2775. + Tests the splitting logic used by :func:`click._termui_impl._pager_contextmanager` + to turn the ``PAGER`` environment variable into an ``argv`` list. """ assert shlex.split(pager_env) == expected_parts @@ -891,11 +890,10 @@ def wait(self): def test_pipepager_less_raw_mode_detection( monkeypatch, cmd_parts, less_env, expected_color, expected_less ): - """Raw-mode detection parses the option tokens from ``LESS`` and the - command line. Filenames and unrelated options carrying the letter ``r`` - or ``R`` do not request raw mode, and ``_pipepager`` then reports no - opinion (``None``) that :func:`get_pager_file` settles to off. - {issue}`3416` + """Raw-mode detection parses the option tokens from ``LESS`` and the command line. + Filenames and unrelated options carrying the letter ``r`` or ``R`` do not request + raw mode, and ``_pipepager`` then reports no opinion (``None``) that + :func:`get_pager_file` settles to off. """ if less_env is None: monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False) @@ -926,8 +924,8 @@ def fake_popen(*args, **kwargs): def test_echo_via_pager_streams_each_write(monkeypatch): - """Each write is flushed so a slow generator streams to the pager - incrementally instead of buffering until the end (issues #3242, #2542). + """Each write is flushed so a slow generator streams to the pager incrementally + instead of buffering until the end. """ calls = [] @@ -1006,7 +1004,7 @@ def test_get_pager_file_pager_unset_falls_back_when_no_default(monkeypatch, tmp_ def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch): - """A missing ``PAGER`` must not close the borrowed stdout (issue #3449). + """A missing ``PAGER`` must not close the borrowed stdout. The ``8.4.0`` regression was only fixed for the no-tty ``_nullpager`` path; the ``_pipepager``/``_tempfilepager`` fallbacks (reached in a tty when @@ -1040,9 +1038,8 @@ def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch): def test_echo_via_pager_tty_pager_missing(runner, monkeypatch): """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working. - Regression for issue #3449 via the pager fallback: a tty with ``PAGER`` - pointing at a missing binary used to close the runner's stdout, breaking - ``CliRunner.invoke``. + Regression via the pager fallback: a tty with ``PAGER`` pointing at a missing binary + used to close the runner's stdout, breaking ``CliRunner.invoke``. """ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) monkeypatch.setitem( @@ -1173,11 +1170,11 @@ def _force_tempfile_pager(monkeypatch, pager_cmd="cat"): That backend is only reachable on Windows, so the platform flag and the tty probes are faked to exercise it from any runner. - ``PAGER`` is set to the bare command name, not to the path - :func:`shutil.which` resolves it to. ``pager()`` splits ``PAGER`` with - :func:`shlex.split` in POSIX mode, where a Windows path loses its - backslashes and splits on the space in ``C:\\Program Files``, leaving a - command that resolves to nothing. Click resolves the bare name itself. + ``PAGER`` is set to the bare command name, not to the path :func:`shutil.which` + resolves it to. ``_pager_contextmanager()`` splits ``PAGER`` with + :func:`shlex.split` in POSIX mode, where a Windows path loses its backslashes and + splits on the space in ``C:\\Program Files``, leaving a command that resolves to + nothing. Click resolves the bare name itself. """ cmd = shlex.split(pager_cmd)[0] assert shutil.which(cmd) is not None, f"{cmd} not available" @@ -1204,7 +1201,7 @@ def _page_with_echo_via_pager(): ], ) def test_tempfile_pager_accepts_text(monkeypatch, capfd, page): - """The temp file backend must yield a text stream (issues #3731, #3740). + """The temp file backend must yield a text stream. Regression: a binary-mode temp file handed straight to ``get_pager_file`` left the caller writing ``str`` to a binary handle, which raises @@ -1262,11 +1259,11 @@ def test_tempfile_pager_passes_pager_params(monkeypatch, capfd): def test_tempfile_pager_closes_file_before_unlink(monkeypatch): """An error while paging must not leave the temp file open at unlink time. - The ``f.close()`` on the success path sits after the ``yield``, so an - exception raised while the pager is open used to skip it and reach - ``finally: os.unlink(f.name)`` with the handle still open. Windows refuses - to unlink an open file, so ``PermissionError: [WinError 32]`` replaced the - original error and hid it (issue #3731). + The ``f.close()`` on the success path sits after the ``yield``, so an exception + raised while the pager is open used to skip it and reach + ``finally: os.unlink(f.name)`` with the handle still open. Windows refuses to unlink + an open file, so ``PermissionError: [WinError 32]`` replaced the original error and + hid it. """ _force_tempfile_pager(monkeypatch) @@ -1430,10 +1427,9 @@ def cli(password): def test_prompt_and_confirm_ansi_respects_color( runner, call, user_input, color, expect ): - """``confirm`` and ``prompt`` strip ANSI color and style codes from the - prompt when color is disabled and keep them when it is enabled, like - ``echo``. The prompt is written by ``input`` rather than ``echo``, so it - used to keep the codes regardless (issue 3572). + """``confirm`` and ``prompt`` strip ANSI color and style codes from the prompt when + color is disabled and keep them when it is enabled, like ``echo``. The prompt is + written by ``input`` rather than ``echo``, so it used to keep the codes regardless. """ @click.command() @@ -1487,9 +1483,8 @@ def cmd(arg1): def test_string_show_default_in_prompt( runner, show_default, default, user_input, in_prompt, not_in_prompt ): - """When show_default is a string, the prompt should display that - string in parentheses instead of the actual default value, - matching the help text behavior. See pallets/click#2836.""" + """When show_default is a string, the prompt should display that string in + parentheses instead of the actual default value, matching the help text behavior.""" option_kwargs = {"show_default": show_default, "prompt": True} if default is not UNSET: @@ -1617,9 +1612,7 @@ def cmd(arg1): ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True), ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False), # For boolean flags, default=True is a literal value, not a sentinel meaning - # "activate flag", so the prompt shows [Y/n] with default=True. See: - # https://github.com/pallets/click/issues/3111 - # https://github.com/pallets/click/pull/3239 + # "activate flag", so the prompt shows [Y/n] with default=True. ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True), ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True), ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False), @@ -1679,10 +1672,8 @@ def cmd(arg1): def test_flag_value_prompt( runner, opt_decls, opt_params, args, prompt, input, expected ): - """Check how flag value are prompted and handled by all combinations of - ``prompt``, ``default``, and ``flag_value`` parameters. - - Covers concerns raised in issue https://github.com/pallets/click/issues/1992. + """Check how flag value are prompted and handled by all combinations of ``prompt``, + ``default``, and ``flag_value`` parameters. """ @click.command() @@ -1747,9 +1738,8 @@ def convert(self, value, param, ctx): class _PasswordLengthType(click.ParamType): - """Mirrors the issue's original use case: a password validator - that references the user-typed value in its error message without - quoting it. + """A password validator that puts the typed value, unquoted, in its error + message. """ name = "password" @@ -1861,14 +1851,14 @@ def convert(self, value, param, ctx): "1", "is not in the range", None, - id="intrange-numeric-substring-falls-back-to-generic", + id="intrange-numeric-substring-not-masked", ), pytest.param( _StaticMessageType(), "ent", "Authentication failed for this account", None, - id="partial-word-match-falls-back-to-generic", + id="partial-word-match-not-masked", ), # When the raw (unquoted) value appears in the message, mask it instead # of replacing the whole message with a generic fallback that throws @@ -1929,8 +1919,6 @@ def convert(self, value, param, ctx): def test_hide_input_error_message( runner, type, user_input, expected_fragment, unexpected_fragment ): - """https://github.com/pallets/click/issues/2809""" - @click.command() @click.option("--password", prompt=True, hide_input=True, type=type) def cli(password): diff --git a/tests/test_testing.py b/tests/test_testing.py index 870d95c97..808b0eff0 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -269,7 +269,6 @@ def cli(): def test_exit_code_and_output_from_sys_exit(): - # See issue #362 @click.command() def cli_string(): click.echo("hello world") @@ -481,9 +480,9 @@ def write_marker(path): def test_tempdir_isolation_is_thread_safe(): """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``. - Each thread owns a ``tempfile.TemporaryDirectory`` and works through - absolute paths, so there is no ``os.chdir`` and no process-global CWD race - (the reason ``isolated_filesystem()`` is not thread-safe, issue #3501). + Each thread owns a ``tempfile.TemporaryDirectory`` and works through absolute paths, + so there is no ``os.chdir`` and no process-global CWD race (the reason + ``isolated_filesystem()`` is not thread-safe). ``invoke()`` is deliberately not called concurrently here: it redirects the process-global standard streams, so parallel invocations in one process @@ -652,7 +651,7 @@ def cli(): @needs_fd_capture def test_capture_fd_stale_reference(): - """capture='fd' captures writes from stale stdout references (issue #2874). + """capture='fd' captures writes from stale stdout references. Simulates ``from sys import stdout`` at import time, which grabs the real stdout connected to fd 1. The stale object's underlying @@ -678,8 +677,8 @@ def cli(): @needs_fd_capture def test_capture_fd_logging_handler(tmp_path): - """capture='fd' captures logging output from a handler holding a stale - stderr reference (issue #2827). + """capture='fd' captures logging output from a handler holding a stale stderr + reference. stdlib logging.StreamHandler grabs sys.stderr at configuration time. Under normal CliRunner (sys-level capture), the handler still writes @@ -724,7 +723,7 @@ def cli(): @needs_fd_capture def test_capture_fd_faulthandler(): - """faulthandler.enable() works with capture='fd' (issue #2865).""" + """faulthandler.enable() works with capture='fd'.""" @click.command() def cli(): @@ -738,9 +737,8 @@ def cli(): def test_capture_sys_fileno_raises(): - """capture='sys' leaves fileno() raising UnsupportedOperation, so user - code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host - runner's stdout (issue #3384). + """capture='sys' leaves fileno() raising UnsupportedOperation, so user code that + does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host runner's stdout. """ @click.command() diff --git a/tests/test_types/test_File.py b/tests/test_types/test_File.py index 4c67ed133..e7e238c3b 100644 --- a/tests/test_types/test_File.py +++ b/tests/test_types/test_File.py @@ -13,10 +13,11 @@ def test_file_surrogates(type, tmp_path): """Ensures that the error handling in ``click.File`` is robust. - ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems - that reject non-UTF-8 names, like ZFS with ``utf8only=on``. + ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems that + reject non-UTF-8 names, like ZFS with ``utf8only=on``. - See: https://github.com/pallets/click/issues/2634 + The test matches these errors instead of using the skip of ``test_path_surrogates``, + which also skips macOS, where this test passes. """ path = tmp_path / "\udcff" match = ( diff --git a/tests/test_types/test_convert_type.py b/tests/test_types/test_convert_type.py index 14617c35f..3d15c8c15 100644 --- a/tests/test_types/test_convert_type.py +++ b/tests/test_types/test_convert_type.py @@ -23,10 +23,7 @@ ], ) def test_convert_type_from_container_default(default): - """Container defaults are not natively supported and fall back to STRING. - - Refs: https://github.com/pallets/click/issues/3036 - """ + """Container defaults are not natively supported and fall back to STRING.""" assert click.types.convert_type(None, default) is click.STRING @@ -40,8 +37,6 @@ def test_convert_type_from_container_default(default): def test_explicit_container_type_splits_string(container_type, value, expected): """An explicit ``set`` or ``frozenset`` type wraps the builtin in a ``FuncParamType``, which splits CLI strings character-wise. - - Refs: https://github.com/pallets/click/issues/3036 """ param_type = click.types.convert_type(container_type) assert isinstance(param_type, click.types.FuncParamType) @@ -79,8 +74,6 @@ def test_type_inferred_from_default(default, expected): """Every row of the type-inference table in ``docs/parameter-types.md``. Keep the two in step: a change here is a change to documented behavior. - - Refs: https://github.com/pallets/click/issues/3036 """ assert click.types.convert_type(None, default) is expected @@ -89,8 +82,6 @@ def test_type_inferred_from_nested_sequence_default(): """A sequence of sequences gives a composite ``Tuple`` of the inner types. This is the one table row that is not a singleton ``ParamType``. - - Refs: https://github.com/pallets/click/issues/3036 """ param_type = click.types.convert_type(None, [(1, "git")]) assert isinstance(param_type, click.Tuple) @@ -98,10 +89,7 @@ def test_type_inferred_from_nested_sequence_default(): def test_explicit_dict_type_rejects_string(): - """An explicit ``dict`` type cannot convert a plain CLI string at all. - - Refs: https://github.com/pallets/click/issues/3036 - """ + """An explicit ``dict`` type cannot convert a plain CLI string at all.""" param_type = click.types.convert_type(dict) assert isinstance(param_type, click.types.FuncParamType) with pytest.raises(click.BadParameter): diff --git a/tests/test_utils/test_echo.py b/tests/test_utils/test_echo.py index 068e09b48..2b9fd64a6 100644 --- a/tests/test_utils/test_echo.py +++ b/tests/test_utils/test_echo.py @@ -116,16 +116,14 @@ def emulate_input(text): assert out == "Prompt to stdin with no suffix" assert err == "" - # On non-Windows the full prompt goes through redirect_stdout so - # nothing leaks to stdout when err=True. - # https://github.com/pallets/click/issues/2968 + # The full prompt goes through redirect_stdout so nothing leaks to stdout when + # err=True. emulate_input("asdlkj\n") click.prompt("Prompt to stderr", err=True) out, err = capfd.readouterr() assert out == "" assert err == "Prompt to stderr: " - # https://github.com/pallets/click/issues/3019 emulate_input("asdlkj\n") click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True) out, err = capfd.readouterr() @@ -144,14 +142,12 @@ def emulate_input(text): assert out == "Prompt to stdin with no suffix [y/N]" assert err == "" - # https://github.com/pallets/click/issues/2968 emulate_input("y\n") click.confirm("Prompt to stderr", err=True) out, err = capfd.readouterr() assert out == "" assert err == "Prompt to stderr [y/N]: " - # https://github.com/pallets/click/issues/3019 emulate_input("y\n") click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True) out, err = capfd.readouterr() diff --git a/tests/test_utils/test_echo_via_pager.py b/tests/test_utils/test_echo_via_pager.py index 77cb64c42..626941995 100644 --- a/tests/test_utils/test_echo_via_pager.py +++ b/tests/test_utils/test_echo_via_pager.py @@ -195,10 +195,10 @@ def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path): """A generator that yields then raises: click writes the partial output to the pager stream before propagating the exception. - The pager file content is intentionally NOT asserted: pipe-drain timing - between click and the pager subprocess is outside click's control - (#2899, #3470). Spying on ``_PagerWriter.write`` records what click sent - to the pager, which is deterministic regardless of scheduling. + The pager file content is intentionally NOT asserted: pipe-drain timing between + click and the pager subprocess is outside click's control. Spying on + ``_PagerWriter.write`` records what click sent to the pager, which is deterministic + regardless of scheduling. """ monkeypatch.setitem(os.environ, "PAGER", "cat") monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True) @@ -231,9 +231,9 @@ def spy(self, text): def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path): """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses. - Regression coverage for the cleanup path in ``_pipepager``'s exception - handler (issue #2899, PR #3470). Each iteration spawns a real pager - subprocess, raises before any data is written and check there is no leak. + Regression coverage for the cleanup path in ``_pipepager``'s exception handler. Each + iteration spawns a real pager subprocess, raises before any data is written and + check there is no leak. """ monkeypatch.setitem(os.environ, "PAGER", "cat") monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True) diff --git a/tests/test_utils/test_prompt.py b/tests/test_utils/test_prompt.py index 1b223afc3..3596ec8d8 100644 --- a/tests/test_utils/test_prompt.py +++ b/tests/test_utils/test_prompt.py @@ -53,7 +53,7 @@ def f(_): click.echo("interrupted") out, err = capsys.readouterr() - # On non-Windows, prompt is passed directly to getpass, not echoed separately + # The prompt is passed directly to getpass, not echoed separately. assert out == "\ninterrupted\n" @@ -69,11 +69,8 @@ def f(_): ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"], ) def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt): - """On non-Windows, prompt and confirm pass the full prompt text to the - underlying prompt function so readline handles editing correctly. - - https://github.com/pallets/click/issues/2968 - https://github.com/pallets/click/pull/2969 + """Prompt and confirm pass the full prompt text to the underlying prompt function so + readline handles editing correctly. """ received = [] diff --git a/tests/test_utils/test_style.py b/tests/test_utils/test_style.py index ab1c28ce6..bf66d2a9d 100644 --- a/tests/test_utils/test_style.py +++ b/tests/test_utils/test_style.py @@ -139,10 +139,7 @@ def test_styling_invalid_color(param, value): def test_unstyle_exception_message(): - """A styled exception message reads back as plain text. - - https://github.com/pallets/click/issues/2419 - """ + """A styled exception message reads back as plain text.""" exception = click.ClickException(click.style("red", fg="red") + " text") assert click.unstyle(str(exception)) == "red text"