hy-coverage 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: hy-coverage
3
+ Version: 0.1.0
4
+ Summary: coverage.py plugin for Hy source files
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: coverage>=7.6
7
+ Requires-Dist: hy>=1.3
8
+ Provides-Extra: test
9
+ Requires-Dist: pytest>=8; extra == "test"
@@ -0,0 +1,26 @@
1
+ # hy-coverage
2
+
3
+ A standalone coverage.py plugin for Hy source files. It keeps coverage results
4
+ independent of Python bytecode cache state, reports branch coverage, and leaves
5
+ compile-only macro lines out of the denominator.
6
+
7
+ ## Install
8
+
9
+ ```console
10
+ pip install git+https://github.com/norci/hy-coverage.git
11
+ ```
12
+
13
+ This project is not published to PyPI yet. Install it from GitHub until a release is available.
14
+
15
+ ## Configure
16
+
17
+ Add the plugin to your `.coveragerc`:
18
+
19
+ ```ini
20
+ [run]
21
+ plugins = hy_coverage
22
+ source = .
23
+ ```
24
+
25
+ The package works with an unmodified Hy installation. It installs its
26
+ compile-time tracking hooks when coverage.py loads the plugin.
@@ -0,0 +1,5 @@
1
+ """Standalone coverage.py plugin for Hy source files."""
2
+
3
+ from .plugin import coverage_init
4
+
5
+ __all__ = ["coverage_init"]
@@ -0,0 +1,54 @@
1
+ """Compile-time tracking hooks for Hy coverage."""
2
+
3
+ from contextlib import contextmanager
4
+ from contextvars import ContextVar
5
+ from functools import wraps
6
+
7
+ _expansion_active = ContextVar("hy_coverage_expansion_active", default=False)
8
+ _hooks_installed = False
9
+
10
+
11
+ def expansion_active():
12
+ """Return whether the current context is executing a macro expansion."""
13
+ return _expansion_active.get()
14
+
15
+
16
+ @contextmanager
17
+ def expansion_context():
18
+ token = _expansion_active.set(True)
19
+ try:
20
+ yield
21
+ finally:
22
+ _expansion_active.reset(token)
23
+
24
+
25
+ def _wrap(function):
26
+ if getattr(function, "_hy_coverage_wrapped", False):
27
+ return function
28
+
29
+ @wraps(function)
30
+ def wrapped(*args, **kwargs):
31
+ with expansion_context():
32
+ return function(*args, **kwargs)
33
+
34
+ wrapped._hy_coverage_wrapped = True
35
+ return wrapped
36
+
37
+
38
+ def install_hooks():
39
+ """Wrap Hy expansion entry points without changing Hy itself."""
40
+ global _hooks_installed
41
+ if _hooks_installed:
42
+ return
43
+
44
+ import hy.compiler
45
+ import hy.macros
46
+ import hy.reader.hy_reader as hy_reader
47
+
48
+ hy.macros.macroexpand = _wrap(hy.macros.macroexpand)
49
+ hy.compiler.macroexpand = _wrap(hy.compiler.macroexpand)
50
+
51
+ hy_reader.HyReader.tag_dispatch = _wrap(hy_reader.HyReader.tag_dispatch)
52
+ hy_reader.HyReader.DEFAULT_TABLE["#"] = hy_reader.HyReader.tag_dispatch
53
+
54
+ _hooks_installed = True
@@ -0,0 +1,235 @@
1
+ """coverage.py plugin for Hy source files."""
2
+
3
+ import collections
4
+ import dis
5
+ import os
6
+ import sys
7
+ import types
8
+ import uuid
9
+
10
+ from coverage import CoverageData
11
+ from coverage.plugin import CoveragePlugin, FileReporter, FileTracer
12
+
13
+ from hy import read_many
14
+ from hy.compiler import hy_compile
15
+
16
+ from .context import expansion_active, install_hooks
17
+
18
+
19
+ COMPILE_TIME_CONTEXT = "hy-compile-time"
20
+
21
+ _UNCONDITIONAL_JUMPS = frozenset(
22
+ {
23
+ "JUMP_ABSOLUTE",
24
+ "JUMP_BACKWARD",
25
+ "JUMP_BACKWARD_NO_INTERRUPT",
26
+ "JUMP_FORWARD",
27
+ }
28
+ )
29
+ _RETURN_OPS = frozenset({"RAISE_VARARGS", "RERAISE", "RETURN_CONST", "RETURN_VALUE"})
30
+ _SKIPPED_OPS = frozenset({"RESUME", "RETURN_GENERATOR"})
31
+
32
+
33
+ class HyFileTracer(FileTracer):
34
+ def __init__(self, filename):
35
+ self.filename = filename
36
+
37
+ def source_filename(self):
38
+ return self.filename
39
+
40
+
41
+ class HyFileReporter(FileReporter):
42
+ def __init__(self, filename, data_file):
43
+ super().__init__(filename)
44
+ self.data_file = data_file
45
+ self._measurement = None
46
+
47
+ def _measure(self):
48
+ if self._measurement is None:
49
+ source = self.source()
50
+ executable_lines, compile_time_lines, arcs = _forced_measurement(
51
+ self.filename, source
52
+ )
53
+ runtime_lines = _runtime_lines(self.filename, self.data_file)
54
+ lines = executable_lines - (compile_time_lines - runtime_lines)
55
+ arcs = {
56
+ arc
57
+ for arc in arcs
58
+ if (arc[0] == -1 or arc[0] in lines)
59
+ and (arc[1] == -1 or arc[1] in lines)
60
+ }
61
+ self._measurement = lines, arcs
62
+ return self._measurement
63
+
64
+ def lines(self):
65
+ return self._measure()[0]
66
+
67
+ def arcs(self):
68
+ return self._measure()[1]
69
+
70
+ def exit_counts(self):
71
+ counts = collections.Counter()
72
+ for start, _ in self.arcs():
73
+ if start > 0:
74
+ counts[start] += 1
75
+ return dict(counts)
76
+
77
+
78
+ class HyCoveragePlugin(CoveragePlugin):
79
+ def __init__(self):
80
+ self.data_file = ".coverage"
81
+
82
+ def configure(self, config):
83
+ data_file = config.get_option("run:data_file")
84
+ if data_file:
85
+ self.data_file = os.path.abspath(data_file)
86
+
87
+ def file_tracer(self, filename):
88
+ if filename.endswith(".hy"):
89
+ return HyFileTracer(filename)
90
+ return None
91
+
92
+ def file_reporter(self, filename):
93
+ return HyFileReporter(filename, self.data_file)
94
+
95
+ def dynamic_context(self, frame):
96
+ if expansion_active():
97
+ return COMPILE_TIME_CONTEXT
98
+ return None
99
+
100
+
101
+ def coverage_init(reg, options):
102
+ install_hooks()
103
+ plugin = HyCoveragePlugin()
104
+ reg.add_configurer(plugin)
105
+ reg.add_file_tracer(plugin)
106
+ reg.add_dynamic_context(plugin)
107
+
108
+
109
+ def _runtime_lines(filename, data_file):
110
+ data = CoverageData(data_file, read_only=True)
111
+ data.read()
112
+ contexts = data.contexts_by_lineno(filename)
113
+ return {
114
+ line
115
+ for line, line_contexts in contexts.items()
116
+ if any(context != COMPILE_TIME_CONTEXT for context in line_contexts)
117
+ }
118
+
119
+
120
+ def _forced_measurement(filename, source):
121
+ compile_time_lines = set()
122
+ forced_lines = set()
123
+ module_name = "_hy_coverage_" + uuid.uuid4().hex
124
+ module = types.ModuleType(module_name)
125
+ module.__file__ = filename
126
+
127
+ def trace(frame, event, arg):
128
+ if event == "line" and frame.f_code.co_filename == filename:
129
+ forced_lines.add(frame.f_lineno)
130
+ if expansion_active():
131
+ compile_time_lines.add(frame.f_lineno)
132
+ return trace
133
+
134
+ previous_module = sys.modules.get(module_name)
135
+ sys.modules[module_name] = module
136
+ previous_trace = sys.gettrace()
137
+ sys.settrace(trace)
138
+ try:
139
+ try:
140
+ tree = read_many(source, filename=filename)
141
+ ast_tree = hy_compile(
142
+ tree, module, filename=filename, source=source, import_stdlib=True
143
+ )
144
+ finally:
145
+ sys.settrace(previous_trace)
146
+ code = compile(ast_tree, filename, "exec")
147
+ finally:
148
+ if previous_module is None:
149
+ sys.modules.pop(module_name, None)
150
+ else:
151
+ sys.modules[module_name] = previous_module
152
+
153
+ line_count = len(source.splitlines())
154
+ forced_lines = {line for line in forced_lines if 0 < line <= line_count}
155
+ compile_time_lines &= forced_lines
156
+ for code_object in _walk_code(code):
157
+ forced_lines.update(
158
+ line
159
+ for _, line in dis.findlinestarts(code_object)
160
+ if line is not None and 0 < line <= line_count
161
+ )
162
+ arcs = set()
163
+ for code_object in _walk_code(code):
164
+ arcs.update(_code_arcs(code_object, forced_lines))
165
+ return forced_lines, compile_time_lines, arcs
166
+
167
+
168
+ def _code_arcs(code, lines):
169
+ line_starts = sorted(
170
+ (start, line) for start, line in dis.findlinestarts(code) if line is not None
171
+ )
172
+ instructions = list(dis.get_instructions(code))
173
+
174
+ def line_at(offset):
175
+ line = None
176
+ for start, candidate in line_starts:
177
+ if start > offset:
178
+ break
179
+ if candidate is not None:
180
+ line = candidate
181
+ return line
182
+
183
+ arcs = set()
184
+ first_line = None
185
+ for instruction in instructions:
186
+ if instruction.opname in _SKIPPED_OPS:
187
+ continue
188
+ line = line_at(instruction.offset)
189
+ if line is not None and line > 0 and line in lines:
190
+ first_line = line
191
+ break
192
+ if first_line is not None:
193
+ arcs.add((-1, first_line))
194
+
195
+ for index, instruction in enumerate(instructions):
196
+ if instruction.opname in _SKIPPED_OPS:
197
+ continue
198
+ current = line_at(instruction.offset)
199
+ if current is None or current <= 0 or current not in lines:
200
+ continue
201
+ next_instruction = instructions[index + 1] if index + 1 < len(instructions) else None
202
+ next_line = line_at(next_instruction.offset) if next_instruction else None
203
+ if instruction.opname in _RETURN_OPS:
204
+ arcs.add((current, -1))
205
+ continue
206
+ if instruction.opcode in dis.hasjabs or instruction.opcode in dis.hasjrel:
207
+ target = line_at(instruction.argval)
208
+ if target is not None and target > 0 and target in lines and target != current:
209
+ arcs.add((current, target))
210
+ if (
211
+ instruction.opname not in _UNCONDITIONAL_JUMPS
212
+ and next_instruction is not None
213
+ and next_line is not None
214
+ and next_line > 0
215
+ and next_line in lines
216
+ and next_line != current
217
+ ):
218
+ arcs.add((current, next_line))
219
+ continue
220
+ if (
221
+ next_instruction is not None
222
+ and next_line is not None
223
+ and next_line > 0
224
+ and next_line in lines
225
+ and next_line != current
226
+ ):
227
+ arcs.add((current, next_line))
228
+ return arcs
229
+
230
+
231
+ def _walk_code(code):
232
+ yield code
233
+ for constant in code.co_consts:
234
+ if isinstance(constant, types.CodeType):
235
+ yield from _walk_code(constant)
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: hy-coverage
3
+ Version: 0.1.0
4
+ Summary: coverage.py plugin for Hy source files
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: coverage>=7.6
7
+ Requires-Dist: hy>=1.3
8
+ Provides-Extra: test
9
+ Requires-Dist: pytest>=8; extra == "test"
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ hy_coverage/__init__.py
4
+ hy_coverage/context.py
5
+ hy_coverage/plugin.py
6
+ hy_coverage.egg-info/PKG-INFO
7
+ hy_coverage.egg-info/SOURCES.txt
8
+ hy_coverage.egg-info/dependency_links.txt
9
+ hy_coverage.egg-info/requires.txt
10
+ hy_coverage.egg-info/top_level.txt
11
+ tests/test_context.py
12
+ tests/test_coverage.py
@@ -0,0 +1,5 @@
1
+ coverage>=7.6
2
+ hy>=1.3
3
+
4
+ [test]
5
+ pytest>=8
@@ -0,0 +1 @@
1
+ hy_coverage
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hy-coverage"
7
+ version = "0.1.0"
8
+ description = "coverage.py plugin for Hy source files"
9
+ requires-python = ">=3.10"
10
+ dependencies = ["coverage>=7.6", "hy>=1.3"]
11
+
12
+ [project.optional-dependencies]
13
+ test = ["pytest>=8"]
14
+
15
+ [tool.setuptools]
16
+ packages = ["hy_coverage"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,64 @@
1
+ import hy.macros
2
+ from hy.compiler import HyASTCompiler
3
+ from hy.macros import macro
4
+ from hy.models import Integer
5
+ from hy.reader import read
6
+ from hy.reader.hy_reader import HyReader
7
+
8
+ from hy_coverage.context import expansion_active, install_hooks
9
+
10
+
11
+ seen = []
12
+
13
+
14
+ @macro("coverage-expansion-probe")
15
+ def expansion_probe():
16
+ seen.append(("macro", expansion_active()))
17
+ helper()
18
+ return Integer(1)
19
+
20
+
21
+ def helper():
22
+ seen.append(("helper", expansion_active()))
23
+
24
+
25
+ @macro("coverage-expansion-inner")
26
+ def expansion_inner():
27
+ seen.append(("inner", expansion_active()))
28
+ return Integer(2)
29
+
30
+
31
+ @macro("coverage-expansion-outer")
32
+ def expansion_outer():
33
+ seen.append(("outer", expansion_active()))
34
+ return hy.macros.macroexpand(read("(coverage-expansion-inner)"), __name__, HyASTCompiler(__name__))
35
+
36
+ def test_install_hooks_marks_macro_and_helper():
37
+ install_hooks()
38
+ seen.clear()
39
+ result = hy.macros.macroexpand(read("(coverage-expansion-probe)"), __name__, HyASTCompiler(__name__))
40
+ assert seen == [("macro", True), ("helper", True)]
41
+ assert expansion_active() is False
42
+
43
+
44
+ def test_nested_macro_expansion_restores_context():
45
+ install_hooks()
46
+ seen.clear()
47
+ result = hy.macros.macroexpand(read("(coverage-expansion-outer)"), __name__, HyASTCompiler(__name__))
48
+ assert seen == [("outer", True), ("inner", True)]
49
+ assert expansion_active() is False
50
+
51
+
52
+ def test_reader_macro_is_marked():
53
+ install_hooks()
54
+ seen.clear()
55
+
56
+ def reader_probe(reader, key):
57
+ seen.append(("reader", expansion_active()))
58
+ return Integer(3)
59
+
60
+ reader = HyReader()
61
+ reader.reader_macros["coverage-probe"] = reader_probe
62
+ assert read("#coverage-probe", reader=reader) == Integer(3)
63
+ assert seen == [("reader", True)]
64
+ assert expansion_active() is False
@@ -0,0 +1,220 @@
1
+ import json
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ pytest.importorskip("coverage")
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+
14
+
15
+ def _line(source, marker):
16
+ for number, text in enumerate(source.splitlines(), 1):
17
+ if marker in text:
18
+ return number
19
+ raise AssertionError(f"marker not found: {marker}")
20
+
21
+
22
+ def _python_path(tmp_path):
23
+ paths = [str(tmp_path), str(ROOT)]
24
+ hy_root = os.environ.get("HY_ROOT")
25
+ if hy_root:
26
+ paths.insert(0, hy_root)
27
+ return os.pathsep.join(paths)
28
+
29
+
30
+ def _write_project(tmp_path):
31
+ source = """(eval-and-compile
32
+ (defn compile-only [value]
33
+ (+ value 1) ; marker-compile-only
34
+ )
35
+ (defn shared [value]
36
+ (+ value 2) ; marker-shared-helper
37
+ ))
38
+
39
+ (defmacro compile-macro []
40
+ (compile-only 1) ; marker-compile-macro-body
41
+ None)
42
+
43
+ (defmacro shared-macro []
44
+ (shared 1) ; marker-shared-macro-body
45
+ None)
46
+
47
+ (defn runtime []
48
+ (shared 2) ; marker-runtime-shared-call
49
+ (shared-macro))
50
+
51
+ (compile-macro)
52
+ """
53
+ (tmp_path / "sample.hy").write_text(source, encoding="utf-8")
54
+ (tmp_path / "run.py").write_text(
55
+ "import hy\nimport sample\nsample.runtime()\n", encoding="utf-8"
56
+ )
57
+ (tmp_path / ".coveragerc").write_text(
58
+ "[run]\n"
59
+ "core = ctrace\n"
60
+ "plugins = hy_coverage\n"
61
+ "source = .\n",
62
+ encoding="utf-8",
63
+ )
64
+ return {
65
+ "compile_only": _line(source, "marker-compile-only"),
66
+ "compile_macro": _line(source, "marker-compile-macro-body"),
67
+ "shared_macro": _line(source, "marker-shared-macro-body"),
68
+ "shared_helper": _line(source, "marker-shared-helper"),
69
+ "runtime_shared": _line(source, "marker-runtime-shared-call"),
70
+ }
71
+
72
+
73
+ def _write_branch_project(tmp_path):
74
+ source = """(defn choose [x]
75
+ (if x
76
+ (+ x 1) ; marker-true
77
+ (- x 1))) ; marker-false
78
+
79
+ (print (choose True))
80
+ """
81
+ (tmp_path / "sample.hy").write_text(source, encoding="utf-8")
82
+ (tmp_path / "run.py").write_text(
83
+ "import hy\nimport sample\n", encoding="utf-8"
84
+ )
85
+ (tmp_path / ".coveragerc").write_text(
86
+ "[run]\n"
87
+ "branch = true\n"
88
+ "core = ctrace\n"
89
+ "plugins = hy_coverage\n"
90
+ "source = .\n",
91
+ encoding="utf-8",
92
+ )
93
+ return {
94
+ "if": _line(source, "(if x"),
95
+ "true": _line(source, "marker-true"),
96
+ "false": _line(source, "marker-false"),
97
+ }
98
+
99
+
100
+ def _run_coverage(tmp_path, label, clear_cache):
101
+ if clear_cache:
102
+ shutil.rmtree(tmp_path / "__pycache__", ignore_errors=True)
103
+
104
+ env = os.environ.copy()
105
+ env["PYTHONPATH"] = _python_path(tmp_path)
106
+ env["COVERAGE_FILE"] = str(tmp_path / f".coverage-{label}")
107
+ rcfile = str(tmp_path / ".coveragerc")
108
+ report_path = tmp_path / f"report-{label}.json"
109
+
110
+ run = subprocess.run(
111
+ [sys.executable, "-m", "coverage", "run", f"--rcfile={rcfile}", "run.py"],
112
+ cwd=tmp_path,
113
+ env=env,
114
+ capture_output=True,
115
+ text=True,
116
+ )
117
+ assert run.returncode == 0, run.stdout + run.stderr
118
+
119
+ report = subprocess.run(
120
+ [
121
+ sys.executable,
122
+ "-m",
123
+ "coverage",
124
+ "json",
125
+ f"--rcfile={rcfile}",
126
+ "-o",
127
+ str(report_path),
128
+ ],
129
+ cwd=tmp_path,
130
+ env=env,
131
+ capture_output=True,
132
+ text=True,
133
+ )
134
+ assert report.returncode == 0, report.stdout + report.stderr
135
+
136
+ data = json.loads(report_path.read_text(encoding="utf-8"))
137
+ filename = next(name for name in data["files"] if name.endswith("sample.hy"))
138
+ return data["files"][filename]
139
+
140
+
141
+ def _denominator(report):
142
+ return set(report["executed_lines"]) | set(report["missing_lines"])
143
+
144
+
145
+ def _run_plain(tmp_path):
146
+ env = os.environ.copy()
147
+ env["PYTHONPATH"] = _python_path(tmp_path)
148
+ run = subprocess.run(
149
+ [sys.executable, "run.py"],
150
+ cwd=tmp_path,
151
+ env=env,
152
+ capture_output=True,
153
+ text=True,
154
+ )
155
+ assert run.returncode == 0, run.stdout + run.stderr
156
+ assert list((tmp_path / "__pycache__").glob("sample*.pyc"))
157
+
158
+
159
+ def test_hy_coverage_is_independent_of_pycache(tmp_path):
160
+ markers = _write_project(tmp_path)
161
+ cold = _run_coverage(tmp_path, "cold", clear_cache=True)
162
+ hot = _run_coverage(tmp_path, "hot", clear_cache=False)
163
+
164
+ for report in (cold, hot):
165
+ assert report["summary"]["percent_covered"] == 100
166
+ denominator = _denominator(report)
167
+ assert markers["compile_only"] not in denominator
168
+ assert markers["compile_macro"] not in denominator
169
+ assert markers["shared_macro"] not in denominator
170
+ assert markers["shared_helper"] in denominator
171
+ assert markers["runtime_shared"] in denominator
172
+
173
+ assert _denominator(cold) == _denominator(hot)
174
+
175
+
176
+ def test_hy_branch_coverage_reports_unexecuted_branch(tmp_path):
177
+ markers = _write_branch_project(tmp_path)
178
+ report = _run_coverage(tmp_path, "branch", clear_cache=True)
179
+
180
+ assert report["summary"]["num_branches"] >= 2
181
+ assert [markers["if"], markers["false"]] in report["missing_branches"]
182
+
183
+
184
+ def test_reporter_ignores_bytecode_lines_without_line_numbers(tmp_path):
185
+ source = """(defclass C []
186
+ (defn __init__ [self] (setv self.x 1)) ; marker-init
187
+ (defn get [self] self.x)) ; marker-get
188
+ """
189
+ (tmp_path / "sample.hy").write_text(source, encoding="utf-8")
190
+ (tmp_path / "run.py").write_text(
191
+ "import hy\nimport sample\nsample.C()\n", encoding="utf-8"
192
+ )
193
+ (tmp_path / ".coveragerc").write_text(
194
+ "[run]\n"
195
+ "core = ctrace\n"
196
+ "plugins = hy_coverage\n"
197
+ "source = .\n",
198
+ encoding="utf-8",
199
+ )
200
+ report = _run_coverage(tmp_path, "class", clear_cache=True)
201
+ expected = {
202
+ _line(source, "(defclass"),
203
+ _line(source, "marker-init"),
204
+ _line(source, "marker-get"),
205
+ }
206
+ assert _denominator(report) == expected
207
+
208
+
209
+ def test_hy_coverage_with_cache_created_before_plugin(tmp_path):
210
+ markers = _write_project(tmp_path)
211
+ _run_plain(tmp_path)
212
+ report = _run_coverage(tmp_path, "stale", clear_cache=False)
213
+
214
+ assert report["summary"]["percent_covered"] == 100
215
+ denominator = _denominator(report)
216
+ assert markers["compile_only"] not in denominator
217
+ assert markers["compile_macro"] not in denominator
218
+ assert markers["shared_macro"] not in denominator
219
+ assert markers["shared_helper"] in denominator
220
+ assert markers["runtime_shared"] in denominator