Debian Codegraph @

tests/conftest.py

raw
1 """
2 Generated lexer tests
3 ~~~~~~~~~~~~~~~~~~~~~
4
5 Checks that lexers output the expected tokens for each sample
6 under snippets/ and examplefiles/.
7
8 After making a change, rather than updating the samples manually,
9 run `pytest --update-goldens <changed file>`.
10
11 To add a new sample, create a new file matching this pattern.
12 The directory must match the alias of the lexer to be used.
13 Populate only the input, then just `--update-goldens`.
14
15 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
16 :license: BSD, see LICENSE for details.
17 """
18
19 from pathlib import Path
20
21 import pytest
22
23 import pygments.lexers
24 from pygments.token import Error
25
26
27 def pytest_addoption(parser):
28 parser.addoption('--update-goldens', action='store_true',
29 help='reset golden master benchmarks')
30
31
32 class LexerTestItem(pytest.Item):
33 def __init__(self, name, parent):
34 super().__init__(name, parent)
35 self.lexer = Path(str(self.fspath)).parent.name
36 self.actual = None
37
38 @classmethod
39 def _prettyprint_tokens(cls, tokens):
40 for tok, val in tokens:
41 if tok is Error and not cls.allow_errors:
42 raise ValueError(f'generated Error token at {val!r}')
43 yield f'{val!r:<13} {str(tok)[6:]}'
44 if val.endswith('\n'):
45 yield ''
46
47 def runtest(self):
48 lexer = pygments.lexers.get_lexer_by_name(self.lexer)
49 tokens = list(lexer.get_tokens(self.input))
50 self.actual = '\n'.join(self._prettyprint_tokens(tokens)).rstrip('\n') + '\n'
51 if self.config.getoption('--update-goldens'):
52 # Make sure the new golden output corresponds to the input.
53 output = ''.join(val for (tok, val) in tokens)
54 preproc_input = lexer._preprocess_lexer_input(self.input) # remove BOMs etc.
55 assert output == preproc_input
56 else:
57 # Make sure the output is the expected golden output
58 assert self.actual == self.expected
59
60 def _test_file_rel_path(self):
61 return Path(str(self.fspath)).relative_to(Path(__file__).parent.parent)
62
63 def _prunetraceback(self, excinfo):
64 excinfo.traceback = excinfo.traceback.cut(__file__).filter()
65
66 def repr_failure(self, excinfo):
67 if isinstance(excinfo.value, AssertionError):
68 if self.config.getoption('--update-goldens'):
69 message = (
70 f'The tokens produced by the "{self.lexer}" lexer '
71 'do not add up to the input.'
72 )
73 else:
74 rel_path = self._test_file_rel_path()
75 message = (
76 f'The tokens produced by the "{self.lexer}" lexer differ from the '
77 f'expected ones in the file "{rel_path}".\n'
78 f'Run `tox -- {Path(*rel_path.parts[:2])} --update-goldens` to update it.'
79 )
80 diff = str(excinfo.value).split('\n', 1)[-1]
81 return message + '\n\n' + diff
82 else:
83 return pytest.Item.repr_failure(self, excinfo)
84
85 def reportinfo(self):
86 return self.fspath, None, str(self._test_file_rel_path())
87
88 def maybe_overwrite(self):
89 if self.actual is not None and self.config.getoption('--update-goldens'):
90 self.overwrite()
91
92
93 class LexerSeparateTestItem(LexerTestItem):
94 allow_errors = False
95
96 def __init__(self, name, parent):
97 super().__init__(name, parent)
98
99 self.input = self.fspath.read_text('utf-8')
100 output_path = self.fspath + '.output'
101 if output_path.check():
102 self.expected = output_path.read_text(encoding='utf-8')
103 else:
104 self.expected = ''
105
106 def overwrite(self):
107 output_path = self.fspath + '.output'
108 output_path.write_text(self.actual, encoding='utf-8')
109
110
111 class LexerInlineTestItem(LexerTestItem):
112 allow_errors = True
113
114 def __init__(self, name, parent):
115 super().__init__(name, parent)
116
117 content = self.fspath.read_text('utf-8')
118 content, _, self.expected = content.partition('\n---tokens---\n')
119 if content.startswith('---input---\n'):
120 content = '\n' + content
121 self.comment, _, self.input = content.rpartition('\n---input---\n')
122 if not self.input.endswith('\n'):
123 self.input += '\n'
124 self.comment = self.comment.strip()
125
126 def overwrite(self):
127 with self.fspath.open('w', encoding='utf-8') as f:
128 f.write(self.comment)
129 if self.comment:
130 f.write('\n\n')
131 f.write('---input---\n')
132 f.write(self.input)
133 f.write('\n---tokens---\n')
134 f.write(self.actual)
135
136
137 def pytest_runtest_teardown(item, nextitem):
138 if isinstance(item, LexerTestItem):
139 item.maybe_overwrite()