Debian Codegraph @

test/common/js_coverage.py

raw
1 #!/usr/bin/python3
2
3 #
4 # Copyright (C) 2024 Red Hat, Inc.
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7
8 import argparse
9 import bisect
10 import fnmatch
11 import hashlib
12 import json
13 import os
14 import sys
15 import time
16 from array import array
17 from collections import defaultdict
18 from collections.abc import Callable, Iterable, Sequence
19 from pathlib import Path
20 from typing import TypedDict
21
22 import pytest
23 from _pytest.terminal import TerminalReporter # TODO: https://github.com/pytest-dev/pytest/issues/7469
24 from yarl import URL
25
26
27 def find_line_starts(text: str) -> Sequence[int]:
28 result: list[int] = []
29 try:
30 line_start = 0
31 while True:
32 result.append(line_start)
33 line_start = text.index('\n', line_start) + 1
34 except ValueError:
35 if not text.endswith('\n'):
36 result.append(len(text) + 1) # pretend...
37 return result
38
39
40 # .translate() is a quick way to turn an entire sourcemap string into an
41 # iterable of the integer values that they represent. We do it this way
42 # because parsing this string is by far the slowest thing in this program and
43 # .translate() happens in C.
44 SOURCEMAP_CHARS = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/,;'
45 SOURCEMAP_TABLE = bytes(SOURCEMAP_CHARS.find(i) & 0xff for i in range(256))
46
47
48 # https://tc39.es/source-map/#mappings-structure
49 def parse_mappings(bundle: str, mappings: str) -> tuple[Sequence[int], Sequence[tuple[int, int, int]]]:
50 assert mappings.endswith((';', ','))
51
52 line_starts = find_line_starts(bundle)
53
54 # our result
55 bundle_offsets, source_offsets = array('i'), list[tuple[int, int, int]]()
56
57 # internal state
58 bundle_line = 0
59 token, token_shift = [0, 0, 0, 0, 0], 0 # for collecting the machine instruction
60 bits, bits_shift = 0, 0 # for collecting individual VLQ integers
61
62 for v in mappings.encode().translate(SOURCEMAP_TABLE):
63 if not v:
64 # 'A': common enough for a special-case to be a net performance win
65 assert not bits_shift # We should never have an 'A' after a continuation
66 token_shift += 1
67
68 elif v < 32:
69 # the final byte of a VLQ quantity: push it into the token array
70 bits += v << bits_shift
71 token[token_shift] += (-(bits >> 1)) if bits & 1 else (bits >> 1) # TODO: '+=' seems oddly slow
72 token_shift += 1
73 bits_shift = 0
74 bits = 0
75
76 elif v < 64:
77 # a non-final VLQ byte: store those bits
78 bits += (v & 31) << bits_shift
79 bits_shift += 5
80
81 else:
82 # a separator: process the token and emit the state
83 if token_shift:
84 # emit the state
85 bundle_offsets.append(token[0])
86 source_offsets.append((token[1], token[2], token[3]))
87 token_shift = 0 # start over
88
89 if v == 65: # ';': a new line
90 bundle_line += 1
91 token[0] = line_starts[bundle_line]
92
93 # make sure the final character is mapped -- esbuild doesn't do this for us
94 bundle_offsets.append(len(bundle))
95 source_offsets.append((token[1], token[2], token[3]))
96
97 return bundle_offsets, source_offsets
98
99
100 # this is the type of a sourcemap: https://tc39.es/source-map/
101 class SourceMap(TypedDict):
102 sources: str
103 sourcesContent: str
104 mappings: str
105
106
107 # these are the types reported from the browser directly via Profiler.takePreciseCoverage()
108 class BrowserCoverageRange(TypedDict):
109 startOffset: int
110 endOffset: int
111 count: int
112
113
114 class BrowserCoverageFunction(TypedDict):
115 functionName: str
116 ranges: Sequence[BrowserCoverageRange]
117
118
119 class BrowserCoverageUrl(TypedDict):
120 url: str
121 functions: Sequence[BrowserCoverageFunction]
122
123
124 class BrowserCoverageResult(TypedDict):
125 result: Sequence[BrowserCoverageUrl]
126
127
128 # these are the types we use in our file format (which reference the browser types)
129 class FileDescription(TypedDict):
130 filename: str
131 sha256: str
132
133
134 class CoverageFileEntry(TypedDict):
135 bundle: FileDescription
136 map: FileDescription
137 functions: Sequence[BrowserCoverageFunction]
138
139
140 class CoverageFile(TypedDict):
141 coverage: Sequence[CoverageFileEntry]
142
143
144 # Used to avoid reading and re-reading bundles mentioned from multiple coverage files
145 # also ensures that the file that we read is the one that was present during testing
146 class File:
147 def __init__(self, description: FileDescription) -> None:
148 content = Path(description['filename']).read_bytes()
149 self.sha256 = hashlib.sha256(content).hexdigest()
150 self.content = content.decode()
151
152 def verify(self, description: FileDescription) -> None:
153 if self.sha256 != description['sha256']:
154 raise RuntimeError(f'{description['filename']} has incorrect checksum')
155
156
157 # A collection of all coverage data for a particular source file - mutable
158 class SourceCoverageData:
159 def __init__(self, path: str, origin: str, content: str) -> None:
160 self.path = path
161 self.content = content
162 self.coverage = defaultdict[tuple[str, int, int, int, int], int](lambda: 0)
163 self.origin = origin
164 self.line_starts = find_line_starts(content)
165
166 def add_coverage(
167 self, function: str, start_line: int, start_col: int, end_line: int, end_col: int, count: int
168 ) -> None:
169 self.coverage[function, start_line, start_col, end_line, end_col] += count
170
171 def print_block(self, start_line: int, start_col: int, end_line: int, end_col: int, name: str) -> None:
172 start = self.line_starts[start_line] + start_col
173 end = self.line_starts[end_line] + end_col
174
175 print(f'\033[1m{self.path}\033[0m:\033[1;36m{start_line + 1}:{start_col + 1}-{end_line + 1}:{end_col + 1} \033[34m{name}\033[0m')
176 print(' ' * 6, ' ' * start_col + '▼ from here')
177
178 for line in range(start_line, end_line + 1):
179 line_start = self.line_starts[line]
180 line_end = self.line_starts[line + 1] - 1
181
182 before = self.content[line_start:start]
183 highlight = self.content[max(line_start, start):min(end, line_end)]
184 after = self.content[end:line_end]
185
186 print(f'\033[1;36m{line + 1:6}\033[0m', f'{before}\033[1;31m{highlight}\033[0m{after}')
187
188 # the end_col points to one character past the range, so adjust it backwards by 1
189 print(' ' * 6, ' ' * (end_col - 1) + '▲ to here')
190 print()
191
192
193 # A collection of all coverage data for a particular bundle - mutable
194 class BundleCoverageData:
195 def __init__(self, filename: str, entry: CoverageFileEntry) -> None:
196 self.coverage = defaultdict[tuple[str, int, int], int](lambda: 0)
197 self.filename = filename
198 self.bundle = File(entry['bundle'])
199 self.sourcemap = File(entry['map'])
200 self.functions = list[BrowserCoverageFunction]()
201
202 try:
203 map_data: SourceMap = json.loads(self.sourcemap.content)
204 except json.JSONDecodeError as exc:
205 raise RuntimeError(f'{entry['map']['filename']}: {exc}') from exc
206
207 self.src_names = map_data['sources']
208 self.src_contents = map_data['sourcesContent']
209 self.map_points, self.map_data = parse_mappings(self.bundle.content, map_data['mappings'])
210
211 def add_coverage_file_entry(self, entry: CoverageFileEntry) -> None:
212 assert entry['bundle']['filename'] == self.filename
213 self.bundle.verify(entry['bundle'])
214 self.sourcemap.verify(entry['map'])
215 for f in entry['functions']:
216 for r in f['ranges']:
217 self.coverage[f['functionName'], r['startOffset'], r['endOffset']] += r['count']
218
219 def map(self, start: int, end: int) -> tuple[str, str, int, int, int, int]:
220 # we want to find the first point equal to or after 'start'
221 # and the last point strictly before 'end'
222 start_index = bisect.bisect_right(self.map_points, start - 1)
223 start_file, start_line, start_col = self.map_data[start_index]
224
225 end_index = bisect.bisect_left(self.map_points, end - 1)
226 end_file, end_line, end_col = self.map_data[min(end_index, len(self.map_data) - 1)]
227
228 # don't bother with ranges that aren't within the same file
229 if start_file != end_file:
230 raise ValueError
231
232 return self.src_names[start_file], self.src_contents[start_file], start_line, start_col, end_line, end_col + 1
233
234
235 class Progress:
236 def report_step(self, step: str) -> None:
237 raise NotImplementedError
238
239 def report_detail(self, detail: str) -> None:
240 raise NotImplementedError
241
242 def done(self) -> None:
243 raise NotImplementedError
244
245
246 class FancyProgress(Progress):
247 def report_step(self, step: str) -> None:
248 self.step = step
249
250 def report_detail(self, detail: str) -> None:
251 THEME = '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈' # from https://github.com/console-rs/indicatif/blob/main/src/style.rs
252 frame = int(time.monotonic() * 10) % len(THEME)
253 sys.stdout.write(f'\r\033[2K\r{THEME[frame]} {self.step} : {detail} ')
254
255 def done(self) -> None:
256 sys.stdout.write('\r\033[2K\r') # clear line
257
258
259 class BoringProgress(Progress):
260 step = None
261
262 def report_step(self, step: str) -> None:
263 self.done()
264 print(f'{step}:', file=sys.stderr)
265 self.step = step
266
267 def report_detail(self, detail: str) -> None:
268 print(f' {detail}', file=sys.stderr)
269
270 def done(self) -> None:
271 if self.step is not None:
272 print('\n')
273
274
275 def report_coverage(paths: Sequence[Path], matches: Sequence[str]) -> None:
276 progress = FancyProgress() if os.isatty(2) else BoringProgress()
277
278 # We have data in three forms:
279 # - first, we have data in separate files corresponding to test runs
280 # .... which we split up and merge into ....
281 # - a set of BundleCoverageData objects, one per bundle file
282 # .... which we source-map and merge into ....
283 # - a set of SourceCoverageData objects, one per source file
284 # .... when we then use to show coverage data
285
286 # first transformation: test runs → bundles
287 progress.report_step('Parsing coverage data from test runs')
288 bundles = dict[str, BundleCoverageData]()
289
290 for path in paths:
291 progress.report_detail(path.name)
292 try:
293 file: CoverageFile = json.loads(path.read_text())
294 except (json.JSONDecodeError, OSError) as exc:
295 sys.exit(f'{path}: {exc}')
296
297 try:
298 for entry in file['coverage']:
299 filename = entry['bundle']['filename']
300 if filename not in bundles:
301 bundles[filename] = BundleCoverageData(filename, entry)
302 bundles[filename].add_coverage_file_entry(entry)
303
304 except (OSError, RuntimeError) as exc:
305 sys.exit(f'{path}: {exc}')
306
307 # second transformation: bundles → source files
308 progress.report_step('Collecting coverage data for bundles')
309 sources = dict[str, SourceCoverageData]()
310 for bundle in bundles.values():
311 progress.report_detail(bundle.filename)
312 for (function, start, end), count in bundle.coverage.items():
313 # find out what source file this block is from, and which lines/cols
314 try:
315 source_path, source_content, start_line, start_col, end_line, end_col = bundle.map(start, end)
316 except ValueError:
317 continue
318
319 source_path = source_path.lstrip('./') # strip leading '../' segments
320
321 if source_path.startswith('node_modules/'):
322 continue
323
324 if source_path not in sources:
325 # we didn't see this source file yet — create it
326 sources[source_path] = SourceCoverageData(source_path, bundle.filename, source_content)
327 else:
328 # we've seen this source file before — make sure it's identical to our copy
329 assert sources[source_path].content == source_content
330
331 # add the coverage
332 sources[source_path].add_coverage(function, start_line, start_col, end_line, end_col, count)
333
334 progress.done()
335
336 # now we're ready to print results
337 any_output = False
338 n_files = 0
339
340 if matches:
341 # print detailed output
342 for source in sources.values():
343 if not any(fnmatch.fnmatch(source.path, pat) for pat in matches):
344 continue
345
346 for (function, start_line, start_col, end_line, end_col), count in source.coverage.items():
347 if count == 0:
348 source.print_block(start_line, start_col, end_line, end_col, function)
349 any_output = True
350
351 n_files += 1
352
353 else:
354 # print summary table
355 print(f'{"Path":50} {"%":>7} (bytes covered) ~ uncovered lines')
356 for filename in sorted(sources):
357 source = sources[filename]
358 total, covered = 0, 0
359 uncovered_ranges = set[tuple[int, int]]()
360
361 for (_function, start_line, start_col, end_line, end_col), count in source.coverage.items():
362 # quick and dirty - we just count byte ranges, possibly multiple-counting overlaps
363 start_offset = source.line_starts[start_line] + start_col
364 end_offset = source.line_starts[end_line] + end_col
365 block_size = end_offset - start_offset
366 total += block_size
367 if count:
368 covered += block_size
369 else:
370 # TODO: adjust ending line when it's at the start?
371 uncovered_ranges.add((start_line + 1, end_line + 1))
372
373 if uncovered_ranges:
374 ranges = ', '.join(f'{s}-{e}' if s != e else f'{s}' for s, e in sorted(uncovered_ranges))
375 print(f'{source.path:50} {100 * covered / total:>6.1f}% ({covered} / {total}) ~ {ranges}')
376 any_output = True
377
378 n_files += 1
379
380 if not n_files:
381 print('No files considered for coverage')
382 elif not any_output:
383 print(f'Coverage is complete for {n_files} file{'s' if n_files != 1 else ''}')
384
385
386 CoverageReport = Callable[[BrowserCoverageResult], None]
387
388
389 @pytest.fixture
390 def coverage_report(
391 pytestconfig: pytest.Config,
392 request: pytest.FixtureRequest,
393 tmp_path_factory: pytest.TempPathFactory,
394 ) -> Iterable[CoverageReport]:
395 def with_hash(filename: str) -> FileDescription:
396 # capture the hash value at the time of the call. this helps to ensure
397 # that we don't mix coverage data from different file versions. ideally
398 # we would capture it as we serve it to the browser, but this is good
399 # enough for the time being.
400 path = pytestconfig.rootpath / filename
401 return {
402 'filename': filename,
403 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()
404 }
405
406 output: list[CoverageFileEntry] = []
407
408 def append_to_report(coverage_data: BrowserCoverageResult) -> None:
409 for file in coverage_data['result']:
410 filename = URL(file['url']).path[1:] # pathname relative to root
411
412 if not filename.endswith('.js'):
413 continue
414
415 try:
416 output.append({
417 'bundle': with_hash(filename),
418 'map': with_hash(f'{filename}.map'),
419 'functions': file['functions']
420 })
421 except FileNotFoundError:
422 continue
423
424 yield append_to_report
425
426 if output:
427 basetempdir = tmp_path_factory.getbasetemp()
428 if os.getenv('PYTEST_XDIST_WORKER'):
429 # each xdist process gets a tmpdir subdir, but we want the parent
430 basetempdir = basetempdir.parent
431
432 assert isinstance(request.node, pytest.Item) # fixture is not session-scoped
433 item = request.node
434
435 name = item.name.replace('/', ':') + '.js-coverage.json'
436 coverage_file = basetempdir / 'js-coverage' / name
437 coverage_file.parent.mkdir(exist_ok=True)
438 coverage_file.write_text(json.dumps({
439 'coverage': output
440 }, indent=2))
441
442
443 def pytest_terminal_summary(config: pytest.Config, terminalreporter: TerminalReporter) -> None:
444 show_cov: bool = config.getoption('jscov')
445 matches: Sequence[str] = config.getoption('jscovfiles')
446 if not show_cov and not matches:
447 return
448
449 # Using the tmpdir gets us:
450 # - automatic cleanup
451 # - effortless communication with xdist workers
452 # - ability to use the data out-of-process
453 # - no need to have an entire plugin to pass data around
454 # So: this is definitely evil, but the alternative is *way* too complicated...
455 basetempdir = config._tmp_path_factory.getbasetemp() # type: ignore[attr-defined]
456 assert isinstance(basetempdir, Path)
457
458 coverage_dir = basetempdir / 'js-coverage'
459 coverage_files = tuple(coverage_dir.glob('*.js-coverage.json'))
460
461 terminalreporter.ensure_newline()
462 terminalreporter.section('JavaScript coverage summary', sep='=', purple=True, bold=True)
463 report_coverage(coverage_files, matches)
464
465
466 def pytest_addoption(parser: pytest.Parser) -> None:
467 parser.addoption('--js-cov', dest='jscov', action='store_true',
468 help="Show JS coverage summary")
469 parser.addoption('--js-cov-files', dest='jscovfiles', action='append',
470 help="Show detailed coverage for given JS file glob")
471
472
473 def main() -> None:
474 parser = argparse.ArgumentParser(description='Coverage reporting tool')
475 parser.add_argument('-d', '--debug', action='store_true', help="Print debugging output")
476 parser.add_argument('-m', '--match', action='append', help="Filename glob pattern for source files")
477 parser.add_argument('files', type=Path, nargs='+')
478 args = parser.parse_args()
479
480 report_coverage(args.files, args.match)
481
482
483 if __name__ == '__main__':
484 main()