Debian Codegraph @

tests/test_terminal_formatter.py

raw
1 """
2 Pygments terminal formatter tests
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
6 :license: BSD, see LICENSE for details.
7 """
8
9 import re
10 from io import StringIO
11
12 from pygments.lexers.sql import PlPgsqlLexer
13 from pygments.formatters import TerminalFormatter, Terminal256Formatter, \
14 HtmlFormatter, LatexFormatter
15
16 from pygments.style import Style
17 from pygments.token import Token
18 from pygments.lexers import Python3Lexer
19 from pygments import highlight
20
21 DEMO_TEXT = '''\
22 -- comment
23 select
24 * from bar;
25 '''
26 DEMO_LEXER = PlPgsqlLexer
27 DEMO_TOKENS = list(DEMO_LEXER().get_tokens(DEMO_TEXT))
28
29 ANSI_RE = re.compile(r'\x1b[\w\W]*?m')
30
31
32 def strip_ansi(x):
33 return ANSI_RE.sub('', x)
34
35
36 def test_reasonable_output():
37 out = StringIO()
38 TerminalFormatter().format(DEMO_TOKENS, out)
39 plain = strip_ansi(out.getvalue())
40 assert DEMO_TEXT.count('\n') == plain.count('\n')
41 print(repr(plain))
42
43 for a, b in zip(DEMO_TEXT.splitlines(), plain.splitlines()):
44 assert a == b
45
46
47 def test_reasonable_output_lineno():
48 out = StringIO()
49 TerminalFormatter(linenos=True).format(DEMO_TOKENS, out)
50 plain = strip_ansi(out.getvalue())
51 assert DEMO_TEXT.count('\n') + 1 == plain.count('\n')
52 print(repr(plain))
53
54 for a, b in zip(DEMO_TEXT.splitlines(), plain.splitlines()):
55 assert a in b
56
57
58 class MyStyle(Style):
59 styles = {
60 Token.Comment: 'ansibrightblack',
61 Token.String: 'ansibrightblue bg:ansired',
62 Token.Number: 'ansibrightgreen bg:ansigreen',
63 Token.Number.Hex: 'ansigreen bg:ansibrightred',
64 Token.Other: '#3366AA'
65 }
66
67
68 CODE = '''
69 # this should be a comment
70 print("Hello World")
71 async def function(a,b,c, *d, **kwarg:Bool)->Bool:
72 pass
73 return 123, 0xb3e3
74
75 '''
76
77
78 def test_style_html():
79 style = HtmlFormatter(style=MyStyle).get_style_defs()
80 assert '#555' in style, "ansigray for comment not html css style"
81 assert '36A' in style, "6-character style was not shortened"
82
83
84 def test_others_work():
85 """Check other formatters don't crash."""
86 highlight(CODE, Python3Lexer(), LatexFormatter(style=MyStyle))
87 highlight(CODE, Python3Lexer(), HtmlFormatter(style=MyStyle))
88
89
90 def test_256esc_seq():
91 """
92 Test that a few escape sequences are actually used when using ansi<> color
93 codes.
94 """
95 def termtest(x):
96 return highlight(x, Python3Lexer(),
97 Terminal256Formatter(style=MyStyle))
98
99 assert '32;101' in termtest('0x123')
100 assert '92;42' in termtest('123')
101 assert '90' in termtest('#comment')
102 assert '94;41' in termtest('"String"')