| 1 |
""" |
| 2 |
Pygments basic API 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 pathlib |
| 10 |
import random |
| 11 |
from io import StringIO, BytesIO |
| 12 |
from os import path |
| 13 |
import re |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from pygments import lexers, formatters, lex, format, __version__ |
| 18 |
from pygments.token import _TokenType, Text |
| 19 |
from pygments.lexer import RegexLexer |
| 20 |
from pygments.formatter import Formatter |
| 21 |
from pygments.formatters.img import FontNotFound |
| 22 |
from pygments.lexers import LEXERS |
| 23 |
from pygments.util import ClassNotFound |
| 24 |
|
| 25 |
TESTDIR = path.dirname(path.abspath(__file__)) |
| 26 |
TESTFILE = path.join(TESTDIR, 'test_basic_api.py') |
| 27 |
|
| 28 |
test_content = [chr(i) for i in range(33, 128)] * 5 |
| 29 |
random.shuffle(test_content) |
| 30 |
test_content = ''.join(test_content) + '\n' |
| 31 |
|
| 32 |
|
| 33 |
@pytest.mark.parametrize('name', lexers.LEXERS) |
| 34 |
def test_lexer_instantiate_all(name): |
| 35 |
# instantiate every lexer, to see if the token type defs are correct |
| 36 |
getattr(lexers, name) |
| 37 |
|
| 38 |
major, minor, micro = (int(x) for x in __version__.split(".")) |
| 39 |
|
| 40 |
@pytest.mark.parametrize('cls', lexers._iter_lexerclasses(plugins=False)) |
| 41 |
def test_lexer_classes(cls): |
| 42 |
# test that every lexer class has the correct public API |
| 43 |
assert isinstance(cls.name, str) |
| 44 |
for attr in 'aliases', 'filenames', 'alias_filenames', 'mimetypes': |
| 45 |
assert hasattr(cls, attr) |
| 46 |
assert isinstance(getattr(cls, attr), list), \ |
| 47 |
f"{cls}: {attr} attribute wrong" |
| 48 |
assert isinstance(cls.url, str), \ |
| 49 |
(f"Lexer class {cls.__name__} is missing the `url` attribute. " |
| 50 |
"Please add it to provide a link to the language's homepage " |
| 51 |
"for the Pygments documentation (or set it to an empty " |
| 52 |
"string if this doesn't make sense for the lexer).") |
| 53 |
assert isinstance(cls.version_added, str), \ |
| 54 |
(f"Lexer class {cls.__name__} is missing the `version_added` attribute. " |
| 55 |
f"Please add `version_added = '{major}.{minor+1}'` to the class definition.") |
| 56 |
if cls.version_added: |
| 57 |
assert re.fullmatch(r"\d+\.\d+", cls.version_added), \ |
| 58 |
(f"Lexer class {cls.__name__} has a wrong version_added attribute. " |
| 59 |
"It should be a version number like <major>.<minor> (but not " |
| 60 |
"<major>.<minor>.<micro>).") |
| 61 |
result = cls.analyse_text("abc") |
| 62 |
assert isinstance(result, float) and 0.0 <= result <= 1.0 |
| 63 |
result = cls.analyse_text(".abc") |
| 64 |
assert isinstance(result, float) and 0.0 <= result <= 1.0 |
| 65 |
|
| 66 |
assert all(al.lower() == al for al in cls.aliases) |
| 67 |
|
| 68 |
if issubclass(cls, RegexLexer): |
| 69 |
cls(opt1="val1", opt2="val2") # should not raise |
| 70 |
if not hasattr(cls, '_tokens'): |
| 71 |
# if there's no "_tokens", the lexer has to be one with |
| 72 |
# multiple tokendef variants |
| 73 |
assert cls.token_variants |
| 74 |
for variant in cls.tokens: |
| 75 |
assert 'root' in cls.tokens[variant] |
| 76 |
else: |
| 77 |
assert 'root' in cls._tokens, \ |
| 78 |
f'{cls} has no root state' |
| 79 |
|
| 80 |
|
| 81 |
def test_lexer_metadata_uniqueness(): |
| 82 |
"""Check there is no overlapping metadata between lexers.""" |
| 83 |
# Build reverse indexes for each metadata type. |
| 84 |
name_index = {} |
| 85 |
alias_index = {} |
| 86 |
mimetype_index = {} |
| 87 |
for class_name, (_, name, aliases, _, mimetypes) in LEXERS.items(): |
| 88 |
name_index.setdefault(name, []).append(class_name) |
| 89 |
for alias in aliases: |
| 90 |
alias_index.setdefault(alias, []).append(class_name) |
| 91 |
for mimetype in mimetypes: |
| 92 |
mimetype_index.setdefault(mimetype, []).append(class_name) |
| 93 |
|
| 94 |
# Check that each metadata is unique. |
| 95 |
for class_name, (_, name, aliases, _, mimetypes) in LEXERS.items(): |
| 96 |
assert ( |
| 97 |
len(name_index[name]) == 1 |
| 98 |
), f"Name {name} is not unique: {name_index[name]}" |
| 99 |
for alias in aliases: |
| 100 |
assert ( |
| 101 |
len(alias_index[alias]) == 1 |
| 102 |
), f"Alias {alias} is not unique: {alias_index[alias]}" |
| 103 |
for mimetype in mimetypes: |
| 104 |
assert ( |
| 105 |
len(mimetype_index[mimetype]) == 1 |
| 106 |
), f"Mimetype {mimetype} is not unique: {mimetype_index[mimetype]}" |
| 107 |
|
| 108 |
|
| 109 |
@pytest.mark.parametrize("cls", lexers._iter_lexerclasses(plugins=False)) |
| 110 |
def test_random_input(cls): |
| 111 |
inst = cls() |
| 112 |
try: |
| 113 |
tokens = list(inst.get_tokens(test_content)) |
| 114 |
except KeyboardInterrupt: |
| 115 |
raise KeyboardInterrupt( |
| 116 |
f'interrupted {cls.__name__}.get_tokens(): test_content={test_content!r}') |
| 117 |
txt = "" |
| 118 |
for token in tokens: |
| 119 |
assert isinstance(token, tuple) |
| 120 |
assert isinstance(token[0], _TokenType) |
| 121 |
assert isinstance(token[1], str) |
| 122 |
txt += token[1] |
| 123 |
assert txt == test_content, f"{cls.name} lexer roundtrip failed: {test_content!r} != {txt!r}" |
| 124 |
|
| 125 |
|
| 126 |
@pytest.mark.parametrize('cls', lexers._iter_lexerclasses(plugins=False)) |
| 127 |
def test_lexer_options(cls): |
| 128 |
if cls.__name__ == 'RawTokenLexer': |
| 129 |
# this one is special |
| 130 |
return |
| 131 |
|
| 132 |
# test that the basic options work |
| 133 |
def ensure(tokens, output): |
| 134 |
concatenated = ''.join(token[1] for token in tokens) |
| 135 |
assert concatenated == output, \ |
| 136 |
f'{cls}: {concatenated!r} != {output!r}' |
| 137 |
|
| 138 |
inst = cls(stripnl=False) |
| 139 |
ensure(inst.get_tokens('a\nb'), 'a\nb\n') |
| 140 |
ensure(inst.get_tokens('\n\n\n'), '\n\n\n') |
| 141 |
inst = cls(stripall=True) |
| 142 |
ensure(inst.get_tokens(' \n b\n\n\n'), 'b\n') |
| 143 |
# some lexers require full lines in input |
| 144 |
if ('ConsoleLexer' not in cls.__name__ and |
| 145 |
'SessionLexer' not in cls.__name__ and |
| 146 |
not cls.__name__.startswith('Literate') and |
| 147 |
cls.__name__ not in ('ErlangShellLexer', 'RobotFrameworkLexer')): |
| 148 |
inst = cls(ensurenl=False) |
| 149 |
ensure(inst.get_tokens('a\nb'), 'a\nb') |
| 150 |
inst = cls(ensurenl=False, stripall=True) |
| 151 |
ensure(inst.get_tokens('a\nb\n\n'), 'a\nb') |
| 152 |
|
| 153 |
|
| 154 |
def test_get_lexers(): |
| 155 |
# test that the lexers functions work |
| 156 |
for func, args in [(lexers.get_lexer_by_name, ("python",)), |
| 157 |
(lexers.get_lexer_for_filename, ("test.py",)), |
| 158 |
(lexers.get_lexer_for_mimetype, ("text/x-python",)), |
| 159 |
(lexers.guess_lexer, ("#!/usr/bin/python3 -O\nprint",)), |
| 160 |
(lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>")) |
| 161 |
]: |
| 162 |
x = func(opt='val', *args) |
| 163 |
assert isinstance(x, lexers.PythonLexer) |
| 164 |
assert x.options["opt"] == "val" |
| 165 |
|
| 166 |
for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items(): |
| 167 |
assert cls == lexers.find_lexer_class(lname).__name__ |
| 168 |
|
| 169 |
for alias in aliases: |
| 170 |
assert cls == lexers.get_lexer_by_name(alias).__class__.__name__ |
| 171 |
|
| 172 |
for mimetype in mimetypes: |
| 173 |
assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__ |
| 174 |
|
| 175 |
try: |
| 176 |
lexers.get_lexer_by_name(None) |
| 177 |
except ClassNotFound: |
| 178 |
pass |
| 179 |
else: |
| 180 |
raise Exception |
| 181 |
|
| 182 |
|
| 183 |
@pytest.mark.parametrize('cls', [getattr(formatters, name) |
| 184 |
for name in formatters.FORMATTERS]) |
| 185 |
def test_formatter_public_api(cls): |
| 186 |
# test that every formatter class has the correct public API |
| 187 |
ts = list(lexers.PythonLexer().get_tokens("def f(): pass")) |
| 188 |
string_out = StringIO() |
| 189 |
bytes_out = BytesIO() |
| 190 |
|
| 191 |
info = formatters.FORMATTERS[cls.__name__] |
| 192 |
assert len(info) == 5 |
| 193 |
assert info[1], "missing formatter name" |
| 194 |
assert info[2], "missing formatter aliases" |
| 195 |
assert info[4], "missing formatter docstring" |
| 196 |
|
| 197 |
try: |
| 198 |
inst = cls(opt1="val1") |
| 199 |
except (ImportError, FontNotFound) as e: |
| 200 |
pytest.skip(str(e)) |
| 201 |
|
| 202 |
try: |
| 203 |
inst.get_style_defs() |
| 204 |
except NotImplementedError: |
| 205 |
# may be raised by formatters for which it doesn't make sense |
| 206 |
pass |
| 207 |
|
| 208 |
if cls.unicodeoutput: |
| 209 |
inst.format(ts, string_out) |
| 210 |
else: |
| 211 |
inst.format(ts, bytes_out) |
| 212 |
|
| 213 |
|
| 214 |
def test_formatter_encodings(): |
| 215 |
from pygments.formatters import HtmlFormatter |
| 216 |
|
| 217 |
# unicode output |
| 218 |
fmt = HtmlFormatter() |
| 219 |
tokens = [(Text, "ä")] |
| 220 |
out = format(tokens, fmt) |
| 221 |
assert isinstance(out, str) |
| 222 |
assert "ä" in out |
| 223 |
|
| 224 |
# encoding option |
| 225 |
fmt = HtmlFormatter(encoding="latin1") |
| 226 |
tokens = [(Text, "ä")] |
| 227 |
assert "ä".encode("latin1") in format(tokens, fmt) |
| 228 |
|
| 229 |
# encoding and outencoding option |
| 230 |
fmt = HtmlFormatter(encoding="latin1", outencoding="utf8") |
| 231 |
tokens = [(Text, "ä")] |
| 232 |
assert "ä".encode() in format(tokens, fmt) |
| 233 |
|
| 234 |
|
| 235 |
@pytest.mark.parametrize('cls', [getattr(formatters, name) |
| 236 |
for name in formatters.FORMATTERS]) |
| 237 |
def test_formatter_unicode_handling(cls): |
| 238 |
# test that the formatter supports encoding and Unicode |
| 239 |
tokens = list(lexers.PythonLexer(encoding='utf-8'). |
| 240 |
get_tokens("def f(): 'ä'")) |
| 241 |
|
| 242 |
try: |
| 243 |
inst = cls(encoding=None) |
| 244 |
except (ImportError, FontNotFound) as e: |
| 245 |
# some dependency or font not installed |
| 246 |
pytest.skip(str(e)) |
| 247 |
|
| 248 |
if cls.name != 'Raw tokens': |
| 249 |
out = format(tokens, inst) |
| 250 |
if cls.unicodeoutput: |
| 251 |
assert isinstance(out, str), f'{cls}: {out!r}' |
| 252 |
|
| 253 |
inst = cls(encoding='utf-8') |
| 254 |
out = format(tokens, inst) |
| 255 |
assert isinstance(out, bytes), f'{cls}: {out!r}' |
| 256 |
# Cannot test for encoding, since formatters may have to escape |
| 257 |
# non-ASCII characters. |
| 258 |
else: |
| 259 |
inst = cls() |
| 260 |
out = format(tokens, inst) |
| 261 |
assert isinstance(out, bytes), f'{cls}: {out!r}' |
| 262 |
|
| 263 |
|
| 264 |
def test_get_formatters(): |
| 265 |
# test that the formatters functions work |
| 266 |
x = formatters.get_formatter_by_name("html", opt="val") |
| 267 |
assert isinstance(x, formatters.HtmlFormatter) |
| 268 |
assert x.options["opt"] == "val" |
| 269 |
|
| 270 |
x = formatters.get_formatter_for_filename("a.html", opt="val") |
| 271 |
assert isinstance(x, formatters.HtmlFormatter) |
| 272 |
assert x.options["opt"] == "val" |
| 273 |
|
| 274 |
|
| 275 |
def test_styles(): |
| 276 |
# minimal style test |
| 277 |
from pygments.formatters import HtmlFormatter |
| 278 |
HtmlFormatter(style="pastie") |
| 279 |
|
| 280 |
|
| 281 |
def test_bare_class_handler(): |
| 282 |
from pygments.formatters import HtmlFormatter |
| 283 |
from pygments.lexers import PythonLexer |
| 284 |
try: |
| 285 |
lex('test\n', PythonLexer) |
| 286 |
except TypeError as e: |
| 287 |
assert 'lex() argument must be a lexer instance' in str(e) |
| 288 |
else: |
| 289 |
assert False, 'nothing raised' |
| 290 |
try: |
| 291 |
format([], HtmlFormatter) |
| 292 |
except TypeError as e: |
| 293 |
assert 'format() argument must be a formatter instance' in str(e) |
| 294 |
else: |
| 295 |
assert False, 'nothing raised' |
| 296 |
|
| 297 |
# These cases should not trigger this heuristic. |
| 298 |
class BuggyLexer(RegexLexer): |
| 299 |
def get_tokens(self, text, extra_argument): |
| 300 |
pass |
| 301 |
tokens = {'root': []} |
| 302 |
try: |
| 303 |
list(lex('dummy', BuggyLexer())) |
| 304 |
except TypeError as e: |
| 305 |
assert 'lex() argument must be a lexer instance' not in str(e) |
| 306 |
else: |
| 307 |
assert False, 'no error raised by buggy lexer?' |
| 308 |
|
| 309 |
class BuggyFormatter(Formatter): |
| 310 |
def format(self, tokensource, outfile, extra_argument): |
| 311 |
pass |
| 312 |
try: |
| 313 |
format([], BuggyFormatter()) |
| 314 |
except TypeError as e: |
| 315 |
assert 'format() argument must be a formatter instance' not in str(e) |
| 316 |
else: |
| 317 |
assert False, 'no error raised by buggy formatter?' |
| 318 |
|
| 319 |
class TestFilters: |
| 320 |
|
| 321 |
def test_basic(self): |
| 322 |
filters_args = [ |
| 323 |
('whitespace', {'spaces': True, 'tabs': True, 'newlines': True}), |
| 324 |
('whitespace', {'wstokentype': False, 'spaces': True}), |
| 325 |
('highlight', {'names': ['isinstance', 'lexers', 'x']}), |
| 326 |
('codetagify', {'codetags': 'API'}), |
| 327 |
('keywordcase', {'case': 'capitalize'}), |
| 328 |
('raiseonerror', {}), |
| 329 |
('gobble', {'n': 4}), |
| 330 |
('tokenmerge', {}), |
| 331 |
('symbols', {'lang': 'isabelle'}), |
| 332 |
] |
| 333 |
for x, args in filters_args: |
| 334 |
lx = lexers.PythonLexer() |
| 335 |
lx.add_filter(x, **args) |
| 336 |
# We don't read as binary and decode, but instead read as text, as |
| 337 |
# we need consistent line endings. Otherwise we'll get \r\n on |
| 338 |
# Windows |
| 339 |
with open(TESTFILE, encoding='utf-8') as fp: |
| 340 |
text = fp.read() |
| 341 |
tokens = list(lx.get_tokens(text)) |
| 342 |
assert all(isinstance(t[1], str) for t in tokens), \ |
| 343 |
f'{x} filter did not return Unicode' |
| 344 |
roundtext = ''.join([t[1] for t in tokens]) |
| 345 |
if x not in ('whitespace', 'keywordcase', 'gobble'): |
| 346 |
# these filters change the text |
| 347 |
assert roundtext == text, \ |
| 348 |
f"lexer roundtrip with {x} filter failed" |
| 349 |
|
| 350 |
def test_raiseonerror(self): |
| 351 |
lx = lexers.PythonLexer() |
| 352 |
lx.add_filter('raiseonerror', excclass=RuntimeError) |
| 353 |
assert pytest.raises(RuntimeError, list, lx.get_tokens('$')) |
| 354 |
|
| 355 |
def test_whitespace(self): |
| 356 |
lx = lexers.PythonLexer() |
| 357 |
lx.add_filter('whitespace', spaces='%') |
| 358 |
with open(TESTFILE, 'rb') as fp: |
| 359 |
text = fp.read().decode('utf-8') |
| 360 |
lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) |
| 361 |
assert ' ' not in lxtext |
| 362 |
|
| 363 |
def test_keywordcase(self): |
| 364 |
lx = lexers.PythonLexer() |
| 365 |
lx.add_filter('keywordcase', case='capitalize') |
| 366 |
with open(TESTFILE, 'rb') as fp: |
| 367 |
text = fp.read().decode('utf-8') |
| 368 |
lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) |
| 369 |
assert 'Def' in lxtext and 'Class' in lxtext |
| 370 |
|
| 371 |
def test_codetag(self): |
| 372 |
lx = lexers.PythonLexer() |
| 373 |
lx.add_filter('codetagify') |
| 374 |
text = '# BUG: text' |
| 375 |
tokens = list(lx.get_tokens(text)) |
| 376 |
assert '# ' == tokens[0][1] |
| 377 |
assert 'BUG' == tokens[1][1] |
| 378 |
|
| 379 |
def test_codetag_boundary(self): |
| 380 |
# ticket #368 |
| 381 |
lx = lexers.PythonLexer() |
| 382 |
lx.add_filter('codetagify') |
| 383 |
text = '# DEBUG: text' |
| 384 |
tokens = list(lx.get_tokens(text)) |
| 385 |
assert '# DEBUG: text' == tokens[0][1] |
| 386 |
|
| 387 |
def test_symbols(self): |
| 388 |
lx = lexers.IsabelleLexer() |
| 389 |
lx.add_filter('symbols') |
| 390 |
text = 'lemma "A \\<Longrightarrow> B"' |
| 391 |
tokens = list(lx.get_tokens(text)) |
| 392 |
assert 'lemma' == tokens[0][1] |
| 393 |
assert 'A ' == tokens[3][1] |
| 394 |
assert '\U000027f9' == tokens[4][1] |