Rise
The Vieneo Province
Loading...
Searching...
No Matches
BuildTestCatalog.py
Go to the documentation of this file.
1"""Build/check the Doxygen test catalog without importing or running any tests.
2
3Run with Python 3.10+: python docs/BuildTestCatalog.py [--check]
4The reviewed fixture and case inventory lives in TestCatalog.json. Assertion
5messages are read from source, so the documentation quotes the actual checks.
6"""
7from __future__ import annotations
8
9import argparse
10import ast
11import hashlib
12import html
13import json
14import re
15import sys
16from pathlib import Path
17
18ROOT = Path(__file__).resolve().parents[1]
19MANIFEST = ROOT / 'docs/TestCatalog.json'
20OUTPUT = ROOT / 'docs/TestCatalog.dox'
21TOKEN = re.compile(r'R"(?P<delim>[^ ()\\\t\r\n]{0,16})\‍(.*?\‍)(?P=delim)"|//[^\n]*|/\*.*?\*/|(?:u8|[LuU])?"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', re.S)
22CHECK = re.compile(r'\b(?:Check|check|Require|require|Expect|Assert|Near|HR|CHECK|REQUIRE|assert|static_assert|CheckNear|ExpectNear)\s*\‍(')
23
24
25def read(path):
26 return path.read_text(encoding='utf-8-sig', errors='replace')
27
28
29def mask(text):
30 return TOKEN.sub(lambda m: ''.join('\n' if c == '\n' else ' ' for c in m[0]), text)
31
32
33def close(text, start, opening='(', closing=')'):
34 depth = 0
35 for i in range(start, len(text)):
36 if text[i] == opening:
37 depth += 1
38 elif text[i] == closing:
39 depth -= 1
40 if depth == 0:
41 return i
42 raise ValueError(f'Unbalanced {opening} at offset {start}')
43
44
45def strings(text):
46 values = []
47 for m in TOKEN.finditer(text):
48 token = m[0]
49 if token.startswith(('//', '/*', "'", 'R"')):
50 continue
51 token = re.sub(r'^(u8|[LuU])', '', token)
52 try:
53 value = ast.literal_eval(token)
54 except (ValueError, SyntaxError):
55 value = token[1:-1]
56 if isinstance(value, str):
57 values.append(value.replace('\n', ' '))
58 return values
59
60
61def messages(text):
62 clean = mask(text)
63 found = []
64 for match in CHECK.finditer(clean):
65 start = clean.find('(', match.start())
66 end = close(clean, start)
67 # Split the arguments at the outer level; nested strings in expressions
68 # are not assertion descriptions (e.g. Find("some command")).
69 depth = 0
70 arg_start = start + 1
71 args = []
72 for i in range(start + 1, end):
73 if clean[i] in '([{':
74 depth += 1
75 elif clean[i] in ')]}':
76 depth -= 1
77 elif clean[i] == ',' and depth == 0:
78 args.append(text[arg_start:i])
79 arg_start = i + 1
80 args.append(text[arg_start:end])
81 for arg in args[1:]:
82 if re.match(r'\s*(?:u8|[LuU])?"', arg):
83 value = ''.join(strings(arg)).strip()
84 if value and value not in found:
85 found.append(value)
86 return found
87
88
89def cpp_cases(text):
90 clean = mask(text)
91 pattern = re.compile(r'^[ \t]*(?:(?:static|inline|constexpr|virtual|explicit)\s+)*(?:void|int|bool|float|double|HRESULT|unsigned|DWORD)\s+(?P<name>[A-Za-z_]\w*(?:::\w+)*)\s*\‍(', re.M)
92 cases = {}
93 consumed = -1
94 for match in pattern.finditer(clean):
95 if match.start() < consumed:
96 continue
97 opening = clean.find('(', match.start())
98 end = close(clean, opening)
99 tail = re.match(r'\s*(?:(?:const|noexcept|override|final|try)\s*)*\{', clean[end + 1:])
100 if not tail:
101 continue
102 begin = end + 1 + tail.end() - 1
103 finish = close(clean, begin, '{', '}')
104 consumed = finish
105 name = match['name']
106 labels = messages(text[begin:finish + 1])
107 has_unlabelled_checks = bool(CHECK.search(clean[begin:finish + 1]))
108 has_failure_path = bool(re.search(r'\bthrow\s+|\breturn\s+[2-9]\d*\s*;', clean[begin:finish + 1]))
109 if (not labels and not (name in {'main', 'wmain'} and (has_unlabelled_checks or has_failure_path))) or name in {'Check', 'Require', 'Expect', 'Assert', 'Near', 'HR', 'CheckNear', 'ExpectNear'}:
110 continue
111 key = name
112 ordinal = 2
113 while key in cases:
114 key = f'{name} [{ordinal}]'
115 ordinal += 1
116 cases[key] = {'line': text.count('\n', 0, match.start()) + 1, 'messages': labels}
117 # Compile-time checks have no enclosing test function.
118 if not cases and 'static_assert' in clean:
119 cases['static_assert'] = {'line': text.count('\n', 0, clean.index('static_assert')) + 1,
120 'messages': messages(text)}
121 return cases
122
123
124def python_cases(text):
125 tree = ast.parse(text)
126 cases = {}
127 for node in ast.walk(tree):
128 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith('test_'):
129 # Include the class in the identity: different unittest classes may
130 # legitimately use the same method name.
131 owner = next((p.name for p in ast.walk(tree) if isinstance(p, ast.ClassDef) and node in p.body), None)
132 key = f'{owner}.{node.name}' if owner else node.name
133 labels = []
134 doc = ast.get_docstring(node)
135 if doc:
136 labels.append(doc)
137 for child in ast.walk(node):
138 if isinstance(child, ast.Assert) and isinstance(child.msg, ast.Constant) and isinstance(child.msg.value, str):
139 labels.append(child.msg.value)
140 cases[key] = {'line': node.lineno, 'messages': list(dict.fromkeys(labels))}
141 if not cases:
142 labels = [n.msg.value for n in ast.walk(tree) if isinstance(n, ast.Assert)
143 and isinstance(n.msg, ast.Constant) and isinstance(n.msg.value, str)]
144 cases['script'] = {'line': 1, 'messages': list(dict.fromkeys(labels))}
145 return cases
146
147
148def source_cases(path):
149 text = read(ROOT / path)
150 if path.endswith('.py'):
151 return python_cases(text)
152 if path.endswith('.ps1'):
153 labels = re.findall(r'^\s*(?:Check|Assert|Assert-[\w-]+)\b[^\n]*[\'\"]([^\'\"\n]+)[\'\"]\s*$', text, re.M)
154 return {'script': {'line': 1, 'messages': list(dict.fromkeys(labels))}}
155 return cpp_cases(text)
156
157
159 paths = set()
160 for path in (ROOT / 'Tests').rglob('*'):
161 if any(p in {'obj', 'Debug', 'Release', 'x64', 'Reference', 'Reference9', 'Fixtures', '__pycache__'} for p in path.relative_to(ROOT / 'Tests').parts[:-1]):
162 continue
163 if path.suffix not in {'.cpp', '.h', '.py', '.ps1'}:
164 continue
165 relative = path.relative_to(ROOT).as_posix()
166 if ('Tests' in path.stem or path.stem.startswith(('Verify', 'Check', 'Audit', 'Test-'))
167 or (path.suffix in {'.cpp', '.h'} and source_cases(relative))):
168 paths.add(relative)
169 return paths
170
171
172def includes(entry):
173 """Local test-source closure; never follow production or generated trees."""
174 pending = [ROOT / entry]
175 found = set()
176 while pending:
177 path = pending.pop().resolve()
178 if not path.is_relative_to(ROOT / 'Tests') or not path.is_file():
179 continue
180 relative = path.relative_to(ROOT).as_posix()
181 if relative in found:
182 continue
183 found.add(relative)
184 if path.suffix not in {'.h', '.cpp'}:
185 continue
186 for name in re.findall(r'^\s*#include\s+"([^"\n]+)"', read(path), re.M):
187 pending.append(path.parent / name.replace('\\', '/'))
188 return found
189
190
191def ident(text):
192 return re.sub(r'[^a-z0-9]+', '_', text.lower()).strip('_')
193
194
195def case_title(name):
196 if name in {'main', 'wmain'}:
197 return 'Entry-point checks'
198 if name == 'static_assert':
199 return 'Compile-time checks'
200 if name == 'script':
201 return 'Script checks'
202 name = name.split('.')[-1].removeprefix('test_')
203 return re.sub(r'(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])', ' ', name.replace('_', ' '))
204
205
206def escape(text):
207 # Prevent assertion text from accidentally introducing Doxygen commands,
208 # links, lists, or terminating its containing documentation comment.
209 # Doxygen supports named HTML entities and its own punctuation escapes;
210 # numeric HTML entities are printed literally in ordinary documentation.
211 value = html.escape(text, quote=False)
212 value = re.sub(r'[\\@*_#`]', lambda match: '\\' + match[0], value)
213 return value.replace('*/', '*<span></span>/')
214
215
216def generate(data):
217 fixtures = data['fixtures']
218 registered = {source for fixture in fixtures for source in fixture['sources']}
219 ignored = data.get('support_files', {})
220 errors = []
221 for path in sorted(inventory() - registered - ignored.keys()):
222 errors.append(f'Uncataloged test source: {path}')
223 for path, reason in ignored.items():
224 if not (ROOT / path).is_file() or not reason.strip():
225 errors.append(f'Missing support file or reason: {path}')
226 output = [
227 '// Generated by docs/BuildTestCatalog.py. Edit TestCatalog.json and source check messages.',
228 '/** @page test_catalog Test catalog',
229 '@brief Tests organized by subsystem, fixture/harness, and named verification case.',
230 '',
231 'This is a source inventory, not a test run or a pass/fail report. A fixture here is',
232 'the explicitly named test harness and its shared setup; it need not be a framework class.',
233 'Cases are named verification functions, unittest methods, or a script/entry-point check group.',
234 'Parameterized loops may perform many assertions within one case. Support check groups',
235 'can be called by multiple scenarios. Conditional and diagnostic paths are included;',
236 'their presence does not mean the default invocation executes them.',
237 '',
238 'Each case has a maintained description, an explicit fixture association, and a source link.',
239 'Detailed check messages come directly from the source. Build targets and configurations',
240 'describe availability, not verification or permission to run legacy configurations.',
241 'Use x64 Release where supported; legacy-only targets require separate authorization.',
242 '',
243 '@tableofcontents',
244 '',
245 'Browse all @subpage test_catalog_sources "test source files".',
246 ]
247 for subsystem, title in data['subsystems'].items():
248 group = [f for f in fixtures if f['subsystem'] == subsystem]
249 output += [f'@section tests_{subsystem} {title}', '']
250 for fixture in group:
251 count = sum(len(v['cases']) for v in fixture['sources'].values())
252 output += [f'- @subpage test_fixture_{fixture["id"]} "{fixture["title"]}" — {count} cases/check groups.']
253 output += ['']
254 output += [
255 '@section tests_maintenance Maintaining this catalog',
256 'When adding, changing, moving, or removing tests, update docs/TestCatalog.json in the same',
257 'change: the subsystem, fixture setup, source membership, case identity and readable purpose.',
258 'Update assertion descriptions when expectations change. Run',
259 '`python docs/BuildTestCatalog.py`, review the generated changes, then run',
260 '`python docs/BuildTestCatalog.py --check`. Normal Doxygen generation reads the committed',
261 'catalog directly; it does not run tests or require Python. Source views are included from',
262 'the current checkout when Doxygen runs. Run `doxygen Doxyfile` from the repository root.',
263 '',
264 'The validator detects missing/new/removed named check groups, invalid fixture associations,',
265 'missing source files and stale generated descriptions/line references. It is a lexical',
266 'inventory, not a C++ compiler or proof of execution reachability; review semantic changes.',
267 '*/',
268 ]
269 seen = set()
270 source_pages = set()
271 case_count = 0
272 for fixture in fixtures:
273 fid = fixture['id']
274 if fid in seen or ident(fid) != fid or fixture['subsystem'] not in data['subsystems']:
275 errors.append(f'Invalid/duplicate fixture ID or subsystem: {fid}')
276 seen.add(fid)
277 entry = fixture['entry']
278 associated = includes(entry)
279 if entry not in fixture['sources']:
280 errors.append(f'Fixture entry is not a documented source: {fid}: {entry}')
281 if not fixture['description'].strip() or not fixture['setup'].strip():
282 errors.append(f'Missing fixture description/setup: {fid}')
283 output += [f'/** @page test_fixture_{fid} {fixture["title"]}',
284 f'@brief {fixture["description"]}', '',
285 f'<b>Subsystem:</b> {data["subsystems"][fixture["subsystem"]]}<br>',
286 f'<b>Fixture/harness:</b> `{fid}`<br>', f'<b>Setup:</b> {fixture["setup"]}', '',
287 f'<b>Build/entry point:</b> {fixture["execution"]}', '', '@tableofcontents', '']
288 for source, record in fixture['sources'].items():
289 if source not in associated:
290 errors.append(f'Source does not belong to fixture {fid} via {entry}: {source}')
291 if not (ROOT / source).is_file() or not source.startswith('Tests/'):
292 errors.append(f'Missing/invalid source in {fid}: {source}')
293 continue
294 actual = source_cases(source)
295 declared = record['cases']
296 for key in sorted(actual.keys() - declared.keys()):
297 errors.append(f'Uncataloged case: {source}::{key} (fixture {fid})')
298 for key in sorted(declared.keys() - actual.keys()):
299 errors.append(f'Removed/renamed case: {source}::{key} (fixture {fid})')
300 sid = ident(source)
301 source_pages.add(source)
302 output += [f'@section {fid}_{sid} {Path(source).name}',
303 f'Source: @ref test_source_{sid} "{source}"', '']
304 if record.get('note'):
305 output += [escape(record['note']), '']
306 elif not declared:
307 output += ['Setup/dispatch source: named verification groups are documented under the associated case files.', '']
308 for key, description in declared.items():
309 if not description.strip():
310 errors.append(f'Empty description: {source}::{key}')
311 if key not in actual:
312 continue
313 details = actual[key]
314 anchor = f'{fid}_{sid}_{ident(key)}'
315 output += [f'@subsection {anchor} {escape(case_title(key))}',
316 f'<b>Fixture:</b> @ref test_fixture_{fid} "{fixture["title"]}" <br>',
317 f'<b>Case symbol:</b> `{key}` <br>',
318 f'<b>Source:</b> @ref test_source_{sid} "{source}:{details["line"]}"', '',
319 f'@test {escape(description)}', '']
320 if details['messages']:
321 output += ['<details><summary>Source check messages (including original failure wording)</summary>', '', '<ul>']
322 output += [f'<li>{escape(label)}</li>' for label in details['messages']]
323 output += ['</ul>', '</details>', '']
324 case_count += 1
325 output += ['*/', '']
326 # Source views use Doxygen includes rather than parsing all test stubs as
327 # production symbols. Identical Fixture/Bus/Sound/Check names stay separate.
328 output += ['/** @page test_catalog_sources Test source files',
329 'Source views for the fixtures and cases in @ref test_catalog.', '']
330 for source in sorted(source_pages):
331 output += [f'- @subpage test_source_{ident(source)} "{source}"']
332 output += ['*/', '']
333 for source in sorted(source_pages):
334 sid = ident(source)
335 digest = hashlib.sha256(read(ROOT / source).encode('utf-8')).hexdigest()
336 output += [f'// Source review fingerprint: {source} {digest}',
337 f'/** @page test_source_{sid} {source}',
338 'Source at documentation-generation time. See @ref test_catalog for fixture associations.',
339 f'@include{{lineno}} {source.removeprefix("Tests/")}', '*/', '']
340 if errors:
341 raise ValueError('\n'.join(errors))
342 return '\n'.join(output).rstrip() + '\n', case_count, len(source_pages)
343
344
345def main():
346 parser = argparse.ArgumentParser(description=__doc__)
347 parser.add_argument('--check', action='store_true', help='Validate inventory and require the generated catalog to be current.')
348 args = parser.parse_args()
349 try:
350 data = json.loads(read(MANIFEST))
351 content, cases, sources = generate(data)
352 if args.check:
353 if not OUTPUT.is_file() or read(OUTPUT) != content:
354 raise ValueError('docs/TestCatalog.dox is stale; run python docs/BuildTestCatalog.py and review the diff.')
355 else:
356 OUTPUT.write_text(content, encoding='utf-8', newline='\n')
357 print(f'Catalog verified: {len(data["subsystems"])} subsystems, {len(data["fixtures"])} fixtures, {cases} cases/check groups, {sources} source views.')
358 return 0
359 except (ValueError, KeyError, OSError, SyntaxError) as error:
360 print(str(error), file=sys.stderr)
361 return 1
362
363
364if __name__ == '__main__':
365 sys.exit(main())
close(text, start, opening='(', closing=')')