-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_coverage_tracker.py
More file actions
437 lines (365 loc) · 15.1 KB
/
_coverage_tracker.py
File metadata and controls
437 lines (365 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# tests/_coverage_tracker.py
"""
Coverage tracking utility for URST test suite.
Provides simple coverage analysis for MicroPython compatibility.
"""
import ast
import os
import time
from typing import Any, Dict, Set
class SimpleCoverageTracker:
"""
Simple coverage tracker that works in both CPython and MicroPython environments.
Tracks function and method calls during test execution.
"""
def __init__(self, source_dir: str):
"""
Initialize coverage tracker.
Args:
source_dir: Directory containing source code to track
"""
self.source_dir = source_dir
self.covered_lines: Dict[str, Set[int]] = {}
self.total_lines: Dict[str, Set[int]] = {}
self.function_calls: Dict[str, Set[str]] = {}
self.total_functions: Dict[str, Set[str]] = {}
self.enabled = False
def analyze_source_files(self) -> None:
"""Analyze source files to identify trackable lines and functions."""
for root, dirs, files in os.walk(self.source_dir):
# Skip test directories and __pycache__
dirs[:] = [
d for d in dirs if not d.startswith("__pycache__") and d != "tests"
]
for file in files:
if file.endswith(".py") and not file.startswith("_"):
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, self.source_dir)
self._analyze_file(file_path, rel_path)
def _analyze_file(self, file_path: str, rel_path: str) -> None:
"""
Analyze a single Python file for trackable elements.
Args:
file_path: Absolute path to the file
rel_path: Relative path for reporting
"""
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Parse AST to find functions and executable lines
tree = ast.parse(content)
executable_lines = set()
functions = set()
for node in ast.walk(tree):
if hasattr(node, "lineno"):
# Track lines with executable code
if isinstance(
node,
(
ast.FunctionDef,
ast.ClassDef,
ast.Assign,
ast.AugAssign,
ast.Return,
ast.If,
ast.For,
ast.While,
ast.With,
ast.Try,
ast.Raise,
ast.Assert,
ast.Import,
ast.ImportFrom,
ast.Expr,
),
):
executable_lines.add(node.lineno)
# Track function definitions
if isinstance(node, ast.FunctionDef):
functions.add(node.name)
self.total_lines[rel_path] = executable_lines
self.total_functions[rel_path] = functions
self.covered_lines[rel_path] = set()
self.function_calls[rel_path] = set()
except Exception as e:
print(f"Warning: Could not analyze {file_path}: {e}")
def start_tracking(self) -> None:
"""Start coverage tracking."""
self.enabled = True
# In a full implementation, this would set up tracing
# For simplicity, we'll rely on manual reporting
def stop_tracking(self) -> None:
"""Stop coverage tracking."""
self.enabled = False
def record_line_execution(self, file_path: str, line_number: int) -> None:
"""
Record that a line was executed.
Args:
file_path: Path to the file
line_number: Line number that was executed
"""
if self.enabled and file_path in self.covered_lines:
self.covered_lines[file_path].add(line_number)
def record_function_call(self, file_path: str, function_name: str) -> None:
"""
Record that a function was called.
Args:
file_path: Path to the file containing the function
function_name: Name of the function that was called
"""
if self.enabled and file_path in self.function_calls:
self.function_calls[file_path].add(function_name)
def get_coverage_report(self) -> Dict[str, Any]:
"""
Generate coverage report.
Returns:
Dictionary containing coverage statistics
"""
report = {
"files": {},
"summary": {
"total_files": len(self.total_lines),
"total_lines": 0,
"covered_lines": 0,
"total_functions": 0,
"covered_functions": 0,
"line_coverage": 0.0,
"function_coverage": 0.0,
},
}
total_lines = 0
covered_lines = 0
total_functions = 0
covered_functions = 0
for file_path in self.total_lines:
file_total_lines = len(self.total_lines[file_path])
file_covered_lines = len(self.covered_lines[file_path])
file_total_functions = len(self.total_functions[file_path])
file_covered_functions = len(self.function_calls[file_path])
file_line_coverage = (
(file_covered_lines / file_total_lines * 100)
if file_total_lines > 0
else 0
)
file_function_coverage = (
(file_covered_functions / file_total_functions * 100)
if file_total_functions > 0
else 0
)
report["files"][file_path] = {
"total_lines": file_total_lines,
"covered_lines": file_covered_lines,
"total_functions": file_total_functions,
"covered_functions": file_covered_functions,
"line_coverage": file_line_coverage,
"function_coverage": file_function_coverage,
"uncovered_lines": list(
self.total_lines[file_path] - self.covered_lines[file_path]
),
"uncovered_functions": list(
self.total_functions[file_path] - self.function_calls[file_path]
),
}
total_lines += file_total_lines
covered_lines += file_covered_lines
total_functions += file_total_functions
covered_functions += file_covered_functions
# Calculate overall coverage
report["summary"]["total_lines"] = total_lines
report["summary"]["covered_lines"] = covered_lines
report["summary"]["total_functions"] = total_functions
report["summary"]["covered_functions"] = covered_functions
report["summary"]["line_coverage"] = (
(covered_lines / total_lines * 100) if total_lines > 0 else 0
)
report["summary"]["function_coverage"] = (
(covered_functions / total_functions * 100) if total_functions > 0 else 0
)
return report
def print_coverage_report(self, detailed: bool = False) -> None:
"""
Print formatted coverage report.
Args:
detailed: Include per-file details
"""
report = self.get_coverage_report()
summary = report["summary"]
print("\n" + "=" * 80)
print("COVERAGE REPORT")
print("=" * 80)
print(f"Files analyzed: {summary['total_files']}")
print(
f"Line coverage: {summary['covered_lines']}/{summary['total_lines']} ({summary['line_coverage']:.1f}%)"
)
print(
f"Function coverage: {summary['covered_functions']}/{summary['total_functions']} ({summary['function_coverage']:.1f}%)"
)
if detailed:
print("\nPer-file coverage:")
print("-" * 80)
for file_path, file_data in report["files"].items():
print(f"\n{file_path}:")
print(
f" Lines: {file_data['covered_lines']}/{file_data['total_lines']} ({file_data['line_coverage']:.1f}%)"
)
print(
f" Functions: {file_data['covered_functions']}/{file_data['total_functions']} ({file_data['function_coverage']:.1f}%)"
)
if file_data["uncovered_functions"]:
print(
f" Uncovered functions: {', '.join(file_data['uncovered_functions'])}"
)
print("=" * 80)
def save_coverage_report(self, output_file: str) -> None:
"""
Save coverage report to file.
Args:
output_file: Path to output file
"""
report = self.get_coverage_report()
try:
with open(output_file, "w", encoding="utf-8") as f:
f.write("URST Test Coverage Report\n")
f.write("=" * 50 + "\n")
f.write(f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
summary = report["summary"]
f.write("SUMMARY\n")
f.write("-" * 20 + "\n")
f.write(f"Files analyzed: {summary['total_files']}\n")
f.write(
f"Line coverage: {summary['covered_lines']}/{summary['total_lines']} ({summary['line_coverage']:.1f}%)\n"
)
f.write(
f"Function coverage: {summary['covered_functions']}/{summary['total_functions']} ({summary['function_coverage']:.1f}%)\n\n"
)
f.write("DETAILED RESULTS\n")
f.write("-" * 20 + "\n")
for file_path, file_data in report["files"].items():
f.write(f"\n{file_path}:\n")
f.write(
f" Lines: {file_data['covered_lines']}/{file_data['total_lines']} ({file_data['line_coverage']:.1f}%)\n"
)
f.write(
f" Functions: {file_data['covered_functions']}/{file_data['total_functions']} ({file_data['function_coverage']:.1f}%)\n"
)
if file_data["uncovered_functions"]:
f.write(
f" Uncovered functions: {', '.join(file_data['uncovered_functions'])}\n"
)
if file_data["uncovered_lines"]:
f.write(
f" Uncovered lines: {', '.join(map(str, sorted(file_data['uncovered_lines'])))}\n"
)
print(f"Coverage report saved to: {output_file}")
except Exception as e:
print(f"Error saving coverage report: {e}")
class MockCoverageTracker:
"""
Mock coverage tracker for demonstration purposes.
Simulates coverage data for testing the infrastructure.
"""
def __init__(self, source_dir: str):
self.source_dir = source_dir
self.enabled = False
def analyze_source_files(self) -> None:
"""Mock analysis - does nothing."""
pass
def start_tracking(self) -> None:
"""Start mock tracking."""
self.enabled = True
def stop_tracking(self) -> None:
"""Stop mock tracking."""
self.enabled = False
def get_coverage_report(self) -> Dict[str, Any]:
"""Return mock coverage data."""
return {
"files": {
"urst/codec.py": {
"total_lines": 45,
"covered_lines": 38,
"total_functions": 8,
"covered_functions": 6,
"line_coverage": 84.4,
"function_coverage": 75.0,
"uncovered_lines": [12, 23, 34, 45, 56, 67, 78],
"uncovered_functions": ["_internal_helper", "_debug_method"],
},
"urst/transport.py": {
"total_lines": 32,
"covered_lines": 30,
"total_functions": 6,
"covered_functions": 6,
"line_coverage": 93.8,
"function_coverage": 100.0,
"uncovered_lines": [15, 28],
"uncovered_functions": [],
},
},
"summary": {
"total_files": 2,
"total_lines": 77,
"covered_lines": 68,
"total_functions": 14,
"covered_functions": 12,
"line_coverage": 88.3,
"function_coverage": 85.7,
},
}
def print_coverage_report(self, detailed: bool = False) -> None:
"""Print mock coverage report."""
tracker = SimpleCoverageTracker("")
tracker.total_lines = {"mock": set()}
tracker.covered_lines = {"mock": set()}
tracker.total_functions = {"mock": set()}
tracker.function_calls = {"mock": set()}
# Override with mock data
report = self.get_coverage_report()
print("\n" + "=" * 80)
print("MOCK COVERAGE REPORT (for demonstration)")
print("=" * 80)
summary = report["summary"]
print(f"Files analyzed: {summary['total_files']}")
print(
f"Line coverage: {summary['covered_lines']}/{summary['total_lines']} ({summary['line_coverage']:.1f}%)"
)
print(
f"Function coverage: {summary['covered_functions']}/{summary['total_functions']} ({summary['function_coverage']:.1f}%)"
)
if detailed:
print("\nPer-file coverage:")
print("-" * 80)
for file_path, file_data in report["files"].items():
print(f"\n{file_path}:")
print(
f" Lines: {file_data['covered_lines']}/{file_data['total_lines']} ({file_data['line_coverage']:.1f}%)"
)
print(
f" Functions: {file_data['covered_functions']}/{file_data['total_functions']} ({file_data['function_coverage']:.1f}%)"
)
if file_data["uncovered_functions"]:
print(
f" Uncovered functions: {', '.join(file_data['uncovered_functions'])}"
)
print("=" * 80)
def create_coverage_tracker(source_dir: str, mock: bool = False) -> Any:
"""
Create appropriate coverage tracker.
Args:
source_dir: Directory containing source code
mock: Use mock tracker for demonstration
Returns:
Coverage tracker instance
"""
if mock:
return MockCoverageTracker(source_dir)
else:
return SimpleCoverageTracker(source_dir)
if __name__ == "__main__":
# Demo the coverage tracker
print("Coverage Tracker Demo")
# Use mock tracker for demonstration
tracker = create_coverage_tracker("../", mock=True)
tracker.start_tracking()
# Simulate some coverage
tracker.print_coverage_report(detailed=True)
tracker.stop_tracking()