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