Debian Codegraph @

tests/test__cli/test__cli_util_errors.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import operator
5 from typing import TYPE_CHECKING
6
7 from sphinx._cli.util.colour import blue, reset
8 from sphinx._cli.util.errors import strip_escape_sequences
9
10 if TYPE_CHECKING:
11 from collections.abc import Sequence
12 from typing import Final
13
14 CURSOR_UP: Final[str] = '\x1b[2A' # ignored ANSI code
15 ERASE_LINE: Final[str] = '\x1b[2K' # supported ANSI code
16 TEXT: Final[str] = '\x07 ß Hello world!'
17
18
19 def test_strip_escape_sequences() -> None:
20 # double ERASE_LINE so that the tested strings may have 2 of them
21 ansi_base_blocks = [
22 TEXT,
23 blue(TEXT),
24 reset(TEXT),
25 ERASE_LINE,
26 ERASE_LINE,
27 CURSOR_UP,
28 ]
29 # :func:`strip_escape_sequences` strips ANSI codes known by Sphinx
30 text_base_blocks = [
31 TEXT,
32 TEXT,
33 TEXT,
34 '',
35 '',
36 CURSOR_UP,
37 ]
38
39 assert len(text_base_blocks) == len(ansi_base_blocks)
40 N = len(ansi_base_blocks)
41
42 def next_ansi_blocks(choices: Sequence[str], n: int) -> Sequence[str]:
43 # Get a list of *n* words from a cyclic sequence of *choices*.
44 #
45 # For instance ``next_ansi_blocks(['a', 'b'], 3) == ['a', 'b', 'a']``.
46 stream = itertools.cycle(choices)
47 return list(map(operator.itemgetter(0), zip(stream, range(n), strict=False)))
48
49 # generate all permutations of length N
50 for sigma in itertools.permutations(range(N), N):
51 # apply the permutation on the blocks with ANSI codes
52 ansi_blocks = list(map(ansi_base_blocks.__getitem__, sigma))
53 # apply the permutation on the blocks with stripped codes
54 text_blocks = list(map(text_base_blocks.__getitem__, sigma))
55
56 for glue, n in itertools.product(['.', '\n', '\r\n'], range(4 * N)):
57 ansi_strings = next_ansi_blocks(ansi_blocks, n)
58 text_strings = next_ansi_blocks(text_blocks, n)
59 assert len(ansi_strings) == len(text_strings) == n
60
61 ansi_string = glue.join(ansi_strings)
62 text_string = glue.join(text_strings)
63 assert strip_escape_sequences(ansi_string) == text_string
64
65
66 def test_strip_ansi_short_forms() -> None:
67 # In Sphinx, we always "normalize" the color codes so that they
68 # match "\x1b\[(\d\d;){0,2}(\d\d)m" but it might happen that
69 # some messages use '\x1b[0m' instead of ``reset(s)``, so we
70 # test whether this alternative form is supported or not.
71
72 for strip_function in strip_escape_sequences, strip_escape_sequences:
73 # \x1b[m and \x1b[0m are equivalent to \x1b[00m
74 assert strip_function('\x1b[m') == ''
75 assert strip_function('\x1b[0m') == ''
76
77 # \x1b[1m is equivalent to \x1b[01m
78 assert strip_function('\x1b[1mbold\x1b[0m') == 'bold'
79
80 # \x1b[K is equivalent to \x1b[0K
81 assert strip_escape_sequences('\x1b[K') == ''