Open
【11月贡献大赛-缺陷修复】fix(analyse-coverage): [Bug] fix uncovered function line count, missing start_line TypeError, and list exit code in analyze_function_coverage.py #7332
【11月贡献大赛-缺陷修复】fix(analyse-coverage): [Bug] fix uncovered function line count, missing start_line TypeError, and list exit code in analyze_function_coverage.py #7332
Open
liuhongweiAdd on 10 hours ago
Total: 2 files changed+145-31
@@ -4,23 +4,56 @@ import argparse
4 4 
5def calculate_function_lines(file_path, start_line, executed_lines, missing_lines):5def calculate_function_lines(file_path, start_line, executed_lines, missing_lines):
6 """计算函数的代码行数"""6 """计算函数的代码行数"""
7- if executed_lines:7+ all_lines = [
8- end_line = max(executed_lines + missing_lines)8+ ln for ln in (executed_lines or []) + (missing_lines or [])
9- code_lines = end_line - start_line + 19+ if isinstance(ln, int) and not isinstance(ln, bool)
10- else:10+ ]
11- code_lines = 011+ if not all_lines:
12- return code_lines12+ return 0
13+ begin = (
14+ start_line
15+ if isinstance(start_line, int) and not isinstance(start_line, bool)
16+ else min(all_lines)
17+ )
18+ return max(0, max(all_lines) - begin + 1)
19+ 
20+ 
21+def _load_coverage_files(coverage_file):
22+ """安全加载 coverage.json 并校验顶层 files 映射。"""
23+ try:
24+ with open(coverage_file, 'r', encoding="utf-8") as f:
25+ data = json.load(f)
26+ except (OSError, json.JSONDecodeError) as exc:
27+ print(f"❌ 无法加载覆盖率文件 {coverage_file}: {exc}")
28+ return None
29+ if not isinstance(data, dict) or not isinstance(data.get('files'), dict):
30+ print(f"❌ 覆盖率文件格式无效(缺少 files 映射): {coverage_file}")
31+ return None
32+ return data['files']
33+ 
34+ 
35+def _resolve_file_entry(files_map, file_path):
36+ """按精确路径或统一 '/' 分隔符查找文件覆盖率条目。"""
37+ if file_path in files_map:
38+ return file_path, files_map[file_path]
39+ norm_target = file_path.replace('\\', '/')
40+ for key, entry in files_map.items():
41+ if key.replace('\\', '/') == norm_target:
42+ return key, entry
43+ return None, None
44+ 
13 45 
14def analyze_function_coverage(coverage_file, file_path, function_name):46def analyze_function_coverage(coverage_file, file_path, function_name):
15 """分析指定函数的覆盖率"""47 """分析指定函数的覆盖率"""
16- with open(coverage_file, 'r', encoding="utf-8") as f:48+ files_map = _load_coverage_files(coverage_file)
17- data = json.load(f)49+ if files_map is None:
18- 50+ return None
19- if file_path not in data['files']:51+ 
52+ matched_path, file_data = _resolve_file_entry(files_map, file_path)
53+ if file_data is None:
20 print(f"❌ 未找到文件: {file_path}")54 print(f"❌ 未找到文件: {file_path}")
21 return None55 return None
22- 56+ file_path = matched_path
23- file_data = data['files'][file_path]
24 functions = file_data.get('functions', {})57 functions = file_data.get('functions', {})
25 58
26 if function_name not in functions:59 if function_name not in functions:
@@ -106,30 +139,33 @@ def analyze_function_coverage(coverage_file, file_path, function_name):
106 139 
107def list_all_functions(coverage_file, file_path):140def list_all_functions(coverage_file, file_path):
108 """列出文件中的所有函数"""141 """列出文件中的所有函数"""
109- with open(coverage_file, 'r', encoding="utf-8") as f:142+ files_map = _load_coverage_files(coverage_file)
110- data = json.load(f)143+ if files_map is None:
111- 144+ return False
112- if file_path not in data['files']:145+ 
146+ matched_path, file_data = _resolve_file_entry(files_map, file_path)
147+ if file_data is None:
113 print(f"❌ 未找到文件: {file_path}")148 print(f"❌ 未找到文件: {file_path}")
114- return149+ return False
115- 150+ 
116- file_data = data['files'][file_path]
117 functions = file_data.get('functions', {})151 functions = file_data.get('functions', {})
118- 152+ 
119- print(f"\n📋 文件 {file_path} 中的所有函数:")153+ print(f"\n📋 文件 {matched_path} 中的所有函数:")
120 print("=" * 80)154 print("=" * 80)
121- 155+ 
122 for i, (func_name, func_data) in enumerate(functions.items(), 1):156 for i, (func_name, func_data) in enumerate(functions.items(), 1):
123 summary = func_data.get('summary', {})157 summary = func_data.get('summary', {})
124 percent_covered = summary.get('percent_covered', 0.0)158 percent_covered = summary.get('percent_covered', 0.0)
125 covered_lines = summary.get('covered_lines', 0)159 covered_lines = summary.get('covered_lines', 0)
126 num_statements = summary.get('num_statements', 0)160 num_statements = summary.get('num_statements', 0)
127- 161+ 
128 print(f"{i:3d}. {func_name}")162 print(f"{i:3d}. {func_name}")
129 print(f" 覆盖率: {percent_covered:6.2f}% | 已覆盖: {covered_lines:3d}/{num_statements:3d}")163 print(f" 覆盖率: {percent_covered:6.2f}% | 已覆盖: {covered_lines:3d}/{num_statements:3d}")
130- 164+ 
131 print("=" * 80)165 print("=" * 80)
132 print(f"总计: {len(functions)} 个函数")166 print(f"总计: {len(functions)} 个函数")
167+ return True
168+ 
133 169 
134def main():170def main():
135 parser = argparse.ArgumentParser(171 parser = argparse.ArgumentParser(
@@ -139,25 +175,26 @@ def main():
139示例用法:175示例用法:
140 # 分析特定函数的覆盖率176 # 分析特定函数的覆盖率
141 python analyze_function_coverage.py -f mindspeed_llm/core/models/common/rms_norm.py -n rms_norm_forward177 python analyze_function_coverage.py -f mindspeed_llm/core/models/common/rms_norm.py -n rms_norm_forward
142- 178+ 
143 # 列出文件中的所有函数179 # 列出文件中的所有函数
144 python analyze_function_coverage.py -f mindspeed_llm/core/models/common/rms_norm.py -l180 python analyze_function_coverage.py -f mindspeed_llm/core/models/common/rms_norm.py -l
145 """181 """
146 )182 )
147- 183+ 
148- parser.add_argument('-f', '--file', required=True, 184+ parser.add_argument('-f', '--file', required=True,
149 help='Python文件路径(相对于项目根目录)')185 help='Python文件路径(相对于项目根目录)')
150- parser.add_argument('-n', '--function', 186+ parser.add_argument('-n', '--function',
151 help='函数名称')187 help='函数名称')
152 parser.add_argument('-l', '--list', action='store_true',188 parser.add_argument('-l', '--list', action='store_true',
153 help='列出文件中的所有函数')189 help='列出文件中的所有函数')
154 parser.add_argument('-c', '--coverage', default='COVERAGE/report/coverage.json',190 parser.add_argument('-c', '--coverage', default='COVERAGE/report/coverage.json',
155 help='覆盖率数据文件路径(默认: COVERAGE/report/coverage.json)')191 help='覆盖率数据文件路径(默认: COVERAGE/report/coverage.json)')
156- 192+ 
157 args = parser.parse_args()193 args = parser.parse_args()
158- 194+ 
159 if args.list:195 if args.list:
160- list_all_functions(args.coverage, args.file)196+ if not list_all_functions(args.coverage, args.file):
197+ sys.exit(1)
161 elif args.function:198 elif args.function:
162 result = analyze_function_coverage(args.coverage, args.file, args.function)199 result = analyze_function_coverage(args.coverage, args.file, args.function)
163 if result is None:200 if result is None:
@@ -0,0 +1,77 @@
1+import json
2+import subprocess
3+import sys
4+from pathlib import Path
5+ 
6+SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts"
7+sys.path.insert(0, str(SCRIPT_DIR))
8+ 
9+import analyze_function_coverage as afc # noqa: E402
10+ 
11+ 
12+def _write_cov(tmp_path: Path, payload: dict) -> Path:
13+ cov = tmp_path / "coverage.json"
14+ cov.write_text(json.dumps(payload), encoding="utf-8")
15+ return cov
16+ 
17+ 
18+def test_uncovered_function_and_missing_start_line():
19+ assert afc.calculate_function_lines("a.py", 10, [], [10, 11, 12]) == 3
20+ assert afc.calculate_function_lines("a.py", "N/A", [20], [22, 23]) == 4
21+ assert afc.calculate_function_lines("a.py", "N/A", [], []) == 0
22+ 
23+ 
24+def test_windows_path_lookup_and_uncovered_analysis(tmp_path: Path):
25+ cov = _write_cov(
26+ tmp_path,
27+ {
28+ "files": {
29+ "pkg/mod.py": {
30+ "functions": {
31+ "uncovered_fn": {
32+ "start_line": 10,
33+ "executed_lines": [],
34+ "missing_lines": [10, 11, 12],
35+ "excluded_lines": [],
36+ "summary": {
37+ "covered_lines": 0,
38+ "num_statements": 3,
39+ "percent_covered": 0.0,
40+ },
41+ }
42+ }
43+ }
44+ }
45+ },
46+ )
47+ res = afc.analyze_function_coverage(str(cov), r"pkg\mod.py", "uncovered_fn")
48+ assert res is not None
49+ assert res["code_lines"] == 3
50+ 
51+ 
52+def test_cli_list_exit_codes_and_invalid_json(tmp_path: Path):
53+ script = SCRIPT_DIR / "analyze_function_coverage.py"
54+ cov = _write_cov(tmp_path, {"files": {"a.py": {"functions": {"f": {"summary": {}}}}}})
55+ 
56+ ok = subprocess.run(
57+ [sys.executable, str(script), "-c", str(cov), "-f", "a.py", "-l"],
58+ capture_output=True,
59+ text=True,
60+ )
61+ assert ok.returncode == 0
62+ 
63+ missing_file = subprocess.run(
64+ [sys.executable, str(script), "-c", str(cov), "-f", "missing.py", "-l"],
65+ capture_output=True,
66+ text=True,
67+ )
68+ assert missing_file.returncode == 1
69+ 
70+ bad_cov = tmp_path / "bad.json"
71+ bad_cov.write_text("{not-json", encoding="utf-8")
72+ bad_run = subprocess.run(
73+ [sys.executable, str(script), "-c", str(bad_cov), "-f", "a.py", "-l"],
74+ capture_output=True,
75+ text=True,
76+ )
77+ assert bad_run.returncode == 1