Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions python/tryke/coverage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Code coverage logic

https://docs.python.org/3/library/sys.monitoring.html
"""

import sys
from types import CodeType
from typing import Final

mon = sys.monitoring
TOOL_ID = mon.COVERAGE_ID
TOOL_NAME: Final = "tryke"

type HitLocation = tuple[
# Path name
str,
# Line number
int,
]


class Coverage:
def __init__(self) -> None:
self._hits: set[HitLocation] = set()

def register(self) -> None:
existing_tool = mon.get_tool(TOOL_ID)
if existing_tool:
if existing_tool != TOOL_NAME:
msg = f"Unexpected existing tool: {existing_tool}"
raise ValueError(msg)
else:
mon.use_tool_id(TOOL_ID, TOOL_NAME)
mon.register_callback(TOOL_ID, mon.events.LINE, self._line_callback)
mon.set_events(TOOL_ID, mon.events.LINE)

def _line_callback(self, code: CodeType, line_number: int) -> object:
self._hits.add((code.co_filename, line_number))
return mon.DISABLE
10 changes: 7 additions & 3 deletions python/tryke/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
from typing import TYPE_CHECKING, Literal, NotRequired, TypedDict

import tryke_guard
from tryke.coverage import Coverage
from tryke.expect import (
CaseArgs,
CasesMarked,
Expand Down Expand Up @@ -104,9 +105,6 @@
_log = logging.getLogger("tryke.worker")


# -- Wire-format TypedDicts (mirror crates/tryke_runner/src/protocol.rs) ------


class _AssertionWire(TypedDict):
expression: str
expected: str
Expand Down Expand Up @@ -363,8 +361,14 @@ def __init__(
self._hook_metadata: dict[str, list[object]] = {}
# Hook executors cached per module.
self._executors: dict[str, HookExecutor] = {}
self._coverage: Coverage | None = None

def run(self) -> None:
# TODO(thejchap): driven by config # noqa: FIX002, TD003
if True:
self._coverage = Coverage()
self._coverage.register()

for raw in self._input:
line = raw.strip()
if not line:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_coverage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from tryke import expect, test


@test(name="coverage")
def test_coverage() -> None:
expect("a", "a is truthy").to_be_truthy()
Loading