Debian Codegraph @

tests/test_basic_api.py

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