diff --git a/tests/test_completion/test_sanitization.py b/tests/test_completion/test_sanitization.py index 9150b94cd5..bf6ed7bd04 100644 --- a/tests/test_completion/test_sanitization.py +++ b/tests/test_completion/test_sanitization.py @@ -36,3 +36,32 @@ def test_sanitize_help_text( 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") + + +@pytest.mark.parametrize( + "has_rich, help_text, expected", + [ + ( + False, + "help [bold]with[/] rich tags", + "help [bold]with[/] rich tags", + ), + ( + True, + "help [bold]with[/] rich tags", + "help with rich tags", + ), + ], +) +def test_sanitize_help_text_respects_has_rich( + has_rich: bool, help_text: str, expected: str +): + """When HAS_RICH is False, rich tags are preserved even if rich is installed.""" + with ( + patch("typer._completion_classes.HAS_RICH", has_rich), + patch( + "importlib.util.find_spec", + return_value=ModuleSpec("rich", loader=None), + ), + ): + assert _sanitize_help_text(help_text) == expected diff --git a/typer/_completion_classes.py b/typer/_completion_classes.py index cfae02c9bf..5380ead597 100644 --- a/typer/_completion_classes.py +++ b/typer/_completion_classes.py @@ -14,12 +14,19 @@ COMPLETION_SCRIPT_ZSH, Shells, ) +from .core import HAS_RICH def _sanitize_help_text(text: str) -> str: - """Sanitizes the help text by removing rich tags""" + """Sanitizes the help text by removing rich tags. + + Checks both that rich is installed AND that it is enabled + (respecting the TYPER_USE_RICH environment variable). + """ if not importlib.util.find_spec("rich"): return text + if not HAS_RICH: + return text from . import rich_utils return rich_utils.rich_render_text(text)