diff --git a/tests/test_completion/test_sanitization.py b/tests/test_completion/test_sanitization.py index 9150b94cd5..0f931bd64b 100644 --- a/tests/test_completion/test_sanitization.py +++ b/tests/test_completion/test_sanitization.py @@ -1,38 +1,36 @@ -from importlib.machinery import ModuleSpec -from unittest.mock import patch - import pytest +import typer._completion_classes from typer._completion_classes import _sanitize_help_text @pytest.mark.parametrize( - "find_spec, help_text, expected", + "has_rich, help_text, expected", [ ( - ModuleSpec("rich", loader=None), + True, "help text without rich tags", "help text without rich tags", ), ( - None, + False, "help text without rich tags", "help text without rich tags", ), ( - ModuleSpec("rich", loader=None), + True, "help [bold]with[/] rich tags", "help with rich tags", ), ( - None, + False, "help [bold]with[/] rich tags", "help [bold]with[/] rich tags", ), ], ) def test_sanitize_help_text( - find_spec: ModuleSpec | None, help_text: str, expected: str + has_rich: bool, help_text: str, expected: str, monkeypatch: pytest.MonkeyPatch ): - with patch("importlib.util.find_spec", return_value=find_spec) as mock_find_spec: - assert _sanitize_help_text(help_text) == expected - mock_find_spec.assert_called_once_with("rich") + # we can't monkeypatch typer.core.HAS_RICH because _completion_classes will already have imported it before this test runs + monkeypatch.setattr(typer._completion_classes, "HAS_RICH", has_rich) + assert _sanitize_help_text(help_text) == expected diff --git a/typer/_completion_classes.py b/typer/_completion_classes.py index 8548fb4d6a..f5fdc221fa 100644 --- a/typer/_completion_classes.py +++ b/typer/_completion_classes.py @@ -1,4 +1,3 @@ -import importlib.util import os import re import sys @@ -16,11 +15,12 @@ COMPLETION_SCRIPT_ZSH, Shells, ) +from .core import HAS_RICH def _sanitize_help_text(text: str) -> str: """Sanitizes the help text by removing rich tags""" - if not importlib.util.find_spec("rich"): + if not HAS_RICH: return text from . import rich_utils