Skip to content
Myr

test_compat.py

This file

Path

tests/test_compat.py

270 lines · 8.3 KiB · Python

Last changed by

Strip all ANSI sequences (#3681)Rowlando13before adoption8c1a0a7

History of this file

Take it

1from __future__ import annotations23import re4import sys56import pytest78import click9from click._compat import _ansi_re10from click._compat import strip_ansi11from click._compat import term_len12from click._textwrap import _truncate_visible1314ESC = "\033"1516# Inventory of every escape sequence Click itself emits. ``strip_ansi`` must17# keep removing all of them.18CLICK_EMITTED = [19    # SGR foreground/background, the basic 16 colors.20    f"{ESC}[30m",21    f"{ESC}[37m",22    f"{ESC}[40m",23    f"{ESC}[47m",24    # SGR 256-color and true-color (Click renders these with semicolons).25    f"{ESC}[38;5;200m",26    f"{ESC}[48;5;91m",27    f"{ESC}[38;2;255;12;128m",28    f"{ESC}[48;2;135;0;175m",29    # SGR attributes and their resets.30    f"{ESC}[1m",31    f"{ESC}[22m",32    f"{ESC}[4m",33    f"{ESC}[24m",34    f"{ESC}[53m",35    f"{ESC}[55m",36    f"{ESC}[9m",37    f"{ESC}[29m",38    # Reset-all appended by style().39    f"{ESC}[0m",40    # Screen clear and cursor home from click.clear().41    f"{ESC}[2J",42    f"{ESC}[1;1H",43    # Cursor hide/show around the progress bar.44    f"{ESC}[?25l",45    f"{ESC}[?25h",46]4748# CSI sequences Click never emits but may receive from other tooling.49CSI_FOREIGN = [50    # Colon-delimited (ISO 8613-6) true-color and 256-color SGR.51    f"{ESC}[38:2:255:0:0m",52    f"{ESC}[38:5:200m",53    f"{ESC}[1;38:2::255:0:0m",  # empty colon field is a valid parameter54    # SGR mouse reporting (the ``<`` parameter byte is 0x3C).55    f"{ESC}[<0;30;40M",56    f"{ESC}[<0;30;40m",57    # Private-mode set/reset with a multi-digit parameter.58    f"{ESC}[?1049h",59    f"{ESC}[?1049l",60    # Cursor-shape select: an intermediate byte (space, 0x20) before final ``q``.61    f"{ESC}[0 q",62    f"{ESC}[2 q",63    # Set scrolling region: a non-``m`` letter final byte.64    f"{ESC}[1;24r",65    # Function-key / bracketed-paste codes ending in ``~`` (0x7E).66    f"{ESC}[3~",67    f"{ESC}[200~",68    # Empty parameter list (``ESC [ m`` is a valid reset).69    f"{ESC}[m",70]7172# The previous pattern, kept here to prove the new one is a superset.73_LEGACY_ANSI_RE = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")747576def test_is_jupyter_kernel_output():77    class JupyterKernelFakeStream:78        pass7980    # implementation detail, aka cheapskate test81    JupyterKernelFakeStream.__module__ = "ipykernel.faked"82    assert click._compat._is_jupyter_kernel_output(stream=JupyterKernelFakeStream())838485@pytest.mark.parametrize(86    "stream",87    [None, sys.stdin, sys.stderr, sys.stdout],88)89@pytest.mark.parametrize(90    ("color", "expected_override"),91    [92        (True, False),93        (False, True),94        (None, None),95    ],96)97@pytest.mark.parametrize(98    ("isatty", "is_jupyter", "expected"),99    [100        (True, False, False),101        (False, True, False),102        (False, False, True),103    ],104)105def test_should_strip_ansi(106    monkeypatch,107    stream,108    color: bool | None,109    expected_override: bool | None,110    isatty: bool,111    is_jupyter: bool,112    expected: bool,113) -> None:114    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)115    monkeypatch.setattr(116        click._compat, "_is_jupyter_kernel_output", lambda x: is_jupyter117    )118119    if expected_override is not None:120        expected = expected_override121    assert click._compat.should_strip_ansi(stream=stream, color=color) == expected122123124@pytest.mark.parametrize("seq", CLICK_EMITTED + CSI_FOREIGN)125def test_strip_ansi_removes_full_sequence(seq):126    """Every complete CSI sequence is stripped, alone or wrapped in text."""127    assert strip_ansi(seq) == ""128    assert strip_ansi(f"a{seq}b") == "ab"129    assert term_len(f"a{seq}b") == 2130131132@pytest.mark.parametrize("final", ["m", "H", "J", "A", "z"])133@pytest.mark.parametrize("params", ["", "0", "1;2", ";", "?25", "0;0;0"])134def test_strip_ansi_is_superset_of_legacy(params, final):135    """Everything the legacy pattern stripped, the CSI grammar still strips."""136    seq = f"{ESC}[{params}{final}"137    assert _LEGACY_ANSI_RE.fullmatch(seq) is not None138    assert strip_ansi(seq) == ""139    assert strip_ansi(f"a{seq}b") == "ab"140141142@pytest.mark.parametrize(143    ("text", "expected"),144    [145        (f"{ESC}[31mred{ESC}[0m", "red"),146        (f"a{ESC}[38:2:1:2:3mb{ESC}[0mc", "abc"),147        (f"{ESC}[?25l{ESC}[2Jhidden{ESC}[?25h", "hidden"),148        (f"{ESC}[<0;1;1Mclick{ESC}[<0;1;1m", "click"),149        # Several adjacent sequences around each visible character.150        (f"{ESC}[1m{ESC}[31mA{ESC}[0m {ESC}[32mB{ESC}[0m", "A B"),151        # Real terminal captures ported from the boltons strip_ansi tests.152        # ANSI art fragment (its doctest example).153        (f"{ESC}[0m{ESC}[1;36mart{ESC}[46;34m\xdc", "art\xdc"),154        # `ls` color output, ending on a dangling SGR with no text after it.155        (156            f"ls\r\n{ESC}[00m{ESC}[01;31mfile.zip{ESC}[00m\r\n{ESC}[01;31m",157            "ls\r\nfile.zip\r\n",158        ),159        # Tab-separated colorized fields.160        (f"\t{ESC}[0;35mIP{ESC}[0m\t{ESC}[0;36m192.1.0.2{ESC}[0m", "\tIP\t192.1.0.2"),161        # A styled cell inside a box-drawing table.162        (163            f"╒══════╕\n│ {ESC}[1mCell{ESC}[0m │\n╘══════╛",164            "╒══════╕\n│ Cell │\n╘══════╛",165        ),166        # Kaomoji with a bolded run.167        (f"(╯°□°)╯︵ {ESC}[1m┻━┻{ESC}[0m", "(╯°□°)╯︵ ┻━┻"),168    ],169)170def test_strip_ansi_mixed_content(text, expected):171    assert strip_ansi(text) == expected172    assert term_len(text) == len(expected)173174175def test_strip_ansi_stops_at_final_byte():176    """The match ends at the first final byte."""177    assert strip_ansi(f"{ESC}[31mX{ESC}[0mY") == "XY"178    assert strip_ansi(f"{ESC}[1m{ESC}[31mZ") == "Z"179    # The final ``m`` ends the sequence; the following ``;1m`` is plain text.180    assert strip_ansi(f"{ESC}[m;1m") == ";1m"181182183@pytest.mark.parametrize(184    "text",185    [186        "",187        "plain text",188        "100% [done]",189        "array[0] = 1",190        "a;b;c",191        # Looks like SGR parameters but lacks the ESC introducer.192        "[38;5;200m not an escape",193        "[0m",194    ],195)196def test_strip_ansi_leaves_plain_text(text):197    """Text that merely resembles an escape sequence is never stripped."""198    assert strip_ansi(text) == text199    assert term_len(text) == len(text)200201202@pytest.mark.parametrize(203    "text",204    [205        f"{ESC}",  # lone ESC206        f"{ESC}[",  # CSI introducer with no final byte207        f"{ESC}[31",  # parameters but no final byte208        f"{ESC}[38:2:1",  # colon parameters, truncated209        f"{ESC}[0 ",  # intermediate byte but no final byte210    ],211)212def test_strip_ansi_leaves_incomplete_sequences(text):213    """An unterminated sequence (missing its final byte) is left untouched."""214    assert strip_ansi(text) == text215216217def test_strip_ansi_is_idempotent():218    text = f"{ESC}[38:2:1:2:3mhi{ESC}[0m {ESC}[<0;1;1mthere{ESC}[?25h"219    once = strip_ansi(text)220    assert once == "hi there"221    assert strip_ansi(once) == once222223224@pytest.mark.parametrize(225    ("text", "visible"),226    [227        ("", 0),228        ("plain", 5),229        (f"{ESC}[31mred{ESC}[0m", 3),230        (f"{ESC}[38;2;1;2;3mrgb{ESC}[0m", 3),231        (f"{ESC}[38:2:1:2:3mrgb{ESC}[0m", 3),232        (f"{ESC}[<0;1;1Mx{ESC}[<0;1;1m", 1),233        (f"{ESC}[0 qq", 1),234        (f"{ESC}[?25lvisible{ESC}[?25h", 7),235        (f"{ESC}[1m{ESC}[4m{ESC}[31mhello{ESC}[0m", 5),236    ],237)238def test_term_len(text, visible):239    assert term_len(text) == visible240241242@pytest.mark.parametrize("seq", CLICK_EMITTED + CSI_FOREIGN)243def test_ansi_re_matches_whole_sequence(seq):244    """``_ansi_re`` matches a complete sequence end to end as one token."""245    m = _ansi_re.match(seq)246    assert m is not None247    assert m.start() == 0248    assert m.end() == len(seq)249250251@pytest.mark.parametrize(252    ("text", "n", "expected"),253    [254        # No escapes: behaves like a plain prefix slice.255        ("abcdef", 3, "abc"),256        ("abc", 10, "abc"),257        ("abc", 0, ""),258        ("abc", -1, ""),259        # A leading escape is kept and does not count toward the budget.260        (f"{ESC}[31mabcdef{ESC}[0m", 3, f"{ESC}[31mabc"),261        # A colon true-color escape stays intact; the cut lands after 3 chars.262        (f"{ESC}[38:2:1:2:3mabcdef", 3, f"{ESC}[38:2:1:2:3mabc"),263        # A trailing escape past the cut is not pulled in.264        (f"{ESC}[31mabc{ESC}[0m", 3, f"{ESC}[31mabc"),265    ],266)267def test_truncate_visible(text, n, expected):268    out = _truncate_visible(text, n)269    assert out == expected270    assert term_len(out) <= max(n, 0)