| 1 |
"""A minimal hook for gathering line coverage of the standard library. |
| 2 |
|
| 3 |
Designed to be used with -Xpresite= which means: |
| 4 |
* it installs itself on import |
| 5 |
* it's not imported as `__main__` so can't use the ifmain idiom |
| 6 |
* it can't import anything besides `sys` to avoid tainting gathered coverage |
| 7 |
* filenames are not normalized |
| 8 |
|
| 9 |
To get gathered coverage back, look for 'test.cov' in `sys.modules` |
| 10 |
instead of importing directly. That way you can determine if the module |
| 11 |
was already in use. |
| 12 |
|
| 13 |
If you need to disable the hook, call the `disable()` function. |
| 14 |
""" |
| 15 |
|
| 16 |
import sys |
| 17 |
|
| 18 |
mon = sys.monitoring |
| 19 |
|
| 20 |
FileName = str |
| 21 |
LineNo = int |
| 22 |
Location = tuple[FileName, LineNo] |
| 23 |
|
| 24 |
coverage: set[Location] = set() |
| 25 |
|
| 26 |
|
| 27 |
# `types` and `typing` aren't imported to avoid invalid coverage |
| 28 |
def add_line( |
| 29 |
code: "types.CodeType", |
| 30 |
lineno: int, |
| 31 |
) -> "typing.Literal[sys.monitoring.DISABLE]": |
| 32 |
coverage.add((code.co_filename, lineno)) |
| 33 |
return mon.DISABLE |
| 34 |
|
| 35 |
|
| 36 |
def enable(): |
| 37 |
mon.use_tool_id(mon.COVERAGE_ID, "regrtest coverage") |
| 38 |
mon.register_callback(mon.COVERAGE_ID, mon.events.LINE, add_line) |
| 39 |
mon.set_events(mon.COVERAGE_ID, mon.events.LINE) |
| 40 |
|
| 41 |
|
| 42 |
def disable(): |
| 43 |
mon.set_events(mon.COVERAGE_ID, 0) |
| 44 |
mon.register_callback(mon.COVERAGE_ID, mon.events.LINE, None) |
| 45 |
mon.free_tool_id(mon.COVERAGE_ID) |
| 46 |
|
| 47 |
|
| 48 |
enable() |